diff --git a/docs/examples/camoes_flight_sim.ipynb b/docs/examples/camoes_flight_sim.ipynb index c1c0824e9..66ac0bf9d 100644 --- a/docs/examples/camoes_flight_sim.ipynb +++ b/docs/examples/camoes_flight_sim.ipynb @@ -347,7 +347,7 @@ }, { "cell_type": "code", - "execution_count": 70, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -356,7 +356,6 @@ "\n", "def controller_function(context):\n", " time = context.time\n", - " air_brakes = context.controlled.air_brakes\n", "\n", " new_deployment_level = 0\n", "\n", @@ -376,14 +375,12 @@ " if time < 3.8:\n", " new_deployment_level = 0\n", "\n", - " air_brakes.deployment_level = new_deployment_level\n", - "\n", - " return time, air_brakes.deployment_level" + " context.controls.air_brakes.deployment_level = new_deployment_level" ] }, { "cell_type": "code", - "execution_count": 71, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -526,9 +523,9 @@ " sampling_rate=10,\n", " reference_area=None,\n", " clamp=True,\n", - " initial_observed_variables=(0, 0),\n", " override_rocket_drag=True,\n", " name=\"Air Brakes\",\n", + " position=0.0, # where the air brakes are, in meters\n", ")" ] }, @@ -616,46 +613,12 @@ }, { "cell_type": "code", - "execution_count": 75, + "execution_count": null, "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/tmp/ipykernel_41946/613100350.py:5: DeprecationWarning: Controller observed variables are no longer supported. and will be removed in v1.13.0. Use `Access the desired variables via controller.log` instead.\n", - " obs_vars = test_flight.get_controller_observed_variables()\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAjcAAAHHCAYAAABDUnkqAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjgsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvwVt1zgAAAAlwSFlzAAAPYQAAD2EBqD+naQAATm9JREFUeJzt3XtcVHXeB/DPMAwDyE1FwAuKeclMVJQkyrIUJTXNylIzUSy76abydBFLXGxNbcvM8pKWmqvlbc0t11RCzdw1FQ0va96voYCIyE2GYeb3/DFxcAKVYQ6cMzOf9+vl69k5c87Md37MPvPZ3+1ohBACRERERE7CTekCiIiIiOTEcENEREROheGGiIiInArDDRERETkVhhsiIiJyKgw3RERE5FQYboiIiMipMNwQERGRU2G4ISIiIqfCcEOkco888ggeeeQRpcsgO2g0Gvz1r3+97Tk7duyARqPBunXr6qaoO+D3jhwZww3RLSxbtgwajUb65+npiSZNmiA2NhZz585FQUGB0iU6rUuXLuGvf/0r0tPTq3V++d8qLS2tdgtzYOfOnbP6Pt/u37lz55Qul8gu7koXQKR206ZNQ8uWLWE0GpGZmYkdO3ZgwoQJmD17Nr777jt07NhR6RKdzqVLl5CcnIywsDB07txZ6XKcQqNGjfCPf/zD6thHH32E33//HR9//HGlc7du3VqX5RHJiuGG6A769u2LyMhI6XFiYiK2bduGxx9/HAMHDsRvv/0GLy8vBSskurN69erh+eeftzq2atUqXLt2rdJxIkfHYSmiGujZsyemTJmC8+fPY8WKFVbPHTt2DIMHD0aDBg3g6emJyMhIfPfdd1bnlA+j7Ny5Ey+//DIaNmwIPz8/xMXF4dq1a3d8/+zsbLzwwgsIDg6Gp6cnOnXqhK+++kp6XgiBsLAwPPHEE5WuLSkpgb+/P15++WUAFXM91qxZg+TkZDRt2hS+vr4YPHgwrl+/DoPBgAkTJiAoKAg+Pj6Ij4+HwWCo9LorVqxA165d4eXlhQYNGmDo0KG4ePGi1TmPPPIIOnTogKNHj+LRRx+Ft7c3mjZtig8++EA6Z8eOHbjvvvsAAPHx8dJQybJly+7YLneSkZGB0aNHIzg4GHq9Hvfeey+WLFkiPZ+VlQV3d3ckJydXuvb48ePQaDT47LPPpGN5eXmYMGECQkNDodfr0bp1a8yaNQtms7nGNZpMJkyePBkhISGoV68eBg4caNWOU6dOhU6nw5UrVypd+9JLLyEgIAAlJSU1fv9yf55zU5ffEyK7CSKq0tKlSwUAsW/fviqfv3jxogAgBg8eLB07cuSI8Pf3F+3btxezZs0Sn332mXj44YeFRqMR69evr/Ta4eHh4qGHHhJz584VY8eOFW5ubuLhhx8WZrNZOrdHjx6iR48e0uPi4mJxzz33CJ1OJyZOnCjmzp0rHnroIQFAzJkzRzrvnXfeETqdTly9etWq7jVr1ggAYufOnUIIIbZv3y4AiM6dO4vo6Ggxd+5c8frrrwuNRiOGDh0qnnvuOdG3b18xb948MWLECAFAJCcnW73m3/72N6HRaMSQIUPE/PnzRXJysggMDBRhYWHi2rVrVp+lSZMmIjQ0VIwfP17Mnz9f9OzZUwAQmzZtEkIIkZmZKaZNmyYAiJdeekn84x//EP/4xz/E6dOna/y3Kn/dZs2aidDQUDFt2jSxYMECMXDgQAFAfPzxx9J5PXv2FO3bt690fXJystBqtSIzM1MIIURRUZHo2LGjaNiwoZg8ebJYuHChiIuLExqNRowfP97qWgBi6tSpt6xNiIq/Q3h4uOjYsaOYPXu2mDRpkvD09BRt27YVxcXFQgghTp48KQCITz/91Op6g8Eg6tevL0aPHn3b97lZ//79RYsWLap87s/fu7r8nhDZi+GG6Baq84Pp7+8vIiIipMe9evUS4eHhoqSkRDpmNpvFAw88INq0aVPptbt27SpKS0ul4x988IEAIP71r39Jx/78IzNnzhwBQKxYsUI6VlpaKqKjo4WPj4/Iz88XQghx/PhxAUAsWLDAquaBAweKsLAwKUCV/2h16NDBqpZhw4YJjUYj+vbta3V9dHS01Q/iuXPnhFarFdOnT7c67/Dhw8Ld3d3qeI8ePQQAsXz5cumYwWAQISEh4umnn5aO7du3TwAQS5cuFdVRnb/VCy+8IBo3bixycnKsjg8dOlT4+/tL4eHzzz8XAMThw4etzmvfvr3o2bOn9Pi9994T9erVEydOnLA6b9KkSUKr1YoLFy5Ix2wJN02bNpX+hkJUhNFPPvlEOhYdHS2ioqKsrl+/fr0AILZv337b97lZTcJNXXxPiOzFYSkiO/j4+EirpnJzc7Ft2zY8++yzKCgoQE5ODnJycnD16lXExsbi5MmTyMjIsLr+pZdegk6nkx6/+uqrcHd3x6ZNm275nps2bUJISAiGDRsmHdPpdHj99ddRWFiIn376CQDQtm1bREVFYeXKldJ5ubm5+OGHHzB8+HBoNBqr142Li7OqJSoqCkIIjB492uq8qKgoXLx4EWVlZQCA9evXw2w249lnn5U+c05ODkJCQtCmTRts3769UpvdPMfDw8MD3bp1w5kzZ275me0lhMA///lPDBgwAEIIqzpjY2Nx/fp1HDhwAADw1FNPwd3dHatXr5auP3LkCI4ePYohQ4ZIx9auXYuHHnoI9evXt3q9mJgYmEwm7Ny5s0a1xsXFwdfXV3o8ePBgNG7c2Oo7ERcXhz179uD06dPSsZUrVyI0NBQ9evSo0fvaUl9dfE+I7MEJxUR2KCwsRFBQEADg1KlTEEJgypQpmDJlSpXnZ2dno2nTptLjNm3aWD3v4+ODxo0b33Yp7vnz59GmTRu4uVn/b5N77rlHer5cXFwcxo0bh/Pnz6NFixZYu3YtjEYjRowYUel1mzdvbvXY398fABAaGlrpuNlsxvXr19GwYUOcPHkSQohKn6XczT+EANCsWbNKwap+/fo4dOjQLT+zva5cuYK8vDwsWrQIixYtqvKc7OxsAEBgYCB69eqFNWvW4L333gMArF69Gu7u7njqqaek80+ePIlDhw6hUaNGt309W/25HTUaDVq3bm31nRgyZAgmTJiAlStXIikpCdevX8fGjRsxceLESm0rt7r6nhDZg+GGqIZ+//13XL9+Ha1btwYAaRLpG2+8gdjY2CqvKT+3rgwdOhQTJ07EypUrMXnyZKxYsQKRkZG4++67K52r1WqrfI1bHRdCALB8bo1Ggx9++KHKc318fGx6vdpQ/rd5/vnnMXLkyCrPuXlJ/9ChQxEfH4/09HR07twZa9asQa9evRAYGGj1mr1798Zbb71V5eu1bdtWxk9grX79+nj88celcLNu3ToYDIY6WfVUV98TInsw3BDVUPmeIeVB5q677gJg+V+gMTEx1XqNkydP4tFHH5UeFxYW4vLly+jXr98tr2nRogUOHToEs9ls1Xtz7Ngx6flyDRo0QP/+/bFy5UoMHz4c//nPfzBnzpzqfcBqatWqFYQQaNmypWw/6HL3PjRq1Ai+vr4wmUzV+tsMGjQIL7/8sjQ0deLECSQmJlqd06pVKxQWFlb7b11dJ0+etHoshMCpU6cq7acUFxeHJ554Avv27cPKlSsRERGBe++9V9Za5FQb3xOiW+GcG6Ia2LZtG9577z20bNkSw4cPBwAEBQXhkUceweeff47Lly9XuqaqpbuLFi2C0WiUHi9YsABlZWXo27fvLd+7X79+yMzMtJoTUlZWhk8//RQ+Pj6V5lyMGDECR48exZtvvgmtVouhQ4fa/Hlv56mnnoJWq0VycnKl3hchBK5evWrza9arVw+AZam1HLRaLZ5++mn885//xJEjRyo9/+e/TUBAAGJjY7FmzRqsWrUKHh4eGDRokNU5zz77LHbv3o0tW7ZUer28vDxpromtli9fbrX79bp163D58uVK34m+ffsiMDAQs2bNwk8//aT6vWpq43tCdCvsuSG6gx9++AHHjh1DWVkZsrKysG3bNqSkpKBFixb47rvv4OnpKZ07b948dO/eHeHh4RgzZgzuuusuZGVlYffu3fj9999x8OBBq9cuLS1Fr1698Oyzz+L48eOYP38+unfvjoEDB96ynpdeegmff/45Ro0ahf379yMsLAzr1q2TemVunowKAP3790fDhg2xdu1a9O3bV5ojJJdWrVrhb3/7GxITE3Hu3DkMGjQIvr6+OHv2LL799lu89NJLeOONN2x+zYCAACxcuBC+vr6oV68eoqKi0LJly9tet2TJEmzevLnS8fHjx2PmzJnYvn07oqKiMGbMGLRv3x65ubk4cOAAfvzxR+Tm5lpdM2TIEDz//POYP38+YmNjERAQYPX8m2++ie+++w6PP/44Ro0aha5du6KoqAiHDx/GunXrcO7cOathrOpq0KABunfvjvj4eGRlZWHOnDlo3bo1xowZY3WeTqfD0KFD8dlnn0Gr1VpNMFej2vieEN0Kww3RHSQlJQGwrOpp0KABwsPDMWfOHMTHx1cKEu3bt0daWhqSk5OxbNkyXL16FUFBQYiIiJBe52afffaZNG/CaDRi2LBhmDt37m2HZby8vLBjxw5MmjQJX331FfLz83H33Xdj6dKlGDVqVKXzPTw8MGTIEMyfP7/KicRymDRpEtq2bYuPP/5Y2gAvNDQUffr0uW1QuxWdToevvvoKiYmJeOWVV1BWVoalS5feMdwsWLCgyuOjRo1Cs2bNsHfvXkybNg3r16/H/Pnz0bBhQ9x7772YNWtWpWsGDhwILy8vFBQUWK2SKuft7Y2ffvoJ77//PtauXYvly5fDz88Pbdu2RXJysjTR1laTJ0/GoUOHMGPGDBQUFKBXr16YP38+vL29K50bFxeHzz77DL169ULjxo1r9H51Se7vCdGtaERtzuIjoiotW7YM8fHx2Ldvn9WtHWrLxIkT8eWXXyIzM7PKH0lyTAcPHkTnzp2xfPnyWguuRI6Ic26InFxJSQlWrFiBp59+msHGySxevBg+Pj5WS9SJiMNSRE4rOzsbP/74I9atW4erV69i/PjxSpdEMvn+++9x9OhRLFq0COPGjZMmYBORBcMNkZM6evQohg8fjqCgIMydOxedO3dWuiSSyV/+8hdkZWWhX79+Vd7kk8jVcc4NERERORXOuSEiIiKnwnBDRERETsXl5tyYzWZcunQJvr6+tX6DOSIiIpKHEAIFBQVo0qRJpRsH/5nLhZtLly5VunstEREROYaLFy+iWbNmtz3H5cJN+Y6yFy9ehJ+fn2yvazQasXXrVvTp0wc6nU6213VFbEt5sB3lwXaUB9tRHq7cjvn5+QgNDa20M3xVXC7clA9F+fn5yR5uvL294efn53JfOLmxLeXBdpQH21EebEd5sB1RrSklnFBMREREToXhhoiIiJwKww0RERE5FYYbIiIicioMN0RERORUGG6IiIjIqTDcEBERkVNhuCEiIiKnwnBDREREToXhhoiIiJyKouFm586dGDBgAJo0aQKNRoMNGzbc8ZodO3agS5cu0Ov1aN26NZYtW1brdRIREZHjUDTcFBUVoVOnTpg3b161zj979iz69++PRx99FOnp6ZgwYQJefPFFbNmypZYrJSIiIkeh6I0z+/bti759+1b7/IULF6Jly5b46KOPAAD33HMPdu3ahY8//hixsbG1VWadKDOZkXG9RLH3b+DtAV9Pl7uPKhEROSGH+jXbvXs3YmJirI7FxsZiwoQJt7zGYDDAYDBIj/Pz8wFY7qxqNBplq638tWrymkII3P/ZbvyakS9bPbby0rkhbfyDaBNYT7EaytnTllSB7SgPtqM82I7ycOV2tOUzO1S4yczMRHBwsNWx4OBg5Ofn48aNG/Dy8qp0zYwZM5CcnFzp+NatW+Ht7S17jSkpKTZfYxLArxmWEUKdRqAad3OXldEM3DCa8Y9NP+H+wLp979upSVtSZWxHebAd5cF2lIcrtmNxcXG1z3WocFMTiYmJSEhIkB7n5+cjNDQUffr0gZ+fn2zvYzQakZKSgt69e0On09l0bZnJDPy8FQDw+5QY1Pe27Xp79Vy4B7vOXUPniC7oFx5Sp+9dFXvakiqwHeXBdpQH21EertyO5SMv1eFQ4SYkJARZWVlWx7KysuDn51dlrw0A6PV66PX6Ssd1Ol2tfDFq8roaN/NN17vX+RdWq3X7ow6tqv7LUlt/I1fDdpQH21EebEd5uGI72vJ5HWqfm+joaKSmplodS0lJQXR0tEIVyUMo/P5ufwyDmYXSlRAREdlP0XBTWFiI9PR0pKenA7As9U5PT8eFCxcAWIaU4uLipPNfeeUVnDlzBm+99RaOHTuG+fPnY82aNZg4caIS5TsNtz8m+TDcEBGRM1A03KSlpSEiIgIREREAgISEBERERCApKQkAcPnyZSnoAEDLli3x73//GykpKejUqRM++ugjfPHFFw6/DPxmmrqeTQxAK4WbOn9rIiIi2Sk65+aRRx6BuE1vQVW7Dz/yyCP49ddfa7Gquqd0h4nbHxHXxHRDREROwKHm3FDt4LAUERE5E4Yblan7QSkOSxERkXNhuFEBofB6qfLVUhyWIiIiZ8BwQ3Bz47AUERE5D4YblVFgsRSHpYiIyKkw3KiA0h0m5ROKOSxFRETOgOGGuEMxERE5FYYbldEosF6KS8GJiMiZMNwQtG6cc0NERM6D4UYFlM4UXApORETOhOGGOCxFREROheFGZRRZCs5hKSIiciIMNypwu5uH1gVpWIo9N0RE5AQYbqhiWIpdN0RE5AQYblRGkRtncliKiIicCMONCig9GsQJxURE5EwYbohzboiIyKkw3KiMEqulKubc1P17ExERyY3hRgWU7i+pmHOjdCVERET2Y7ghDksREZFTYbhRGY0C41KcUExERM6E4UYFlM4UXApORETOhOGGpGEpbuJHRETOgOFGZZTYxK98WIpzboiIyBkw3BCHpYiIyKkw3KiAUHgxuDQsxZ4bIiJyAgw3VDEsxa4bIiJyAgw3KqPoDsXMNkRE5AQYblRA6dEgLfe5ISIiJ8JwQ3D741vAYSkiInIGDDcqo1FgMTiHpYiIyJkw3KiA0pmCw1JERORMGG6IS8GJiMipMNyojCKrpdy4FJyIiJwHw40KCIV7TLScc0NERE6E4YY4LEVERE6F4UZlFL1xJrtuiIjICTDcEJeCExGRU2G4UQGlM4WWm/gREZETYbgheOm0AIBio0nhSoiIiOzHcKMyGgXWgvvq3QEAhYayOn9vIiIiuTHcqIDSi5R8ysNNKXtuiIjI8THcEHz0lmGpAvbcEBGRE2C4URklloJzWIqIiJwJw40KKL1DsY+HJdwUlZpg5oopIiJycAw3BF9Pd+k/F3HeDREROTiGG5VR4saZnu5u0i0YCks5NEVERI6N4UYFlB4I0mg0FSumOO+GiIgcHMMNAaiYVMwVU0RE5OgYblRGiU38AMDHw7IcvNDAOTdEROTYGG5UQOlN/ICKjfzYc0NERI6O4YYAcK8bIiJyHgw3BIC3YCAiIufBcEMAKubccFiKiIgcHcONCqhgyo20kR+HpYiIyNEx3BCAilswcLUUERE5OsXDzbx58xAWFgZPT09ERUVh7969tz1/zpw5uPvuu+Hl5YXQ0FBMnDgRJSUldVRt7VJoFTgA3hmciIich6LhZvXq1UhISMDUqVNx4MABdOrUCbGxscjOzq7y/K+//hqTJk3C1KlT8dtvv+HLL7/E6tWrMXny5DquXF5K3zgTuGm1FG+/QEREDk7RcDN79myMGTMG8fHxaN++PRYuXAhvb28sWbKkyvP/+9//4sEHH8Rzzz2HsLAw9OnTB8OGDbtjbw/dGW+/QEREzsL9zqfUjtLSUuzfvx+JiYnSMTc3N8TExGD37t1VXvPAAw9gxYoV2Lt3L7p164YzZ85g06ZNGDFixC3fx2AwwGAwSI/z8/MBAEajEUajUaZPA+m1avKaxjJLoNDU8Ho5eFpGpZBfIm+71IQ9bUkV2I7yYDvKg+0oD1duR1s+s2LhJicnByaTCcHBwVbHg4ODcezYsSqvee6555CTk4Pu3btDCIGysjK88sortx2WmjFjBpKTkysd37p1K7y9ve37EFVISUmx+ZpcAwC4AUJg06ZNstdUHSdyLDVczMpRrIY/q0lbUmVsR3mwHeXBdpSHK7ZjcXFxtc9VLNzUxI4dO/D+++9j/vz5iIqKwqlTpzB+/Hi89957mDJlSpXXJCYmIiEhQXqcn5+P0NBQ9OnTB35+frLVZjQakZKSgt69e0On09l07eX8EmDPDkCjQb9+fWWryRb6kzmYeTQN7l6+6NevuyI1lLOnLakC21EebEd5sB3l4crtWD7yUh2KhZvAwEBotVpkZWVZHc/KykJISEiV10yZMgUjRozAiy++CAAIDw9HUVERXnrpJbzzzjtwc6s8hUiv10Ov11c6rtPpauWLUZPX1eksy681Go1iX9aAep4AgCKjSTX/hamtv5GrYTvKg+0oD7ajPFyxHW35vIpNKPbw8EDXrl2RmpoqHTObzUhNTUV0dHSV1xQXF1cKMFqtZbKIGlYc1ZQaSq+4txT3uSEiIsem6LBUQkICRo4cicjISHTr1g1z5sxBUVER4uPjAQBxcXFo2rQpZsyYAQAYMGAAZs+ejYiICGlYasqUKRgwYIAUcqhmePsFIiJyFoqGmyFDhuDKlStISkpCZmYmOnfujM2bN0uTjC9cuGDVU/Puu+9Co9Hg3XffRUZGBho1aoQBAwZg+vTpSn0EWSm4h5+0FNxQZobRZIZOq/j+jkRERDWi+ITicePGYdy4cVU+t2PHDqvH7u7umDp1KqZOnVoHldUdoYK7S5UPSwFAUakJAV4MN0RE5Jj4C0YAAA93N+i0lr6jghIOTRERkeNiuCGJdPNM3oKBiIgcGMONiih540wA8PXkiikiInJ8DDcqoIal4ABXTBERkXNguCEJb55JRETOgOFGRTSKLgavWDHFnhsiInJkDDcqoJZhKYYbIiJyBgw3JPH/Y0LxdS4FJyIiB8ZwoyJKr5by87TclCy/xKhsIURERHZguFEBNexQDLDnhoiInAPDDUn8/gg3+Qw3RETkwBhuVEThUSn4/zEsdZ3DUkRE5MAYblRALaul2HNDRETOgOGGJOVzbvK5FJyIiBwYw42KqGW11PUbHJYiIiLHxXBDEj/23BARkRNguFEBlUy5qVgKfoPhhoiIHBfDDUnKh6VKTWYYykwKV0NERFQzDDcqolF40k35vaUA9t4QEZHjYrhRAbUsBde6aeCj1wLgvBsiInJcDDdkxZ/3lyIiIgfHcKMiSu9QDFSsmOL9pYiIyFEx3KiAWm6cCdzcc8NwQ0REjonhhqz46ct7bjgsRUREjonhRkWU3qEY4P2liIjI8THcqIBaVksBHJYiIiLHx3BDViomFHNYioiIHBPDjYpoVLBeyp/DUkRE5OAYblRARaNSXApOREQOj+GGrHATPyIicnQMN2SFPTdEROToGG5URA1LwblaioiIHB3DjQoIFa0Fl/a5MXBYioiIHJN7dU566qmnqv2C69evr3ExpDxpWOoGe26IiMgxVSvc+Pv713YdBHXcOFMaljKUQQgBjRrGyoiIiGxQrXCzdOnS2q7DpalnUKpinxuTWaDQYIKvZ7W+IkRERKpRozk3ZWVl+PHHH/H555+joKAAAHDp0iUUFhbKWhzVPW8PLTy0lq/FtRulCldDRERkO5v/Z/n58+fx2GOP4cKFCzAYDOjduzd8fX0xa9YsGAwGLFy4sDbqdAlqGALSaDSo761DVoEB124Y0by+0hURERHZxuaem/HjxyMyMhLXrl2Dl5eXdPzJJ59EamqqrMW5ChUtlgIA1PeyzLu5VswVU0RE5Hhs7rn5+eef8d///hceHh5Wx8PCwpCRkSFbYaQcKdzcYLghIiLHY3PPjdlshslkqnT8999/h6+vryxFuSrlB6Us6nuz54aIiByXzeGmT58+mDNnjvRYo9GgsLAQU6dORb9+/eSszWWoaRM/gD03RETk2Gwelvroo48QGxuL9u3bo6SkBM899xxOnjyJwMBAfPPNN7VRI9Wx8nCTW8zVUkRE5HhsDjfNmjXDwYMHsWrVKhw6dAiFhYV44YUXMHz4cKsJxmQ7FSyWAgA08LbMp2LPDREROSKbw01JSQk8PT3x/PPP10Y9pAKcc0NERI7M5jk3QUFBGDlyJFJSUmA2m2ujJpejrhk3nHNDRESOzeZw89VXX6G4uBhPPPEEmjZtigkTJiAtLa02aiOFMNwQEZEjszncPPnkk1i7di2ysrLw/vvv4+jRo7j//vvRtm1bTJs2rTZqdBkqmXLDYSkiInJoNbq3FAD4+voiPj4eW7duxaFDh1CvXj0kJyfLWZvLUNlKcPbcEBGRQ6txuCkpKcGaNWswaNAgdOnSBbm5uXjzzTflrI0UIvXc3DCqbg8eIiKiO7F5tdSWLVvw9ddfY8OGDXB3d8fgwYOxdetWPPzww7VRn0tRw40zgYqeG5NZoMBQBj9PncIVERERVZ/N4ebJJ5/E448/juXLl6Nfv37Q6fjDZy+19Y146bTQu7vBUGbGtWIjww0RETkUm8NNVlYW7yHl5DQaDep76ZBZYMC1G0a0ULogIiIiG9g858bX1xenT5/Gu+++i2HDhiE7OxsA8MMPP+B///uf7AW6EpWMSgGwnndDRETkSGwONz/99BPCw8OxZ88erF+/HoWFhQCAgwcPYurUqbIX6ArUOGlXWjHF5eBERORgbA43kyZNwt/+9jekpKTAw8NDOt6zZ0/88ssvshZHyuFycCIiclQ2h5vDhw/jySefrHQ8KCgIOTk5Nhcwb948hIWFwdPTE1FRUdi7d+9tz8/Ly8PYsWPRuHFj6PV6tG3bFps2bbL5fdVIRaNS0rAU7wxORESOxuZwExAQgMuXL1c6/uuvv6Jp06Y2vdbq1auRkJCAqVOn4sCBA+jUqRNiY2OleTx/Vlpait69e+PcuXNYt24djh8/jsWLF9v8vmqjvkEpoL4X7wxORESOyeZwM3ToULz99tvIzMyERqOB2WzGf/7zH7zxxhuIi4uz6bVmz56NMWPGID4+Hu3bt8fChQvh7e2NJUuWVHn+kiVLkJubiw0bNuDBBx9EWFgYevTogU6dOtn6MegOOOeGiIgclc1Lwd9//32MHTsWoaGhMJlMaN++PUwmE5577jm888471X6d0tJS7N+/H4mJidIxNzc3xMTEYPfu3VVe89133yE6Ohpjx47Fv/71LzRq1AjPPfcc3n77bWi12iqvMRgMMBgM0uP8/HwAgNFohNEo3w93+WvV5DWNZWWVXkdp/npL7s0pMtR5Tfa0JVVgO8qD7SgPtqM8XLkdbfnMNocbDw8PLF68GElJSTh8+DAKCwsRERGBNm3a2PQ6OTk5MJlMCA4OtjoeHByMY8eOVXnNmTNnsG3bNgwfPhybNm3CqVOn8Nprr8FoNN5ypdaMGTOqvOfV1q1b4e3tbVPN1ZGSkmLzNeeKAMANpQaDauYP/Z4FAG44ceEyNm26pEgNNWlLqoztKA+2ozzYjvJwxXYsLi6u9rk2h5tyoaGhCA0NlR4fOnQIkZGRKC2tvQmoZrMZQUFBWLRoEbRaLbp27YqMjAz8/e9/v2W4SUxMREJCgvQ4Pz8foaGh6NOnD/z8/GSrzWg0IiUlBb1797Z51+ZDlwuA/f+BXq9Hv349ZavJHu4nruDj4/sBLz/06/dgnb63PW1JFdiO8mA7yoPtKA9XbsfykZfqqHG4+TMhBEwmU7XPDwwMhFarRVZWltXxrKwshISEVHlN48aNodPprIag7rnnHmRmZqK0tNRqaXo5vV4PvV5f6bhOp6uVL0ZNXlfn/sefQaNRzZc1xM/Sq3W12KhYTbX1N3I1bEd5sB3lwXaUhyu2oy2ft8Z3BbeXh4cHunbtitTUVOmY2WxGamoqoqOjq7zmwQcfxKlTp2A2m6VjJ06cQOPGjasMNo5GTUvBA+tZ2vNKYakqNxkkIiK6FcXCDQAkJCRg8eLF+Oqrr/Dbb7/h1VdfRVFREeLj4wEAcXFxVhOOX331VeTm5mL8+PE4ceIE/v3vf0sTnB2ZUOFi8EY+lnBTajKj0FD9HjkiIiKlVXtY6k5jXQUFBTa/+ZAhQ3DlyhUkJSUhMzMTnTt3xubNm6VJxhcuXICbW0X+Cg0NxZYtWzBx4kR07NgRTZs2xfjx4/H222/b/N50e94e7vDSueGG0YycolL4eso2gklERFSrqv2LFRAQAM1t7uwohLjt87cybtw4jBs3rsrnduzYUelYdHS0097mQU03zgQsQ1MX80qQU1SKlg3lX1lGRERUG6odbrZv316bdbg0tU5pqQg3hjufTEREpBLVDjc9evSozTpIhaRJxUW8vxQRETkORScUkzWNqtZLAYH1LEvocxhuiIjIgTDcqIBah6XKV0wx3BARkSNhuKFbKh+WYrghIiJHwnCjImpcLQVYNvIjIiJyFDaHm9GjR1e5p01RURFGjx4tS1GkDuy5ISIiR2RzuPnqq69w48aNSsdv3LiB5cuXy1KUq1HjDsUAww0RETkmm3YoFkJACIGCggJ4enpKz5lMJmzatAlBQUG1UiQpo9Ef4Sa7kPvcEBGR47B5h2KNRoO2bdtWel6j0SA5OVnW4lyNyqbcINjXshQ8t9iI0jIzPNw5RYuIiNTPph2KhRDo2bMn/vnPf6JBgwbScx4eHmjRogWaNGlSK0U6O7UuBW/o7QGtmwYms0B2oQHNAryULomIiOiObN6h+OzZswgNDbW6oSU5Jzc3DYJ8PHA534CsAoYbIiJyDDbf6rlFixbIy8vD3r17kZ2dDbPZbPV8XFycbMW5GrUtBQeAEF+9Jdxw3g0RETkIm8PN999/j+HDh6OwsBB+fn5WdwLXaDQMNzWg0lEpABXzbjLzGW6IiMgx2Dy29H//938YPXo0CgsLkZeXh2vXrkn/cnNza6NGUlCIr2VVHHtuiIjIUdgcbjIyMvD666/D29u7NupxaRoVjksF+/zRc1PAcENERI7B5nATGxuLtLS02qjFZal1tRQAhPhZwk0Www0RETkIm+fc9O/fH2+++SaOHj2K8PBw6HQ6q+cHDhwoW3GkPPbcEBGRo7E53IwZMwYAMG3atErPaTQamEwm+6tyUeoblGLPDREROR6bw82fl36T/dR6bymgoueG4YaIiByFXTvxlZSUyFUHqVT5UvBrN4wwlLFXjoiI1M/mcGMymfDee++hadOm8PHxwZkzZwAAU6ZMwZdffil7gaSsBt466LSWATP23hARkSOwOdxMnz4dy5YtwwcffAAPDw/peIcOHfDFF1/IWpyrUeFKcGg0GjTxs+x1k3GdPXVERKR+Noeb5cuXY9GiRRg+fDi0Wq10vFOnTjh27JisxbkKNS8FB4Cm/gw3RETkOGq0iV/r1q0rHTebzTAajbIURerSzN9yw8zfGW6IiMgB2Bxu2rdvj59//rnS8XXr1iEiIkKWolyVRpWLwYFmAZaem9/zbihcCRER0Z3ZvBQ8KSkJI0eOREZGBsxmM9avX4/jx49j+fLl2LhxY23U6PRUPirFYSkiInIoNvfcPPHEE/j+++/x448/ol69ekhKSsJvv/2G77//Hr17966NGklhHJYiIiJHYnPPDQA89NBDSElJkbsWl6fG1VIA0OyPnpvfr3NYioiI1K9G4aZcYWFhpR2L/fz87CrIFQmVL5cqH5a6dN0As1nAzU2lKYyIiAg1GJY6e/Ys+vfvj3r16sHf3x/169dH/fr1ERAQgPr169dGjaSwxn6e0GiAUpMZOUWlSpdDRER0Wzb33Dz//PMQQmDJkiUIDg6GRq1jKQ5IrS3p4e6GIB89sgoM+P36DQT9cUsGIiIiNbI53Bw8eBD79+/H3XffXRv1uCSVj0oBsMy7ySow4Pe8EnRppnQ1REREt2bzsNR9992Hixcv1kYtpGKhAZYVUxe41w0REamczT03X3zxBV555RVkZGSgQ4cO0Ol0Vs937NhRtuJcjZqH+O5q6A0AOJtbrHAlREREt2dzuLly5QpOnz6N+Ph46ZhGo4EQAhqNBiaTSdYCSR1aNrCEmzNXGW6IiEjdbA43o0ePRkREBL755htOKJaJA0y5kcINe26IiEjtbA4358+fx3fffVflzTPJed0cbsp76YiIiNTI5gnFPXv2xMGDB2ujFpen5rgQ1sAyoTi/pAzXbvDu70REpF4299wMGDAAEydOxOHDhxEeHl5pQvHAgQNlK85VqH2HYgDw9nBHsK9lr5uzV4vRwNtD6ZKIiIiqZHO4eeWVVwAA06ZNq/QcJxQ7t5YNvC3hJrcYXUMDlC6HiIioSjYPS5nN5lv+Y7Cxj9qnsdzFScVEROQAbA43Z86cqY06XJr6B6UsWv6x181pLgcnIiIVsznctG7dGo8++ihWrFiBkpKS2qiJVOruRvUAAMezCxWuhIiI6NZsDjcHDhxAx44dkZCQgJCQELz88svYu3dvbdTmclQ+KoV2Qb4AgN8YboiISMVsDjedO3fGJ598gkuXLmHJkiW4fPkyunfvjg4dOmD27Nm4cuVKbdTp1BxgsRQAoF2QDwAgq8CAa8WlCldDRERUNZvDTTl3d3c89dRTWLt2LWbNmoVTp07hjTfeQGhoKOLi4nD58mU56yQV8PV0R1N/TwDA8StFCldDRERUtRqHm7S0NLz22mto3LgxZs+ejTfeeAOnT59GSkoKLl26hCeeeELOOl2CI+z6e88fvTe/ZRUoXAkREVHVbN7nZvbs2Vi6dCmOHz+Ofv36Yfny5ejXrx/c3Cw5qWXLlli2bBnCwsLkrtVpCYdZL2UZmvrxZA6Ocd4NERGplM3hZsGCBRg9ejRGjRqFxo0bV3lOUFAQvvzyS7uLI/VpJ/XcMNwQEZE62RxuTp48ecdzPDw8MHLkyBoV5MocYFQK7UMsK6aOZHJYioiI1MnmcAMAeXl5+PLLL/Hbb78BAO69916MHj0a/v7+shZH6tO5iR8Ayy7F14pLUZ/3mCIiIpWxeUJxWloaWrVqhY8//hi5ubnIzc3F7Nmz0apVKxw4cKA2anR6jrIUHADqe3ug5R+3Yfg1I1/haoiIiCqzOdxMnDgRAwcOxLlz57B+/XqsX78eZ8+exeOPP44JEybUQomkNl2bWXro9v+ep2whREREVahRz83bb78Nd/eKES13d3e89dZbSEtLk7U4V+MAU24AVISbA79fV7gSIiKiymwON35+frhw4UKl4xcvXoSvr68sRbkaBxqVAgB0kXpuGG6IiEh9bA43Q4YMwQsvvIDVq1fj4sWLuHjxIlatWoUXX3wRw4YNq1ER8+bNQ1hYGDw9PREVFVXte1WtWrUKGo0GgwYNqtH7Us10aWoJNydzipDL2zAQEZHK2Lxa6sMPP4RGo0FcXBzKysoAADqdDq+++ipmzpxpcwGrV69GQkICFi5ciKioKMyZMwexsbE4fvw4goKCbnnduXPn8MYbb+Chhx6y+T3VyhF2KAaAQB892gX54Fh2IXaevopB4VXvd0RERKQEm3tuPDw88Mknn+DatWtIT09Heno6cnNz8fHHH0Ov19tcwOzZszFmzBjEx8ejffv2WLhwIby9vbFkyZJbXmMymTB8+HAkJyfjrrvusvk91caRVkuVe7R1QwDA9tNXFa6EiIjIWo3vLeXt7Y3w8HCEh4fD29u7Rq9RWlqK/fv3IyYmpqIgNzfExMRg9+7dt7xu2rRpCAoKwgsvvFCj9yX79WwdCADYfipH4UqIiIisVWtY6qmnnqr2C65fv77a5+bk5MBkMiE4ONjqeHBwMI4dO1blNbt27cKXX36J9PT0ar2HwWCAwWCQHufnW/ZmMRqNMBqN1a71TspfqyavWT68ByFkrak2PdjCMu/m8OUCXLpWhEY+8m3mZ09bUgW2ozzYjvJgO8rDldvRls9crXCjlp2HCwoKMGLECCxevBiBgYHVumbGjBlITk6udHzr1q017nG6nZSUFJuvOXgNANxQUFCATZs2yV5TbQmrp8G5Ig3+vvZHPBJ85/NtVZO2pMrYjvJgO8qD7SgPV2zH4uLiap9brXCzdOnSGhdzO4GBgdBqtcjKyrI6npWVhZCQkErnnz59GufOncOAAQOkY2azGYBlr53jx4+jVatWVtckJiYiISFBepyfn4/Q0FD06dMHfn5+sn0Wo9GIlJQU9O7dGzqdzqZrPU9dBQ7vg6+vL/r16y5bTbVtr/tJvL/tNM5oQ/BBvy6yva49bUkV2I7yYDvKg+0oD1dux/KRl+qo0b2lACA7OxvHjx8HANx99923Xdl0Kx4eHujatStSU1Ol5dxmsxmpqakYN25cpfPbtWuHw4cPWx179913UVBQgE8++QShoaGVrtHr9VVOdNbpdLXyxajJ67prtQAANzeNQ31Zn41oive3ncaWEzm4YQL8POWtvbb+Rq6G7SgPtqM82I7ycMV2tOXz2hxu8vPzMXbsWKxatQomkwkAoNVqMWTIEMybN8/mIayEhASMHDkSkZGR6NatG+bMmYOioiLEx8cDAOLi4tC0aVPMmDEDnp6e6NChg9X1AQEBAFDpONW+jo39cE+wD37LKsSK/Rl47cEwpUsiIiKyfbXUmDFjsGfPHmzcuBF5eXnIy8vDxo0bkZaWhpdfftnmAoYMGYIPP/wQSUlJ6Ny5M9LT07F582ZpkvGFCxdw+fJlm1/XkTjgSnAAln15Xr6/BQBg3n/Owmy+8ycpM5lx9moxrhQa7nguERFRTdjcc7Nx40Zs2bIF3btXzA2JjY3F4sWL8dhjj9WoiHHjxlU5DAUAO3bsuO21y5Ytq9F7kjxG3heKpC3HcTSrEKvSM/Bcl2ZVnpeZX4L3U09h5YHfkVtsmfH+0F0NsODpjrg3hLftICIi+djcc9OwYcMqh578/f1Rv359WYpyVRqHuXVmhQAvHd561DKJ+/++O4rsAuseGUOZCR9sO4U2M7fh011nkVtshN7d8rX7+UwuoufuwgHeXZyIiGRkc7h59913kZCQgMzMTOlYZmYm3nzzTUyZMkXW4lyFI+5QfLOEHq1wb4gvMgsM6LPoFxz4PQ9XCg1YsucC2s3ajrf//RsKDSbcFxqAzWOiUDSjHy5OicFDdzVAgaEMTy1LQ0FJmdIfg4iInITNw1ILFizAqVOn0Lx5czRv3hyAZV6MXq/HlStX8Pnnn0vnHjhwQL5KSbW8dFqsjeuKRxfsxsFL+ej68c9Wzzfx88T0vu0QF9kMbm6W3qlmAV74bnQ3dJm9E2dzizFr+yn8rW87JconIiInY3O44R24a4+D3DezSvcE++KX17vjrY1H8f3/slBSZkb7YB/ERYZi3INhqKev/FUL8NJh9sD2eHJZGmb/dBoJPe5CA2/5djomIiLXZHO4mTp1am3U4dKEw66XshbWwBtr4iJRZjKjzCzgqdPe8ZonOoSgUxM/HLyUjy9+uYC3eraug0qJiMiZ1ejGmXl5efjiiy+QmJiI3NxcAJYhqIyMDFmLI8fkrnWrVrABLMvJxz/UEgCweM8FCEefgERERIqzOdwcOnQIbdu2xaxZs/Dhhx8iLy8PgOWGmYmJiXLX51IceFTKLs90agIvnRtO5RTh14zrSpdDREQOzuZwk5CQgFGjRuHkyZPw9PSUjvfr1w87d+6UtThX4eqdFT56d/S/x7Jp4+r0SwpXQ0REjs7mcLNv374qdyJu2rSp1fJwIlsM7tgYAPD90aw7nElERHR7NocbvV5f5Z05T5w4gUaNGslSlKty5NVS9urRqiEA4LesQpSZzApXQ0REjszmcDNw4EBMmzYNRqNlC32NRoMLFy7g7bffxtNPPy17ga7AxUelAEDatRhgexARkX1sDjcfffQRCgsLERQUhBs3bqBHjx5o3bo1fH19MX369NqokVyA5qZuK1efg0RERPaxeZ8bf39/pKSkYNeuXTh06BAKCwvRpUsXxMTE1EZ9LkXjwuNSN39yZhsiIrKHzeGmXPfu3a3uDE5kj5tzHfe6ISIie9gUbsxmM5YtW4b169fj3Llz0Gg0aNmyJQYPHowRI0a4dM+DPfhjbn1HdLYGERHZo9pzboQQGDhwIF588UVkZGQgPDwc9957L86fP49Ro0bhySefrM06yYUw6xERkT2q3XOzbNky7Ny5E6mpqXj00Uetntu2bRsGDRqE5cuXIy4uTvYiXYUr93ux04+IiORS7Z6bb775BpMnT64UbACgZ8+emDRpElauXClrca6CHRV/nlDMFiEiopqrdrg5dOgQHnvssVs+37dvXxw8eFCWosj1WE8oVq4OIiJyfNUON7m5uQgODr7l88HBwbh27ZosRbkqVx6asdrnRsE6iIjI8VU73JhMJri733qKjlarRVlZmSxFuRr2VPxpWIrtQUREdqj2hGIhBEaNGgW9Xl/l8waDQbaiyPVYDUux74aIiOxQ7XAzcuTIO57DlVL20bjweimrfW6YbYiIyA7VDjdLly6tzTpcGn/LOaGYiIjkY/ONM4lqG4eliIjIHgw3KuLSq6WULoCIiJwGww2pgtVScHbcEBGRHRhuVIA3zvzzDsVEREQ1x3BDqsAJxUREJBeGGxVx5Xkn1jsUM90QEVHNMdyoAHsqrLE9iIjIHgw3pBrlnTfMNkREZA+GGxXRuPJacFQMy3GCNRER2YPhRgX4U26N7UFERPZguCHVcPWeKyIikgfDjYq4+k97xbCUomUQEZGDY7hRAc4xseCEYiIikgPDDamG5o++G4Y9IiKyB8ONirj6lBP23BARkRwYblSAP+YWnHNDRERyYLgh1ZB6bphuiIjIDgw3KuLio1ISRhsiIrIHww2pRvk+N+y4ISIiezDcqAB/zC2kOTeKVkFERI6O4YZUw9VXixERkTwYblTE1W8/wH1uiIhIDgw3KiA4EAOA+9wQEZE8GG5INbjPDRERyYHhRkVcfFSqYrUU+26IiMgODDcqwJ4KC/bcEBGRHBhuSHWYbYiIyB4MNyri4qNSN91+Qdk6iIjIsTHcqAB/yy0qNvFjixARUc0x3JBquPo+P0REJA+GGxVx9R93DksREZEcGG5INXhvKSIikoMqws28efMQFhYGT09PREVFYe/evbc8d/HixXjooYdQv3591K9fHzExMbc93xGwp8KCdwUnIiI5KB5uVq9ejYSEBEydOhUHDhxAp06dEBsbi+zs7CrP37FjB4YNG4bt27dj9+7dCA0NRZ8+fZCRkVHHlZPcKva5YbohIqKaUzzczJ49G2PGjEF8fDzat2+PhQsXwtvbG0uWLKny/JUrV+K1115D586d0a5dO3zxxRcwm81ITU2t48rl59ozbnhvKSIikoei4aa0tBT79+9HTEyMdMzNzQ0xMTHYvXt3tV6juLgYRqMRDRo0qK0yax17KqyxOYiIyB7uSr55Tk4OTCYTgoODrY4HBwfj2LFj1XqNt99+G02aNLEKSDczGAwwGAzS4/z8fACA0WiE0WisYeWVlb9WTV6zzGQCYAk5ctbkaMp7roxlNW9LqmDPd5IqsB3lwXaUhyu3oy2fWdFwY6+ZM2di1apV2LFjBzw9Pas8Z8aMGUhOTq50fOvWrfD29pa9ppSUFJuvSc8GADfkXr2KTZs2yV6TozCUaABo8Msve9Dat2ZtSZWxHeXBdpQH21EertiOxcXF1T5X0XATGBgIrVaLrKwsq+NZWVkICQm57bUffvghZs6ciR9//BEdO3a85XmJiYlISEiQHufn50uTkP38/Oz7ADcxGo1ISUlB7969odPpbLq24OBl4NhBNGzYEP36dZOtJkfjdXAHUFqC+6OikHN0T43akirY852kCmxHebAd5eHK7Vg+8lIdioYbDw8PdO3aFampqRg0aBAASJODx40bd8vrPvjgA0yfPh1btmxBZGTkbd9Dr9dDr9dXOq7T6Wrli1GT13XXagEAGjeNy31Zb1Y+oVjrbvla1tbfyNWwHeXBdpQH21EertiOtnxexYelEhISMHLkSERGRqJbt26YM2cOioqKEB8fDwCIi4tD06ZNMWPGDADArFmzkJSUhK+//hphYWHIzMwEAPj4+MDHx0exzyEHjYuvl+I+N0REJAfFw82QIUNw5coVJCUlITMzE507d8bmzZulScYXLlyAm1vFoq4FCxagtLQUgwcPtnqdqVOn4q9//Wtdli4b/phb8MaZREQkB8XDDQCMGzfulsNQO3bssHp87ty52i+IFMF7SxERkRwU38SPKrj4fTOlYTlmGyIisgfDjQpwGMYaNzUkIiJ7MNyQavD2C0REJAeGGxVx8VGpm26cqWgZRETk4BhuSDWkpeAK10FERI6N4UYF2FNh4eo9V0REJA+GG1KNiqXgTHtERFRzDDcqwqXgFsw2RERkD4YbFeBvuQXn3BARkRwYbkh1OCxFRET2YLhREd440/J/GW2IiMgeDDcqwJ4KC865ISIiOTDckGpwzg0REcmB4UZFuFrKgj1ZRERkD4YbFeBPuYWrhzsiIpIHww2pRvmEaoY9IiKyB8ONirh6z0XFDsXK1kFERI6N4YZUQ5pzw74bIiKyA8ONCrCnwhrbg4iI7MFwQ6rBTfyIiEgODDcqwh2K/5hQzHRDRER2YLhRAf6YW3DODRERyYHhhlSDq6WIiEgODDcq4vJLwV18WI6IiOTBcKMCHIaxYM8NERHJgeGGVKNizg0REVHNMdyoiKsPylSslmK8ISKimmO4UQH+lltjcxARkT0Ybkg1pGEpphsiIrIDw42KaFx8uVTFDsVMN0REVHMMNyrAn3IL9twQEZEcGG5INaQJxQrXQUREjo3hRkVce1CK+9wQEZE8GG5INVw93BERkTwYblSA+7pYVAxLsT2IiKjmGG5INTihmIiI5MBwoyIuvhJcwmxDRET2YLhRAf6YW1RMKGaLEBFRzTHckGpowKXgRERkP4YbFXH1USkuBSciIjkw3KgAf8wtpAnFilZBRESOjuGGVINzboiISA4MNyri8jfOdPmBOSIikgPDjQpw0zoLzrkhIiI5MNyQakjhRtkyiIjIwTHcqIiLj0pVYNcNERHZgeFGBfhbbsF9boiISA4MN6QanHNDRERyYLgh1eA+N0REJAeGGxVx9Sk35Uvhuc8NERHZg+FGBfhTbsGeGyIikgPDDakGV4sREZEcGG5UhDsUW3BUioiI7MFwowL8MbfGHZuJiMgeDDekGhUTihUuhIiIHBrDjYq49qAUb79ARETyYLhRAS59tuCcGyIikoMqws28efMQFhYGT09PREVFYe/evbc9f+3atWjXrh08PT0RHh6OTZs21VGlVJukYSn23RARkR0UDzerV69GQkICpk6digMHDqBTp06IjY1FdnZ2lef/97//xbBhw/DCCy/g119/xaBBgzBo0CAcOXKkjiuXn4svlmLPDRERycJd6QJmz56NMWPGID4+HgCwcOFC/Pvf/8aSJUswadKkSud/8skneOyxx/Dmm28CAN577z2kpKTgs88+w8KFC+u09psZyszILgHOX7sBnbvRpmuvFtt2vrMqD3dXi43wrmFbUgVjWVmNv5NUge0oD7ajPBylHfXubgjx81Ts/RUNN6Wlpdi/fz8SExOlY25uboiJicHu3burvGb37t1ISEiwOhYbG4sNGzZUeb7BYIDBYJAe5+fnAwCMRiOMRvm+GGkXcvHSXjdg7081fg2zWchak6Mpn3v03o+nANjXllSO7SgPtqM82I7yUH873t88ADtfu1/W17Tl91HRcJOTkwOTyYTg4GCr48HBwTh27FiV12RmZlZ5fmZmZpXnz5gxA8nJyZWOb926Fd7e3jWsvLIT+YCHW83Hldw1QHPjJWzadEm2mhxN81KgnrsGRrPSlRARkT0Krl+TfT5scXFxtc9VfFiqtiUmJlr19OTn5yM0NBR9+vSBn5+fbO/T22hEW78U9O7dGzqdTrbXdSX9AMyEJZ2npLAt7cV2lAfbUR5sR3m4cjuWj7xUh6LhJjAwEFqtFllZWVbHs7KyEBISUuU1ISEhNp2v1+uh1+srHdfpdLXyxait13VFbEt5sB3lwXaUB9tRHq7YjrZ8XkVXS3l4eKBr165ITU2VjpnNZqSmpiI6OrrKa6Kjo63OB4CUlJRbnk9ERESuRfFhqYSEBIwcORKRkZHo1q0b5syZg6KiImn1VFxcHJo2bYoZM2YAAMaPH48ePXrgo48+Qv/+/bFq1SqkpaVh0aJFSn4MIiIiUgnFw82QIUNw5coVJCUlITMzE507d8bmzZulScMXLlyAm1tFB9MDDzyAr7/+Gu+++y4mT56MNm3aYMOGDejQoYNSH4GIiIhURPFwAwDjxo3DuHHjqnxux44dlY4988wzeOaZZ2q5KiIiInJEiu9QTERERCQnhhsiIiJyKgw3RERE5FQYboiIiMipMNwQERGRU2G4ISIiIqfCcENEREROheGGiIiInArDDRERETkVVexQXJeEEABsu3V6dRiNRhQXFyM/P9/l7tQqN7alPNiO8mA7yoPtKA9Xbsfy3+3y3/HbcblwU1BQAAAIDQ1VuBIiIiKyVUFBAfz9/W97jkZUJwI5EbPZjEuXLsHX1xcajUa2183Pz0doaCguXrwIPz8/2V7XFbEt5cF2lAfbUR5sR3m4cjsKIVBQUIAmTZpY3VC7Ki7Xc+Pm5oZmzZrV2uv7+fm53BeutrAt5cF2lAfbUR5sR3m4ajveqcemHCcUExERkVNhuCEiIiKnwnAjE71ej6lTp0Kv1ytdisNjW8qD7SgPtqM82I7yYDtWj8tNKCYiIiLnxp4bIiIicioMN0RERORUGG6IiIjIqTDcEBERkVNhuJHJvHnzEBYWBk9PT0RFRWHv3r1Kl6RqM2bMwH333QdfX18EBQVh0KBBOH78uNU5JSUlGDt2LBo2bAgfHx88/fTTyMrKUqhixzBz5kxoNBpMmDBBOsZ2rJ6MjAw8//zzaNiwIby8vBAeHo60tDTpeSEEkpKS0LhxY3h5eSEmJgYnT55UsGL1MZlMmDJlClq2bAkvLy+0atUK7733ntW9gNiOVdu5cycGDBiAJk2aQKPRYMOGDVbPV6fdcnNzMXz4cPj5+SEgIAAvvPACCgsL6/BTqIggu61atUp4eHiIJUuWiP/9739izJgxIiAgQGRlZSldmmrFxsaKpUuXiiNHjoj09HTRr18/0bx5c1FYWCid88orr4jQ0FCRmpoq0tLSxP333y8eeOABBatWt71794qwsDDRsWNHMX78eOk42/HOcnNzRYsWLcSoUaPEnj17xJkzZ8SWLVvEqVOnpHNmzpwp/P39xYYNG8TBgwfFwIEDRcuWLcWNGzcUrFxdpk+fLho2bCg2btwozp49K9auXSt8fHzEJ598Ip3Ddqzapk2bxDvvvCPWr18vAIhvv/3W6vnqtNtjjz0mOnXqJH755Rfx888/i9atW4thw4bV8SdRB4YbGXTr1k2MHTtWemwymUSTJk3EjBkzFKzKsWRnZwsA4qeffhJCCJGXlyd0Op1Yu3atdM5vv/0mAIjdu3crVaZqFRQUiDZt2oiUlBTRo0cPKdywHavn7bffFt27d7/l82azWYSEhIi///3v0rG8vDyh1+vFN998UxclOoT+/fuL0aNHWx176qmnxPDhw4UQbMfq+nO4qU67HT16VAAQ+/btk8754YcfhEajERkZGXVWu1pwWMpOpaWl2L9/P2JiYqRjbm5uiImJwe7duxWszLFcv34dANCgQQMAwP79+2E0Gq3atV27dmjevDnbtQpjx45F//79rdoLYDtW13fffYfIyEg888wzCAoKQkREBBYvXiw9f/bsWWRmZlq1o7+/P6KiotiON3nggQeQmpqKEydOAAAOHjyIXbt2oW/fvgDYjjVVnXbbvXs3AgICEBkZKZ0TExMDNzc37Nmzp85rVprL3ThTbjk5OTCZTAgODrY6HhwcjGPHjilUlWMxm82YMGECHnzwQXTo0AEAkJmZCQ8PDwQEBFidGxwcjMzMTAWqVK9Vq1bhwIED2LdvX6Xn2I7Vc+bMGSxYsAAJCQmYPHky9u3bh9dffx0eHh4YOXKk1FZV/fec7Vhh0qRJyM/PR7t27aDVamEymTB9+nQMHz4cANiONVSddsvMzERQUJDV8+7u7mjQoIFLti3DDSlu7NixOHLkCHbt2qV0KQ7n4sWLGD9+PFJSUuDp6al0OQ7LbDYjMjIS77//PgAgIiICR44cwcKFCzFy5EiFq3Mca9aswcqVK/H111/j3nvvRXp6OiZMmIAmTZqwHalOcVjKToGBgdBqtZVWn2RlZSEkJEShqhzHuHHjsHHjRmzfvh3NmjWTjoeEhKC0tBR5eXlW57Ndre3fvx/Z2dno0qUL3N3d4e7ujp9++glz586Fu7s7goOD2Y7V0LhxY7Rv397q2D333IMLFy4AgNRW/O/57b355puYNGkShg4divDwcIwYMQITJ07EjBkzALAda6o67RYSEoLs7Gyr58vKypCbm+uSbctwYycPDw907doVqamp0jGz2YzU1FRER0crWJm6CSEwbtw4fPvtt9i2bRtatmxp9XzXrl2h0+ms2vX48eO4cOEC2/UmvXr1wuHDh5Geni79i4yMxPDhw6X/zHa8swcffLDSVgQnTpxAixYtAAAtW7ZESEiIVTvm5+djz549bMebFBcXw83N+mdFq9XCbDYDYDvWVHXaLTo6Gnl5edi/f790zrZt22A2mxEVFVXnNStO6RnNzmDVqlVCr9eLZcuWiaNHj4qXXnpJBAQEiMzMTKVLU61XX31V+Pv7ix07dojLly9L/4qLi6VzXnnlFdG8eXOxbds2kZaWJqKjo0V0dLSCVTuGm1dLCcF2rI69e/cKd3d3MX36dHHy5EmxcuVK4e3tLVasWCGdM3PmTBEQECD+9a9/iUOHDoknnniCS5j/ZOTIkaJp06bSUvD169eLwMBA8dZbb0nnsB2rVlBQIH799Vfx66+/CgBi9uzZ4tdffxXnz58XQlSv3R577DEREREh9uzZI3bt2iXatGnDpeBkn08//VQ0b95ceHh4iG7duolffvlF6ZJUDUCV/5YuXSqdc+PGDfHaa6+J+vXrC29vb/Hkk0+Ky5cvK1e0g/hzuGE7Vs/3338vOnToIPR6vWjXrp1YtGiR1fNms1lMmTJFBAcHC71eL3r16iWOHz+uULXqlJ+fL8aPHy+aN28uPD09xV133SXeeecdYTAYpHPYjlXbvn17lf8/ceTIkUKI6rXb1atXxbBhw4SPj4/w8/MT8fHxoqCgQIFPozyNEDdtHUlERETk4DjnhoiIiJwKww0RERE5FYYbIiIicioMN0RERORUGG6IiIjIqTDcEBERkVNhuCEiIiKnwnBDREREToXhhogUN2rUKAwaNEix9x8xYoR0R/A7GTp0KD766KNaroiI7MEdiomoVmk0mts+P3XqVEycOBFCCAQEBNRNUTc5ePAgevbsifPnz8PHx+eO5x85cgQPP/wwzp49C39//zqokIhsxXBDRLUqMzNT+s+rV69GUlKS1R24fXx8qhUqasuLL74Id3d3LFy4sNrX3HfffRg1ahTGjh1bi5URUU1xWIqIalVISIj0z9/fHxqNxuqYj49PpWGpRx55BH/5y18wYcIE1K9fH8HBwVi8eDGKiooQHx8PX19ftG7dGj/88IPVex05cgR9+/aFj48PgoODMWLECOTk5NyyNpPJhHXr1mHAgAFWx+fPn482bdrA09MTwcHBGDx4sNXzAwYMwKpVq+xvHCKqFQw3RKRKX331FQIDA7F371785S9/wauvvopnnnkGDzzwAA4cOIA+ffpgxIgRKC4uBgDk5eWhZ8+eiIiIQFpaGjZv3oysrCw8++yzt3yPQ4cO4fr164iMjJSOpaWl4fXXX8e0adNw/PhxbN68GQ8//LDVdd26dcPevXthMBhq58MTkV0YbohIlTp16oR3330Xbdq0QWJiIjw9PREYGIgxY8agTZs2SEpKwtWrV3Ho0CEAwGeffYaIiAi8//77aNeuHSIiIrBkyRJs374dJ06cqPI9zp8/D61Wi6CgIOnYhQsXUK9ePTz++ONo0aIFIiIi8Prrr1td16RJE5SWlloNuRGRejDcEJEqdezYUfrPWq0WDRs2RHh4uHQsODgYAJCdnQ3AMjF4+/bt0hweHx8ftGvXDgBw+vTpKt/jxo0b0Ov1VpOee/fujRYtWuCuu+7CiBEjsHLlSql3qJyXlxcAVDpOROrAcENEqqTT6aweazQaq2PlgcRsNgMACgsLMWDAAKSnp1v9O3nyZKVhpXKBgYEoLi5GaWmpdMzX1xcHDhzAN998g8aNGyMpKQmdOnVCXl6edE5ubi4AoFGjRrJ8ViKSF8MNETmFLl264H//+x/CwsLQunVrq3/16tWr8prOnTsDAI4ePWp13N3dHTExMfjggw9w6NAhnDt3Dtu2bZOeP3LkCJo1a4bAwMBa+zxEVHMMN0TkFMaOHYvc3FwMGzYM+/btw+nTp7FlyxbEx8fDZDJVeU2jRo3QpUsX7Nq1Szq2ceNGzJ07F+np6Th//jyWL18Os9mMu+++Wzrn559/Rp8+fWr9MxFRzTDcEJFTaNKkCf7zn//AZDKhT58+CA8Px4QJExAQEAA3t1v/v7oXX3wRK1eulB4HBARg/fr16NmzJ+655x4sXLgQ33zzDe69914AQElJCTZs2IAxY8bU+mcioprhJn5E5NJu3LiBu+++G6tXr0Z0dPQdz1+wYAG+/fZbbN26tQ6qI6KaYM8NEbk0Ly8vLF++/Lab/d1Mp9Ph008/reWqiMge7LkhIiIip8KeGyIiInIqDDdERETkVBhuiIiIyKkw3BAREZFTYbghIiIip8JwQ0RERE6F4YaIiIicCsMNERERORWGGyIiInIq/w8dLLzjQTtrIwAAAABJRU5ErkJggg==", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "outputs": [], "source": [ - "import matplotlib.pyplot as plt\n", - "\n", - "time_list, deployment_level_list = [], []\n", - "\n", - "obs_vars = test_flight.get_controller_observed_variables()\n", - "\n", - "for time, deployment_level in obs_vars:\n", - " time_list.append(time)\n", - " deployment_level_list.append(deployment_level)\n", - "\n", - "# Plot deployment level by time\n", - "plt.plot(time_list, deployment_level_list)\n", - "plt.xlabel(\"Time (s)\")\n", - "plt.ylabel(\"Deployment Level\")\n", - "plt.title(\"Deployment Level by Time\")\n", - "plt.grid()\n", - "plt.show()" + "# The deployment level the air brakes flew with, held between controller calls\n", + "test_flight.plots.controls()" ] }, { diff --git a/docs/notebooks/sensors.ipynb b/docs/notebooks/sensors.ipynb index ed29454e9..1b4e7772e 100644 --- a/docs/notebooks/sensors.ipynb +++ b/docs/notebooks/sensors.ipynb @@ -452,12 +452,10 @@ "outputs": [], "source": [ "def controller_function(context):\n", - " time = context.time\n", " sampling_rate = context.sampling_rate\n", " state = context.state\n", " previous_state = context.previous_state\n", - " air_brakes = context.controlled.air_brakes\n", - " sensors = context.sensors\n", + " air_brakes = context.controls.air_brakes\n", " environment = context.environment\n", "\n", " altitude_ASL = state.z\n", @@ -474,13 +472,17 @@ " free_stream_speed = ((wind_x - vx) ** 2 + (wind_y - vy) ** 2 + (vz) ** 2) ** 0.5\n", " mach_number = free_stream_speed / environment.speed_of_sound(altitude_ASL)\n", "\n", + " deployment_level = air_brakes.deployment_level\n", + "\n", " # Get the state from the previous controller call\n", " previous_vz = previous_state.vz if previous_state is not None else vz\n", "\n", + " # Keep the Mach number with its time, to read after the flight\n", + " context.record(mach_number=mach_number)\n", + "\n", " # Check if the rocket has reached burnout\n", - " accelerometer = sensors[0]\n", - " if accelerometer.measurement[2] > 0:\n", - " return None\n", + " if context.sensors.accelerometer_in_nosecone.az > 0:\n", + " return\n", "\n", " # If below 1500 meters above ground level, air_brakes are not deployed\n", " if altitude_AGL < 1500:\n", @@ -489,31 +491,22 @@ " # Else calculate the deployment level\n", " else:\n", " # Controller logic\n", - " new_deployment_level = (\n", - " air_brakes.deployment_level + 0.1 * vz + 0.01 * previous_vz**2\n", - " )\n", + " new_deployment_level = deployment_level + 0.1 * vz + 0.01 * previous_vz**2\n", "\n", " # Limiting the speed of the air_brakes to 0.2 per second\n", " # Since this function is called every 1/sampling_rate seconds\n", " # the max change in deployment level per call is 0.2/sampling_rate\n", " max_change = 0.2 / sampling_rate\n", - " lower_bound = air_brakes.deployment_level - max_change\n", - " upper_bound = air_brakes.deployment_level + max_change\n", - " new_deployment_level = min(max(new_deployment_level, lower_bound), upper_bound)\n", - "\n", - " air_brakes.deployment_level = new_deployment_level\n", - "\n", - " # Return variables of interest to be saved in the observed_variables list\n", - " return (\n", - " time,\n", - " air_brakes.deployment_level,\n", - " air_brakes.drag_coefficient(air_brakes.deployment_level, mach_number),\n", - " )" + " lower_bound = deployment_level - max_change\n", + " upper_bound = deployment_level + max_change\n", + " air_brakes.deployment_level = min(\n", + " max(new_deployment_level, lower_bound), upper_bound\n", + " )" ] }, { "cell_type": "code", - "execution_count": 14, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -523,10 +516,10 @@ " sampling_rate=10,\n", " reference_area=None,\n", " clamp=True,\n", - " initial_observed_variables=[0, 0, 0],\n", " override_rocket_drag=False,\n", " name=\"AirBrakes\",\n", " controller_name=\"AirBrakes Controller\",\n", + " position=-0.5, # where the air brakes are, in meters\n", ")" ] }, diff --git a/docs/reference/classes/Commands.rst b/docs/reference/classes/Commands.rst new file mode 100644 index 000000000..ae80dbb9a --- /dev/null +++ b/docs/reference/classes/Commands.rst @@ -0,0 +1,9 @@ +Commands Class +-------------- + +What an event's trigger or callback asks of the flight, reached as +``context.commands``. It is not part of RocketPy's top-level namespace. See +:ref:`eventusage` for examples of each command. + +.. autoclass:: rocketpy.simulation.events.commands.Commands + :members: diff --git a/docs/reference/classes/EventContext.rst b/docs/reference/classes/EventContext.rst index 5c7be147c..6011242dc 100644 --- a/docs/reference/classes/EventContext.rst +++ b/docs/reference/classes/EventContext.rst @@ -2,10 +2,4 @@ EventContext Class ------------------ .. autoclass:: rocketpy.EventContext - :members: time, state, state_dot, previous_state, previous_time, height_agl, pressure, step_size, sampling_rate, event, flight, rocket, environment, phase, sensors, sensors_by_name, controller, controlled - -Controlled Class ----------------- - -.. autoclass:: rocketpy.control.controlled.Controlled - :members: + :members: time, state, state_dot, previous_state, previous_time, height_agl, conditions, pressure, density, speed_of_sound, wind_velocity, stream_velocity, stream_speed, mach, dt, sampling_rate, event, memory, commands, rocket, environment, phase_name, sensors, controls, outputs, record diff --git a/docs/reference/classes/EventViews.rst b/docs/reference/classes/EventViews.rst new file mode 100644 index 000000000..cde31da3a --- /dev/null +++ b/docs/reference/classes/EventViews.rst @@ -0,0 +1,15 @@ +Event View Classes +------------------ + +What ``context.controls``, ``context.outputs`` and ``context.sensors`` return +inside an event or controller function. They are not part of RocketPy's +top-level namespace and are not built by the user. + +.. autoclass:: rocketpy.simulation.events.views.ControlsView + :members: + +.. autoclass:: rocketpy.simulation.events.views.OutputsView + :members: + +.. autoclass:: rocketpy.simulation.events.views.SensorsView + :members: diff --git a/docs/reference/classes/FlightDataExporter.rst b/docs/reference/classes/FlightDataExporter.rst new file mode 100644 index 000000000..d4ab1969c --- /dev/null +++ b/docs/reference/classes/FlightDataExporter.rst @@ -0,0 +1,7 @@ +FlightDataExporter Class +------------------------ + +Writes a flight's results to files, reached as ``flight.exports``. + +.. autoclass:: rocketpy.simulation.flight_data_exporter.FlightDataExporter + :members: diff --git a/docs/reference/classes/Solution.rst b/docs/reference/classes/Solution.rst index f8735fbb3..467fc3472 100644 --- a/docs/reference/classes/Solution.rst +++ b/docs/reference/classes/Solution.rst @@ -1,9 +1,44 @@ Solution Classes ---------------- -These classes hold the state history produced by a :class:`rocketpy.Flight` -simulation. They are not part of RocketPy's top-level namespace; a flight's -solution is reached through :attr:`Flight.solution `. +These classes hold everything a :class:`rocketpy.Flight` simulation produced +over time, as raw numbers. They are not part of RocketPy's top-level +namespace; a flight's solution is reached through +:attr:`Flight.solution `. + +Every quantity the flight knows at each stored row is read by name, as an +attribute or as a key, and comes back as an ``(n, 2)`` array of time and +value: + +.. code-block:: python + + flight.solution.vz # an integrated state + flight.solution.az # a variable worked out from the states + flight.solution.controls.canards.fin_1 # a control input, by controllable + flight.solution["vz"], flight.solution["canards.fin_1"] # the same, by name + flight.solution.names # everything it holds + flight.solution.at(3.0) # all of it at the nearest stored time + +The states are the 13 the flight integrates (position, velocity, attitude +and angular rates) plus any state a controllable adds. The variables worked +out from them are the ones a flight phase computes on its way to each state +derivative without integrating them: the accelerations, the aerodynamic +forces and moments, the net thrust. They are worked out again after the +flight the first time one is read, from the stored rows and their control +inputs, and kept; a flight read back from a file cannot report them, since +that needs the equations of motion. + +The flight's own :attr:`Flight.az ` and its companions, +and ``flight.controls.canards.fin_1``, wrap these arrays as a +:class:`Function `, which can be plotted and evaluated at +any time. Reach for the solution when you want the values exactly as the +simulation stored them. + +What the sensors read sits in the solution too, at the sensors' own sampling +times rather than the solver's rows: ``flight.solution.sensors.barometer.pressure`` +is the ``(n, 2)`` array of readings, and ``flight.sensor_history`` the same as +Functions. What events recorded with ``context.record`` is the user's own +data, kept exactly as given in ``flight.records``, not in the solution. The ``Solution`` holds every row of the flight in one list, in the order they were flown. The flight phases sit alongside it, each saying where its own rows @@ -27,35 +62,12 @@ For a rocket with a drogue and a main parachute it prints something like: Main_parachute_descent 59 :meth:`Solution.phase_span` gives where a phase's rows begin and end, so -``flight.solution[start:stop]``, ``flight.solution["vz"][start:stop]`` and +``flight.solution[start:stop]``, ``flight.solution.vz[start:stop]`` and ``flight.solution.canonical_array[start:stop]`` read just that phase. .. autoclass:: rocketpy.simulation.solution.Solution :members: -Post-process variables -~~~~~~~~~~~~~~~~~~~~~~ - -On its way to each state derivative, a flight phase works out quantities it -never integrates: the accelerations, the aerodynamic forces and moments, and -the net thrust. Read them through ``flight.solution.post``: - -.. code-block:: python - - post = flight.solution.post - post.names # every variable this flight computes - post["az"] # its [t, value] history over the whole flight - post.at(3.0) # every variable at the nearest stored time - -The same values back the flight's own :attr:`Flight.az ` -and its companions, which wrap them as a -:class:`Function ` so they can be plotted and evaluated at -any time. Reach for ``post`` when you want the values exactly as the simulation -stored them, without interpolation. - -.. autoclass:: rocketpy.simulation.solution.PostProcessSolution - :members: - The phase objects themselves are internal to RocketPy for now, so their shape may change between releases. These are the values worth reading off one: diff --git a/docs/reference/classes/aero_surfaces/AeroCoefficient.rst b/docs/reference/classes/aero_surfaces/AeroCoefficient.rst new file mode 100644 index 000000000..8306f816e --- /dev/null +++ b/docs/reference/classes/aero_surfaces/AeroCoefficient.rst @@ -0,0 +1,5 @@ +AeroCoefficient Class +--------------------- + +.. autoclass:: rocketpy.AeroCoefficient + :members: diff --git a/docs/reference/classes/aero_surfaces/ControlFins.rst b/docs/reference/classes/aero_surfaces/ControlFins.rst new file mode 100644 index 000000000..9d7e989be --- /dev/null +++ b/docs/reference/classes/aero_surfaces/ControlFins.rst @@ -0,0 +1,5 @@ +ControlFins Class +----------------- + +.. autoclass:: rocketpy.ControlFins + :members: diff --git a/docs/reference/classes/aero_surfaces/ControllableGenericSurface.rst b/docs/reference/classes/aero_surfaces/ControllableGenericSurface.rst deleted file mode 100644 index 94e9b7814..000000000 --- a/docs/reference/classes/aero_surfaces/ControllableGenericSurface.rst +++ /dev/null @@ -1,5 +0,0 @@ -Controllable Generic Surface Class ----------------------------------- - -.. autoclass:: rocketpy.ControllableGenericSurface - :members: diff --git a/docs/reference/classes/aero_surfaces/index.rst b/docs/reference/classes/aero_surfaces/index.rst index d4b67e68a..c9c0627ba 100644 --- a/docs/reference/classes/aero_surfaces/index.rst +++ b/docs/reference/classes/aero_surfaces/index.rst @@ -12,12 +12,14 @@ AeroSurface Classes TrapezoidalFins EllipticalFins FreeFormFins + _BaseFin Fin TrapezoidalFin EllipticalFin FreeFormFin + ControlFins RailButtons AirBrakes GenericSurface LinearGenericSurface - ControllableGenericSurface \ No newline at end of file + AeroCoefficient \ No newline at end of file diff --git a/docs/reference/classes/control/continuous_controller.rst b/docs/reference/classes/control/continuous_controller.rst new file mode 100644 index 000000000..1e14b8d4b --- /dev/null +++ b/docs/reference/classes/control/continuous_controller.rst @@ -0,0 +1,5 @@ +ContinuousController Class +-------------------------- + +.. autoclass:: rocketpy.ContinuousController + :members: diff --git a/docs/reference/classes/control/controller.rst b/docs/reference/classes/control/controller.rst new file mode 100644 index 000000000..663edc286 --- /dev/null +++ b/docs/reference/classes/control/controller.rst @@ -0,0 +1,5 @@ +Controller Class +---------------- + +.. autoclass:: rocketpy.Controller + :members: diff --git a/docs/reference/classes/control/effectors.rst b/docs/reference/classes/control/effectors.rst new file mode 100644 index 000000000..e306beee9 --- /dev/null +++ b/docs/reference/classes/control/effectors.rst @@ -0,0 +1,8 @@ +Effector Classes +---------------- + +.. autoclass:: rocketpy.ThrustEffector + :members: + +.. autoclass:: rocketpy.ForceEffector + :members: diff --git a/docs/reference/classes/control/flight_conditions.rst b/docs/reference/classes/control/flight_conditions.rst new file mode 100644 index 000000000..3bb44052c --- /dev/null +++ b/docs/reference/classes/control/flight_conditions.rst @@ -0,0 +1,5 @@ +FlightConditions Class +---------------------- + +.. autoclass:: rocketpy.control.FlightConditions + :members: diff --git a/docs/reference/classes/control/index.rst b/docs/reference/classes/control/index.rst new file mode 100644 index 000000000..417e197aa --- /dev/null +++ b/docs/reference/classes/control/index.rst @@ -0,0 +1,14 @@ +Control Classes +=============== + +Controllers, the parts they move and what a part is told about the flight. See +:ref:`controllers` for how they are used. + +.. toctree:: + :maxdepth: 1 + :caption: Contents: + + Controller Class + ContinuousController Class + Effector Classes + FlightConditions Class diff --git a/docs/reference/index.rst b/docs/reference/index.rst index a85e886ba..538b1fb85 100644 --- a/docs/reference/index.rst +++ b/docs/reference/index.rst @@ -18,8 +18,12 @@ This reference manual details functions, modules, methods and attributes include classes/sensors/index.rst classes/Flight classes/Solution + classes/FlightDataExporter classes/Event classes/EventContext + classes/Commands + classes/EventViews + Control Classes Utilities classes/EnvironmentAnalysis Monte Carlo Analysis diff --git a/docs/reference/plots_prints/aero_surfaces/AirBrakes/AirBrakesPlots.rst b/docs/reference/plots_prints/aero_surfaces/AirBrakes/AirBrakesPlots.rst new file mode 100644 index 000000000..9d92144f7 --- /dev/null +++ b/docs/reference/plots_prints/aero_surfaces/AirBrakes/AirBrakesPlots.rst @@ -0,0 +1,5 @@ +AirBrakes Plots Class +--------------------- + +.. autoclass:: rocketpy.plots.aero_surface_plots._AirBrakesPlots + :members: diff --git a/docs/reference/plots_prints/aero_surfaces/AirBrakes/AirBrakesPrints.rst b/docs/reference/plots_prints/aero_surfaces/AirBrakes/AirBrakesPrints.rst new file mode 100644 index 000000000..f98a950ce --- /dev/null +++ b/docs/reference/plots_prints/aero_surfaces/AirBrakes/AirBrakesPrints.rst @@ -0,0 +1,5 @@ +AirBrakes Prints Class +---------------------- + +.. autoclass:: rocketpy.prints.aero_surface_prints._AirBrakesPrints + :members: diff --git a/docs/reference/plots_prints/aero_surfaces/AirBrakes/index.rst b/docs/reference/plots_prints/aero_surfaces/AirBrakes/index.rst new file mode 100644 index 000000000..55a46d882 --- /dev/null +++ b/docs/reference/plots_prints/aero_surfaces/AirBrakes/index.rst @@ -0,0 +1,10 @@ +AirBrakes Plots and Prints Classes +================================== + +.. toctree:: + :maxdepth: 1 + :caption: Contents: + + AirBrakesPlots + AirBrakesPrints + diff --git a/docs/reference/plots_prints/aero_surfaces/ControlFins/ControlFinsPlots.rst b/docs/reference/plots_prints/aero_surfaces/ControlFins/ControlFinsPlots.rst new file mode 100644 index 000000000..99ea550aa --- /dev/null +++ b/docs/reference/plots_prints/aero_surfaces/ControlFins/ControlFinsPlots.rst @@ -0,0 +1,5 @@ +ControlFins Plots Class +----------------------- + +.. autoclass:: rocketpy.plots.aero_surface_plots._ControlFinsPlots + :members: diff --git a/docs/reference/plots_prints/aero_surfaces/ControlFins/ControlFinsPrints.rst b/docs/reference/plots_prints/aero_surfaces/ControlFins/ControlFinsPrints.rst new file mode 100644 index 000000000..e20549233 --- /dev/null +++ b/docs/reference/plots_prints/aero_surfaces/ControlFins/ControlFinsPrints.rst @@ -0,0 +1,5 @@ +ControlFins Prints Class +------------------------ + +.. autoclass:: rocketpy.prints.aero_surface_prints._ControlFinsPrints + :members: diff --git a/docs/reference/plots_prints/aero_surfaces/ControlFins/index.rst b/docs/reference/plots_prints/aero_surfaces/ControlFins/index.rst new file mode 100644 index 000000000..573a073f3 --- /dev/null +++ b/docs/reference/plots_prints/aero_surfaces/ControlFins/index.rst @@ -0,0 +1,10 @@ +ControlFins Plots and Prints Classes +==================================== + +.. toctree:: + :maxdepth: 1 + :caption: Contents: + + ControlFinsPlots + ControlFinsPrints + diff --git a/docs/reference/plots_prints/aero_surfaces/index.rst b/docs/reference/plots_prints/aero_surfaces/index.rst index 88edb1d27..7ba292949 100644 --- a/docs/reference/plots_prints/aero_surfaces/index.rst +++ b/docs/reference/plots_prints/aero_surfaces/index.rst @@ -12,4 +12,6 @@ AeroSurface Plots and Prints Classes EllipticalFins Plots and Prints Tail Plots and Prints RailButtons Plots and Prints + ControlFins Plots and Prints + AirBrakes Plots and Prints diff --git a/docs/technical/simulation_loop.rst b/docs/technical/simulation_loop.rst index 0182b24af..8de36ac28 100644 --- a/docs/technical/simulation_loop.rst +++ b/docs/technical/simulation_loop.rst @@ -53,7 +53,14 @@ Building blocks Every phase can report the full 13-state canonical vector, so events and outputs never need to know which states a phase actually integrates. Bound to a flight (``dynamics.bind(flight)``) it is callable as ``(t, u)``, - which is what the SciPy solver expects. + which is what the SciPy solver expects; the equations themselves take + ``(flight, t, u, controls)``, where ``u`` is the state and ``controls`` + the flight's control inputs, a dictionary from control input name to value. + ``controls`` is built from the rocket's controllables with controls + (``rocket.controllables``) at the start of every flight and kept by the + flight (``flight._controls``, private), written by events through + ``context.controls``, and a copy is stored with every row, so a row worked + out again after the flight reads its own controls. ``_TimeNodes`` / ``_TimeNode`` The node schedule of one phase. A node is a time and the list of events @@ -66,8 +73,8 @@ Building blocks The loop reads those commands right after the call. ``Solution`` (``solution.py``) - The stored rows ``[t, *state]`` of the flight, grouped by phase, plus the - post-process values recorded beside them. + The stored rows ``[t, *state]`` of the flight, grouped by phase, with the + control inputs in force at each row and the sensor readings. Setting up ---------- @@ -115,8 +122,8 @@ Running a phase After every solver step (``__execute_solver_step``), the new row ``[solver.t, *solver.y]`` is appended to the solution and ``flight.t`` / ``flight.y_sol`` are updated. Then ``__process_events`` runs, and finally -``__post_process_step`` records the post-process variables of the rows the -step wrote, if the flight records them (see below). +``__store_row_controls`` stores a copy of the control inputs with the rows the +step wrote. Checking events after a step ---------------------------- @@ -134,9 +141,16 @@ Checking events after a step 3. **Evaluation.** One ``EventContext`` is built for that moment and every event in the list is called with it. After each event that fires, its commands are applied (``apply_event_commands``). -4. **Restart the solver.** If the flight was rolled back, or a command moved - the end of the phase, and the phase is still being flown, the solver is - rebuilt from the flight's current state and runs on to the next node. +4. **Restart the solver.** If the flight now stands before the solver, the + solver is rebuilt from the flight's current state and runs on to the next + node, unless the node is over. That happens after a rollback, and after an + event that solved its exact time inside the step and changed the + trajectory. An event that only moved the end of the phase (a new phase + after a lag) moves the solver's bound instead. A control write or a surface + switch at the step's end does not rebuild it: the solver is already at that time and + meets the new derivative on its next step. A rebuilt solver begins again + with a tiny step, so rebuilding on every write would make an event that + writes a control at every step cripple the integration. .. _time_overshoot_processing: @@ -146,20 +160,14 @@ Time-overshoot processing A sampled event with ``time_overshootable=True`` does not force the solver to stop at its sampling times. Instead, after each step, ``__process_overshootable_nodes`` builds the list of sampling times that fell inside the step and, for each one, -interpolates the state there with the solver's dense output and evaluates the -event's trigger on it (``trigger_only=True``). Then: - -- If the trigger is false, nothing happens. -- If it is true and the event does **not** declare ``changes_dynamics``, its - callback runs right there on the interpolated state. If the commands it - queued change the trajectory (a new phase, new dynamics, or termination), the - flight is first rolled back to the interpolated point so the commands apply - from the crossing rather than from the overshot step end. -- If it is true and the event declares ``changes_dynamics=True``, the flight - is rolled back to the interpolated point and the event is queued to be - called for real, together with the continuous events, at that rolled-back - moment. This guarantees the callback's changes to the rocket take effect from - the crossing on, and that the overshot part of the step is discarded. +interpolates the state there with the solver's dense output and runs the +event on it (``call_event``). If the trigger is true, the callback runs right +there on the interpolated state. If the commands it queued change the +trajectory (a new phase, new dynamics, termination, a surface switch, a change +to the rocket or a control write), the flight is first rolled back to the +interpolated point so the commands apply from the crossing rather than from +the overshot step end. The other events of the same sampling time still run +there. A rollback (``apply_rollback_command``) sets ``flight.t`` and ``flight.y_sol`` to the interpolated point and replaces the last stored row with it. Sampling @@ -180,7 +188,10 @@ event queued and applies them, in this order: into the solution. When the event changes the trajectory, the exact row replaces the end of the step and the flight continues from it; otherwise it is inserted just before the step's end and the step stands as flown. -2. **New phase or dynamics.** ``set_dynamics`` and ``start_flight_phase`` add a +2. **Surfaces.** Surface switches are recorded with their time, so a later + rollback drops the ones after the time it returns to and the post-processing + replays them. +3. **New phase or dynamics.** ``set_dynamics`` and ``start_flight_phase`` add a phase to the list right after the current one, starting at the trigger time (plus ``lag``, if any) with the requested dynamics or, if none was given, the current ones, and the flight is rolled back to the trigger. Without a @@ -189,34 +200,29 @@ event queued and applies them, in this order: lag the current phase keeps flying its own equations until the new phase begins: its schedule is cut at that time and its solver is restarted from the trigger (a parachute keeps falling freely while it opens). -3. **Termination.** ``terminate_flight`` truncates the phase list after the +4. **Termination.** ``terminate_flight`` truncates the phase list after the current phase and inserts a final phase at the trigger time, so the outer loop ends there. -4. **Event list changes.** ``add_event`` registers a new event with the flight +5. **Event list changes.** ``add_event`` registers a new event with the flight and, if it is non-overshootable, adds its nodes to the current phase. ``enable``/``disable`` commands, including ``trigger_only_once`` and the ``enable_on``/``disable_on`` gates, update the event and add or remove its nodes from the current phase's schedule. After the events of a node are checked, the solver bound is set again, since -step 4 may have changed the node schedule. +step 5 may have changed the node schedule. Post-process variables ---------------------- The accelerations, aerodynamic forces and moments, and net thrust are not integrated; they are computed from a stored row by evaluating the equations of -motion again with ``post_processing=True``. For most flights that is done once, -after the simulation, over all stored rows. - -A flight with an event that declares ``changes_dynamics=True`` cannot do that: -a controller may have moved an air brake mid-flight, and a replay afterwards -would read the rocket as it ended the flight. Such a flight records the values -step by step during the simulation (``__post_process_step``), one extra -evaluation of the equations of motion per stored row. Whether the flight records -is decided in ``__init__`` from the events it was built with, which is why an -event added later with ``add_event`` cannot turn recording on for the rows -already flown. +motion again with ``post_processing=True``. That is done once, after the +simulation, over all stored rows. + +Each row is computed with the control inputs stored with it. Surface switches +are recorded with their time (``flight._surface_switches``), so the replay +turns each surface on or off for the rows it was on or off in the flight. Where to look ------------- @@ -226,7 +232,7 @@ Where to look ``__process_overshootable_nodes``, ``__restart_phase_solver``. - ``events/event_context.py``: ``EventContext``, the values a trigger and callback are given, and ``build_event_kwargs``, which builds one. - ``events/state.py``: the private ``_State`` and ``_StateDot``, what + ``helpers/state.py``: the private ``_State`` and ``_StateDot``, what ``context.state`` and ``context.state_dot`` are. - ``events/event_execution.py``: ``call_events`` and ``process_overshootable_event``, which run an event, and diff --git a/docs/user/airbrakes.rst b/docs/user/airbrakes.rst index e9ce9c25f..f64542cf4 100644 --- a/docs/user/airbrakes.rst +++ b/docs/user/airbrakes.rst @@ -17,7 +17,7 @@ First, lets define everything we need for the simulation up to the rocket: .. jupyter-execute:: - from rocketpy import Environment, SolidMotor, Rocket, Flight + from rocketpy import AirBrakes, Controller, Environment, SolidMotor, Rocket, Flight env = Environment(latitude=32.990254, longitude=-106.974998, elevation=1400) @@ -91,60 +91,41 @@ To create an air brakes model, we essentially need to define the following: specific deployment level and Mach number. - The **controller function**, which takes in as argument information about the - simulation up to the current time step, and the ``AirBrakes`` instance being - defined, and sets the desired air brakes' deployment level. The air brakes' - deployment level must be between 0 and 1, and is set using the - ``deployment_level`` attribute. Inside this function, any controller logic, - filters, and apogee prediction can be implemented. + simulation up to the current time step and sets the desired air brakes' + deployment level. The air brakes' deployment level must be between 0 and 1, + and is set by writing ``context.controls.air_brakes.deployment_level``. + Inside this function, any controller logic, filters, and apogee prediction + can be implemented. -- The **sampling rate** of the controller function, in seconds. This is the time - between each call of the controller function, in simulation time. Must be - given in Hertz. +- The **sampling rate** of the controller function, in Hertz (Hz): how many + times per second of simulation time the controller function is called. Defining the Controller Function ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Lets start by defining a very simple controller function. -The ``controller_function`` must take in the following arguments, in this -order: - -1. ``time`` (float): The current simulation time in seconds. -2. ``sampling_rate`` (float): The rate at which the controller - function is called, measured in Hertz (Hz). -3. ``state`` (list): The state vector of the simulation. The state - is a list containing the following values, in this order: - - - ``x``: The x position of the rocket, in meters. - - ``y``: The y position of the rocket, in meters. - - ``z``: The z position of the rocket, in meters. - - ``v_x``: The x component of the velocity of the rocket, in meters per - second. - - ``v_y``: The y component of the velocity of the rocket, in meters per - second. - - ``v_z``: The z component of the velocity of the rocket, in meters per - second. - - ``e0``: The first component of the quaternion representing the rotation - of the rocket. - - ``e1``: The second component of the quaternion representing the rotation - of the rocket. - - ``e2``: The third component of the quaternion representing the rotation - of the rocket. - - ``e3``: The fourth component of the quaternion representing the rotation - of the rocket. - - ``w_x``: The x component of the angular velocity of the rocket, in - radians per second. - - ``w_y``: The y component of the angular velocity of the rocket, in - radians per second. - - ``w_z``: The z component of the angular velocity of the rocket, in - radians per second. - -4. ``observed_variables`` (list): A list containing the variables that - the controller function returns. The return of each controller - function call is appended to the observed_variables list. The - initial value in the first step of the simulation of this list is - provided by the ``initial_observed_variables`` argument. -5. ``air_brakes`` (AirBrakes): The ``AirBrakes`` instance being controlled. +The ``controller_function`` takes one argument, ``context``, which holds what +the flight computer knows at the current time step: + +- ``context.time``: the current simulation time, in seconds. +- ``context.sampling_rate``: the rate at which the controller function is + called, in Hertz (Hz). +- ``context.state``: the state of the rocket, read by name: ``state.z`` + (altitude above sea level, in meters), ``state.vx``, ``state.vy``, + ``state.vz`` (velocity, in m/s), ``state.e0`` to ``state.e3`` (the + quaternion of the attitude) and ``state.w1`` to ``state.w3`` (angular + velocity, in rad/s). +- ``context.controls``: the control inputs of the rocket, such as + ``context.controls.air_brakes.deployment_level``. +- ``context.record(...)``: keeps named values with their time, to look at + after the flight. +- ``context.memory``: a dictionary the controller keeps from one call to the + next, for what the next call needs (a filter state, an integral, a + counter). It starts again from its initial values at every flight. +- ``context.environment``, ``context.rocket``, ``context.sensors`` and + ``context.height_agl``, among others. See :ref:`eventusage` for the full + list. Our example ``controller_function`` will deploy the air brakes when the rocket reaches 1500 meters above the ground. The deployment level will be function of the @@ -174,11 +155,14 @@ Lets define the controller function: sampling_rate = context.sampling_rate motor = context.rocket.motor environment = context.environment - air_brakes = context.controlled.air_brakes + air_brakes = context.controls.air_brakes # the air brakes' controls altitude_ASL = state.z altitude_AGL = context.height_agl vx, vy, vz = state.vx, state.vy, state.vz + # The deployment level in force since the previous call + deployment_level = air_brakes.deployment_level + # Get winds in x and y directions wind_x, wind_y = environment.wind_velocity_x(altitude_ASL), environment.wind_velocity_y(altitude_ASL) @@ -192,73 +176,66 @@ Lets define the controller function: previous_state = context.previous_state previous_vz = previous_state.vz if previous_state is not None else vz - # If we wanted to we could get the returned values from observed_variables: - # returned_time, deployment_level, drag_coefficient = observed_variables[-1] - # Check if the rocket has reached burnout if time < motor.burn_out_time: - air_brakes.deployment_level = 0 + deployment_level = 0 # If below 1500 meters above ground level, air_brakes are not deployed if altitude_AGL < 1500: - air_brakes.deployment_level = 0 + deployment_level = 0 # Else calculate the deployment level else: # Controller logic - new_deployment_level = ( - air_brakes.deployment_level + 0.1 * vz + 0.01 * previous_vz**2 - ) + new_deployment_level = deployment_level + 0.1 * vz + 0.01 * previous_vz**2 # Limiting the speed of the air_brakes to 0.2 per second # Since this function is called every 1/sampling_rate seconds # the max change in deployment level per call is 0.2/sampling_rate max_change = 0.2 / sampling_rate - lower_bound = air_brakes.deployment_level - max_change - upper_bound = air_brakes.deployment_level + max_change - new_deployment_level = min(max(new_deployment_level, lower_bound), upper_bound) + lower_bound = deployment_level - max_change + upper_bound = deployment_level + max_change + deployment_level = min(max(new_deployment_level, lower_bound), upper_bound) - air_brakes.deployment_level = new_deployment_level + air_brakes.deployment_level = deployment_level - # Return variables of interest to be saved in the observed_variables list - return ( - time, - air_brakes.deployment_level, - air_brakes.drag_coefficient(air_brakes.deployment_level, mach_number), - ) + # Keep the Mach number with its time, to look at after the flight + context.record(mach_number=mach_number) .. note:: - - The ``controller_function`` accepts 5, 6, or 7 parameters for backward - compatibility: + - The ``context`` gives access to atmospheric conditions through + ``context.environment`` (wind, temperature, pressure, elevation), such + as ``context.environment.wind_velocity_x(altitude)`` or + ``context.environment.speed_of_sound(altitude)``, without relying on + global variables. - * **5 parameters** (original): ``time``, ``sampling_rate``, ``state``, - ``observed_variables``, ``air_brakes`` - * **6 parameters** (with sensors): adds ``sensors`` as the 6th parameter - * **7 parameters** (with environment): adds ``sensors`` and ``environment`` - as the 6th and 7th parameters - - - The **environment parameter** provides access to atmospheric conditions - (wind, temperature, pressure, elevation) without relying on global variables. - This enables proper serialization of rockets with air brakes and improves - code modularity. Available methods include ``environment.elevation``, - ``environment.wind_velocity_x(altitude)``, ``environment.wind_velocity_y(altitude)``, - ``environment.speed_of_sound(altitude)``, and others. + - The positional form of v1.13, + ``controller_function(time, sampling_rate, state, state_history, + observed_variables, air_brakes[, sensors[, environment]])``, still + works but is deprecated and will be removed in v1.16. Write the + function as ``controller_function(context)`` instead. - The code inside the ``controller_function`` can be as complex as needed. Anything can be implemented inside the function, including filters, apogee prediction, and any controller logic. - - The ``air_brakes`` instance ``deployment_level`` is clamped between 0 and 1. - This means that the deployment level will never be set to a value lower than - 0 or higher than 1. If you want to disable this feature, set ``clamp`` to - ``False`` when defining the air brakes. - - - Anything can be returned by the ``controller_function``. The returned - values will be saved in the ``observed_variables`` list at every time step - and can then be accessed by the ``controller_function`` at the next time - step. The saved values can also be accessed after the simulation is - finished. This is useful for debugging and for plotting the results. + - The deployment level written to + ``context.controls.air_brakes.deployment_level`` is kept between 0 + and 1: a value outside that range is moved to the nearest end. To put + no limit on it, set ``clamp`` to ``False`` when defining the air + brakes. The control input is named + after the air brakes, in snake_case: ``name="AirBrakes"`` (the default) + gives ``context.controls.air_brakes``, and ``name="Main Brakes"`` gives + ``context.controls.main_brakes``, or as given, + ``context.controls["Main Brakes"]``. To skip the name, use the air brakes + returned by ``rocket.add_air_brakes``: + ``context.controls[air_brakes].deployment_level``. + + - What the ``controller_function`` passes to ``context.record`` is kept + at every call and can be read after the flight in ``flight.records``. + Each record is a list of ``(time, value)`` pairs, with the value as it + was given. This is useful for debugging and for plotting the results. - The ``controller_function`` can also be defined in a separate file and imported into the simulation script. This includes importing a ``c`` or @@ -319,58 +296,87 @@ Part of the data from the CSV can be seen in the code block below. 1.0, 0.8, 0.218 .. note:: - The air brakes' drag coefficient curve can represent either the air brakes - alone or both the air brakes and the rocket. This is determined by the - ``override_rocket_drag`` argument. If set to True, the drag - coefficient curve will include both the air brakes and the rocket. If set to - False, the curve will exclusively represent the air brakes. - - When the curve represents only the air brakes, its drag coefficient will be - added to the rocket's existing drag coefficient. Conversely, if the curve - represents both the air brakes and the rocket, the drag coefficient will be - set to match that of the curve. This feature is particularly useful when you - have a drag coefficient curve for the entire rocket with the air brakes - deployed, such as data from a wind tunnel test, and you want to incorporate - it into the simulation. + The air brakes' drag coefficient curve can be of the air brakes alone or of + the whole rocket at each deployment level. This is set by the + ``override_rocket_drag`` argument. + + With ``override_rocket_drag=False`` (the default) the curve is of the air + brakes alone, and their drag is added to the rocket's. + + With ``override_rocket_drag=True`` the curve is of the whole rocket, as + measured in a wind tunnel or computed for the complete rocket at several + deployment levels. The air brakes then add the difference between the curve + and its value at deployment level 0, at the same Mach number, to the + rocket's own drag. The curve must include deployment level 0, and the + rocket's ``power_off_drag`` should be those retracted values: the total drag + is then the curve. A warning is shown when the two differ by more than 5%. + + The whole-rocket curve is taken as the rocket with its motor off. The rocket + keeps switching between its two drag curves, and open air brakes add the + same difference to either one: + + - Motor off: ``power_off_drag`` + (curve at the deployment level − curve at + deployment level 0) + - Motor burning: ``power_on_drag`` + the same difference + + To have the air brakes add no drag while the motor burns, build the + :class:`rocketpy.AirBrakes` with ``active_during="power_off"``. + + In both cases retracted air brakes add no drag, and the rocket flies with its + own drag curves. Adding the Air Brakes to the Rocket ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Now we can add the air brakes to the rocket. +The air brakes are an aerodynamic surface with one control, and the controller +is a :class:`rocketpy.Controller` that writes it. Build each and add both to +the rocket, as for any other controllable: -We will set the ``reference_area`` to ``None``. This means that the reference -area for the calculation of the drag force from the coefficient will be the -rocket's reference area (the area of the cross section of the rocket). If we -wanted to set a different reference area, we would set ``reference_area`` to -the desired value. +- ``reference_area`` is the area the drag coefficient was made with. Here it + is the rocket's cross section, ``calisto.area``. +- ``clamp=True`` (the default) keeps the deployment level between 0 and 1: a + controller asking for more gets the limit. With ``clamp=False`` there is no + limit and the drag curve is extrapolated. +- ``positions`` is where the air brakes are on the rocket, in meters, in the + rocket's coordinate system, as for any surface. The drag acts along the + rocket's axis, so the position only matters while the rocket turns. -Also, we will set ``clamp`` to ``True``. This means that the deployment level will -be clamped between 0 and 1. This means that the deployment level will never be set -to a value lower than 0 or higher than 1. This can alter the behavior of the -controller function. If you want to disable this feature, set ``clamp`` to -``False``. +``air_brakes.info()`` prints the settings and the drag coefficient at a few +deployment levels and Mach numbers; ``air_brakes.plots.drag_coefficient()`` +draws the curve, one line per deployment level. .. jupyter-execute:: - air_brakes = calisto.add_air_brakes( + air_brakes = AirBrakes( drag_coefficient_curve="../data/rockets/calisto/air_brakes_cd.csv", - controller_function=controller_function, - sampling_rate=10, - reference_area=None, + reference_area=calisto.area, clamp=True, - initial_observed_variables=[0, 0, 0], override_rocket_drag=False, name="Air Brakes", ) + calisto.add_surfaces(air_brakes, positions=-0.5) # where they are, in meters + + controller = Controller( + controller_function, + sampling_rate=10, + name="AirBrakes Controller", + ) + calisto.add_controller(controller) air_brakes.all_info() -.. note:: +``rocket.add_air_brakes`` does the same in one call, building the air brakes +and the controller together. It is kept for scripts written that way: - The ``initial_observed_variables`` argument is optional. It is used as - the initial value for the ``observed_variables`` list passed on the - ``controller_function`` at the first time step. If not given, the - ``observed_variables`` list will be initialized as an empty list. +.. code-block:: python + + air_brakes = calisto.add_air_brakes( + drag_coefficient_curve="../data/rockets/calisto/air_brakes_cd.csv", + controller_function=controller_function, + sampling_rate=10, + name="Air Brakes", + position=-0.5, + ) .. seealso:: @@ -381,7 +387,7 @@ Simulating a Flight ------------------- We will be terminating the simulation at apogee, by setting -``terminate_at_apogee`` to ``True``. This way the simulation will stop when the +``terminate_on_apogee`` to ``True``. This way the simulation will stop when the rocket reaches apogee, and we will save some time. .. jupyter-execute:: @@ -398,44 +404,32 @@ rocket reaches apogee, and we will save some time. Analyzing the Results --------------------- -Now we can create some plots to analyze the results. We rely on the -``observed_variables`` list to get the data we want to plot. Since we returned -the ``time``, ``deployment_level`` and the ``drag_coefficient`` in the -``controller_function``, the ``observed_variables`` list will contain these -values at every time step. - -We can retrieve the ``observed_variables`` list by calling the -``get_controller_observed_variables`` method of the ``Flight`` instance. -Then we can plot the data we want. +Now we can create some plots to analyze the results. The deployment level +the air brakes flew with is stored with the flight: +``flight.solution.controls.air_brakes.deployment_level`` is the array of +time and value, and ``flight.controls.air_brakes.deployment_level`` the same +as a function of time. What the ``controller_function`` recorded is in +``flight.records``, named after the controller, exactly as it was recorded: +the default ``controller_name="AirBrakes Controller"`` gives +``flight.records["AirBrakes Controller"].mach_number``, a list of +``(time, value)`` pairs. .. jupyter-execute:: - import matplotlib.pyplot as plt - - time_list, deployment_level_list, drag_coefficient_list = [], [], [] + test_flight.plots.controls() - obs_vars = test_flight._controllers[0].log + deployment_level = test_flight.controls["Air Brakes"].deployment_level + mach_number = test_flight.records["AirBrakes Controller"].mach_number + print(f"Deployment level at 10 s: {deployment_level(10):.3f}") + time, mach = mach_number[-1] + print(f"Last Mach number recorded, at {time:.1f} s: {mach:.3f}") - for time, deployment_level, drag_coefficient in obs_vars: - time_list.append(time) - deployment_level_list.append(deployment_level) - drag_coefficient_list.append(drag_coefficient) +The drag the air brakes made during the flight, from the air they met and the +deployment level they flew with, next to the rocket's total drag: - # Plot deployment level by time - plt.plot(time_list, deployment_level_list) - plt.xlabel("Time (s)") - plt.ylabel("Deployment Level") - plt.title("Deployment Level by Time") - plt.grid() - plt.show() +.. jupyter-execute:: - # Plot drag coefficient by time - plt.plot(time_list, drag_coefficient_list) - plt.xlabel("Time (s)") - plt.ylabel("Drag Coefficient") - plt.title("Drag Coefficient by Time") - plt.grid() - plt.show() + air_brakes.plots.drag(test_flight) .. seealso:: diff --git a/docs/user/control_fins.rst b/docs/user/control_fins.rst new file mode 100644 index 000000000..e512a1706 --- /dev/null +++ b/docs/user/control_fins.rst @@ -0,0 +1,676 @@ +.. _controlfins: + +Control Fins +============ + +Control fins are fins a controller turns during the flight: canards near the +nose, or movable tail fins. Turned together they roll the rocket, turned in +pairs they pitch or yaw it. This example keeps a rocket from rolling: Calisto's +tail fins are canted, so left alone it spins up, and four small canards driven +by a controller hold the roll rate at zero. + +We use the same rocket as in the :ref:`First Simulation ` +example and add the canards to it. :ref:`controllers` describes everything a +controller can do; here we go through one from start to finish. + +.. note:: + + There are two ways to model control fins: + + - **From their shape**, with :class:`rocketpy.ControlFins`, as on this + page. RocketPy computes the forces of each fin from its geometry with + the Barrowman method, the model it uses for fixed fins. That method has + limits: small angles, subsonic flight, and each fin computed alone. See + :ref:`the limits of the model ` and + :ref:`controlfins_not_covered` before relying on the numbers. + - **From coefficients** measured in a wind tunnel or computed elsewhere, + with a :class:`rocketpy.GenericSurface` whose coefficients depend on + the deflections (see :ref:`surface_controls`). The sign of each moment + coefficient is given in :ref:`genericsurfaces`. + + The controller is written the same way for both. + +Setting Up The Simulation +------------------------- + +First, everything up to the rocket. Note the ``cant_angle`` of the tail fins: +it is what makes the rocket roll. + +.. jupyter-execute:: + + from rocketpy import Environment, SolidMotor, Rocket, Flight + + env = Environment(latitude=32.990254, longitude=-106.974998, elevation=1400) + + Pro75M1670 = SolidMotor( + thrust_source="../data/motors/cesaroni/Cesaroni_M1670.eng", + dry_mass=1.815, + dry_inertia=(0.125, 0.125, 0.002), + nozzle_radius=33 / 1000, + grain_number=5, + grain_density=1815, + grain_outer_radius=33 / 1000, + grain_initial_inner_radius=15 / 1000, + grain_initial_height=120 / 1000, + grain_separation=5 / 1000, + grains_center_of_mass_position=0.397, + center_of_dry_mass_position=0.317, + nozzle_position=0, + burn_time=3.9, + throat_radius=11 / 1000, + coordinate_system_orientation="nozzle_to_combustion_chamber", + ) + + calisto = Rocket( + radius=127 / 2000, + mass=14.426, + inertia=(6.321, 6.321, 0.034), + power_off_drag="../data/rockets/calisto/powerOffDragCurve.csv", + power_on_drag="../data/rockets/calisto/powerOnDragCurve.csv", + center_of_mass_without_motor=0, + coordinate_system_orientation="tail_to_nose", + ) + + calisto.set_rail_buttons( + upper_button_position=0.0818, + lower_button_position=-0.618, + angular_position=45, + ) + + calisto.add_motor(Pro75M1670, position=-1.255) + + calisto.add_nose(length=0.55829, kind="vonKarman", position=1.278) + + calisto.add_trapezoidal_fins( + n=4, + root_chord=0.120, + tip_chord=0.060, + span=0.110, + position=-1.04956, + cant_angle=0.5, + airfoil=("../data/airfoils/NACA0012-radians.txt", "radians"), + ) + + calisto.add_tail( + top_radius=0.0635, bottom_radius=0.0435, length=0.060, position=-1.194656 + ) + +We keep a copy of the rocket as it is now, without canards, to build the +variants at the end of this page from it. + +.. jupyter-execute:: + + from copy import deepcopy + + calisto_without_canards = deepcopy(calisto) + +Adding the Canards +------------------ + +A :class:`rocketpy.ControlFins` is built from one fin, copied ``n`` times +around the rocket, or from a list of fins given one by one +(``ControlFins([fin_a, fin_b])``). Each fin has one control, its deflection in +radians, named ``fin_1`` to ``fin_n``. ``fin_1`` sits at the +``angular_position`` of the fin given and the others follow as the angular +position grows: four fins starting at 0° sit at 0°, 90°, 180° and 270°. + +A deflection turns a fin about its hinge line, exactly as a cant angle does. +So **a positive deflection rolls the rocket toward negative** ``w3``, the +angular velocity about the rocket's axis: to oppose a roll rate, deflect the +fins with the sign of that rate. One fin deflected alone pushes the rocket +sideways at that fin. :ref:`controlfins_which_fin` gives where each fin sits +and which way it turns, and :ref:`controlfins_commands` how to command the +set by roll, pitch and yaw without minding these signs. + +``hinge_position`` is where the hinge line crosses the root chord, as a +fraction of its length from the leading edge; the default, 0.5, is where a +cant angle turns a fixed fin. The fin model has no stall, so keep the +deflections small, a few tenths of a radian at most. + +``deflection_limits`` is the most a fin can turn, in radians. A controller +that asks for more gets the limit. + +.. _controlfins_model: + +.. important:: + + The forces of the fins are computed from their shape, not measured. They + come from the Barrowman method, the model RocketPy uses for fixed fins + (see :ref:`individual_fins`), with each fin turned by its deflection. The + limits of that method apply here too: + + - **Small angles.** The force of a fin grows in proportion to its + deflection plus the angle of attack it meets, so a fin never stalls. + - **Subsonic flight.** The method was derived for subsonic flow. It is + corrected for the Mach number up to Mach 0.8 and is not valid near and + above Mach 1. + - **Each fin alone.** The effect of one fin on its neighbors, the effect + of canards on the tail fins and the gap between a turning fin and the + body are left out. + - **A fixed center of pressure.** The force of a fin always acts at the + same point of the fin. + - **No drag of the fin itself.** A deflected fin adds drag only because + its force then leans back. + + The roll moment, the sideways force and the hinge torque on this page all + come from this model, so read them as estimates, best at low speed and + small angles. If you have wind tunnel or CFD data for your fins, use it + instead: a :class:`rocketpy.GenericSurface` takes coefficients given as + functions of the deflections (see :ref:`surface_controls`). + +.. jupyter-execute:: + + from rocketpy import ControlFins, TrapezoidalFin + + canard = TrapezoidalFin( + root_chord=0.05, + tip_chord=0.025, + span=0.04, + rocket_radius=calisto.radius, + angular_position=0, + ) + + canards = ControlFins( + canard, + n=4, + name="Canards", + deflection_limits=(-0.2, 0.2), + ) + + calisto.add_surfaces(canards, positions=0.3) + + canards.info() + +The name of the set names its control inputs: ``"Canards"`` gives +``canards.fin_1`` and so on, which is how a controller writes them. + +.. jupyter-execute:: + + calisto.control_names + +.. _controlfins_which_fin: + +Which Fin Is Which +~~~~~~~~~~~~~~~~~~ + +To fly the controller you design here on a real rocket, each ``fin_i`` must be +the right fin of the rocket, and a positive deflection must turn it the right +way. Both follow from the rocket's body axes: ``z`` runs along the rocket +toward the nose, and ``x`` and ``y`` are fixed to the airframe (see +:ref:`rocket_axes`). + +- **Where a fin sits** is its angular position: the angle from the ``+y`` axis + to the fin, growing counterclockwise when you look at the rocket from the + nose toward the tail (see :ref:`Angular Position Inputs `). +- **Which way it turns**: seen from the nose, a positive deflection moves the + leading edge of every fin (the edge nearer the nose) clockwise around the + rocket. The air then pushes the rocket, at that fin, the way the leading + edge moved. + +For the four canards of this page, with the sides and directions given in the +body axes: + +.. list-table:: + :header-rows: 1 + :widths: 14 18 18 25 25 + + * - Control + - Angular position + - Side of the rocket + - A positive deflection moves the leading edge toward + - and pushes the rocket there toward + * - ``fin_1`` + - 0° + - ``+y`` + - ``+x`` + - ``+x`` + * - ``fin_2`` + - 90° + - ``-x`` + - ``+y`` + - ``+y`` + * - ``fin_3`` + - 180° + - ``-y`` + - ``-x`` + - ``-x`` + * - ``fin_4`` + - 270° + - ``+x`` + - ``-y`` + - ``-y`` + +To match this to your rocket: + +1. Mark the line along the airframe that is your ``+y`` side. Every angular + position is measured from it: those of the fins and of the rail buttons. + The rail buttons' ``angular_position`` and the launch ``heading`` set + where that line points on the pad. +2. Give the fin handed to ``ControlFins`` the ``angular_position`` of the fin + your first servo turns. The other fins are numbered counterclockwise from + it, seen from the nose. If your servos are numbered in another order, or + the fins are not evenly spaced, give the fins one by one in your own + order: ``ControlFins([fin_a, fin_b, fin_c, fin_d])``, each built with its + own ``angular_position``. +3. With the rocket on the ground, command a small positive angle to one servo + and look at the rocket from the nose. The leading edge of that fin must + move clockwise. If it moves the other way, change the sign of that servo + in the flight computer. Deflections are in radians. +4. Match the gyroscope of your flight computer to the angular velocities a + controller reads here. ``w1``, ``w2`` and ``w3`` are the angular velocities + about the body ``x``, ``y`` and ``z`` axes, each positive by the right-hand + rule: + + .. list-table:: + :header-rows: 1 + :widths: 20 20 60 + + * - Angular velocity + - About + - When it is positive + * - ``w1`` + - ``x`` + - the nose moves toward ``-y`` + * - ``w2`` + - ``y`` + - the nose moves toward ``+x`` + * - ``w3`` + - ``z`` + - seen from the nose, the rocket turns counterclockwise + + A gyroscope whose axes are not the body axes reads other components. Add + it to the rocket as a sensor with its ``orientation`` and read it with + ``context.sensors`` (see :ref:`sensorsusage`). + +.. _controlfins_commands: + +The Commands and What They Do +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A controller rarely thinks in single fins. ``canards.deflections`` turns a +roll, a pitch and a yaw command into the deflection of every fin. A positive +command turns the rocket toward the positive angular velocity of that name: + +.. list-table:: + :header-rows: 1 + :widths: 20 40 40 + + * - Command + - Angular velocity it raises + - What you see + * - ``roll`` + - ``w3`` + - seen from the nose, the rocket turns counterclockwise + * - ``pitch`` + - ``w1`` + - the nose moves toward ``-y`` + * - ``yaw`` + - ``w2`` + - the nose moves toward ``+x`` + +This holds wherever the set sits. Canards and movable tail fins turn opposite +ways for the same pitch or yaw command, and the set works that out from where +it was added to the rocket. A controller that opposes the three angular +velocities therefore uses ``roll=-K * w3``, ``pitch=-K * w1`` and +``yaw=-K * w2``, on canards and on tail fins alike. + +.. jupyter-execute:: + + print("roll: ", canards.deflections(roll=0.02)) + print("pitch:", canards.deflections(pitch=0.05)) + print("yaw: ", canards.deflections(yaw=0.05)) + print("all: ", canards.deflections(roll=0.02, yaw=0.05)) + +.. note:: + + The pitch and yaw commands need the set to be on a rocket, since they + depend on which side of the center of dry mass it is. Build the set, add + it with ``add_surfaces``, then call ``deflections``. + +How much each command does is ``canards.effectiveness``: the moment +coefficient per radian of each command, as functions of Mach. Multiplied by +the dynamic pressure, the reference area and the reference length they are +the moments in N m per radian, the gains a control design starts from. Here +for a command of 0.05 rad at Mach 0.3: + +.. jupyter-execute:: + + effectiveness = canards.effectiveness() + canards.plots.effectiveness() + + mach = 0.3 + dynamic_pressure = 5500 # Pa, near Mach 0.3 at this altitude + command = 0.05 # rad + to_moment = dynamic_pressure * canards.reference_area * canards.reference_length + for name in ("roll", "pitch", "yaw"): + moment = effectiveness[name](mach) * to_moment * command + print(f"{name}={command}: a moment of {moment:+.3f} N m") + +The pitch and yaw moments are taken about the rocket's center of dry mass, +where the center of mass is once the propellant has burned. While the motor +burns the center of mass is further aft, so these canards turn the rocket a +little more than the numbers say. Divide a moment by the rocket's moment of +inertia about that axis to get the angular acceleration it causes. + +The torque the air puts on each fin about its hinge line, the load the +mechanism turning the fin has to hold, is ``canards.hinge_moments``: one +function of Mach per fin, in N m, at a dynamic pressure and a set of +deflections you give. It is the fin's normal force times the distance from +the hinge line to the fin's center of pressure, so it depends on +``hinge_position``. The fin model gives one fixed center of pressure, while +the real one moves with speed and angle of attack, so with the hinge close to +it trust the size of the torque, not its sign. + +.. jupyter-execute:: + + torque = canards.hinge_moments(dynamic_pressure=30e3, deflections=0.1) + print(f"Torque on fin 1 at Mach 0.3: {torque['fin_1'](0.3):.3f} N m") + +Canards ahead of the center of mass move the center of pressure forward, so +check the stability margin is still what you want: + +.. jupyter-execute:: + + calisto.plots.stability_margin() + +Writing the Controller +---------------------- + +The controller is a function of one argument, the context, called at the +sampling rate. It reads the roll rate, ``context.state.w3`` in rad/s, and +writes the four deflections. This one is a PI controller: the proportional +term damps the roll rate, the integral term finds the steady deflection that +cancels the canted tail fins. The integral is what the next call needs, so it +lives in ``context.memory``; what we want to look at afterwards goes to +``context.record``. + +.. jupyter-execute:: + + from rocketpy import Controller + + KP = 0.02 # rad of roll command per rad/s of roll rate + KI = 0.2 # rad of roll command per rad of accumulated roll + TARGET = 0.0 # rad/s + + def roll_controller(context): + error = context.state.w3 - TARGET + context.memory["integral"] += error * context.dt + # Against the error: a positive roll command raises w3 + roll = -(KP * error + KI * context.memory["integral"]) + context.controls.canards.update(canards.deflections(roll=roll)) + context.record(error=error, roll=roll) + + roll_control = Controller( + roll_controller, + sampling_rate=100, + memory={"integral": 0.0}, + name="Roll Control", + ) + + calisto.add_controller(roll_control) + + roll_control.info() + +A few things worth knowing: + +- ``context.dt`` is the time since the controller last ran, ``1 / sampling_rate`` + on the first call. +- ``context.memory`` starts again from ``{"integral": 0.0}`` at every flight, so + the rocket can be flown many times, in a Monte Carlo study for instance, + with no leftover from the previous flight. +- A deflection outside ``(-0.2, 0.2)`` is clamped when the function returns. +- The controller only writes the deflection; the fins keep it until the next + sample. To read the latest sensor values instead of the true state, use + ``context.sensors``; see :ref:`sensorsusage`. + +If your flight computer already computes one angle per servo, write each fin +yourself, with your own mixing, in place of ``canards.deflections``. This +one holds the roll and damps the pitch and yaw rates: + +.. code-block:: python + + K_ROLL = 0.02 # rad of deflection per rad/s of roll rate + K_RATE = 0.05 # rad of deflection per rad/s of pitch or yaw rate + + def flight_computer(context): + state = context.state + roll = K_ROLL * state.w3 + fins = context.controls.canards + fins.fin_1 = roll - K_RATE * state.w2 # on +y, pushes toward +x + fins.fin_2 = roll + K_RATE * state.w1 # on -x, pushes toward +y + fins.fin_3 = roll + K_RATE * state.w2 # on -y, pushes toward -x + fins.fin_4 = roll - K_RATE * state.w1 # on +x, pushes toward -y + + calisto.add_controller(Controller(flight_computer, sampling_rate=100)) + +RocketPy computes the forces and moments from the four deflections, so +simulating a controller you have already designed needs no gain from this +page: only the right fin, the right sign and the right axes, as in +:ref:`controlfins_which_fin`. A fin in the wrong place or a wrong sign makes +the flight diverge, which looks the same as a badly tuned controller. To tell +them apart, fly a few seconds with one fixed small deflection and no control +law, and check that ``w1``, ``w2`` and ``w3`` move the way your rocket would. + +Simulating a Flight +------------------- + +.. jupyter-execute:: + + test_flight = Flight( + rocket=calisto, + environment=env, + rail_length=5.2, + inclination=85, + heading=0, + terminate_on_apogee=True, + ) + +Analyzing the Results +--------------------- + +The deflections the fins flew with are stored with the flight. +``flight.solution.controls`` holds each one as an array of time and value and +``flight.controls`` as a function of time, by the set's name as given or in +snake_case, and ``flight.plots.controls()`` draws them all, held between +samples as they were in flight. + +.. jupyter-execute:: + + test_flight.plots.controls() + + fin_1 = test_flight.controls.canards.fin_1 + print(f"Deflection at 2 s: {fin_1(2.0):.4f} rad") + print(f"Deflection at 10 s: {fin_1(10.0):.4f} rad") + +The torque the air put on each fin about its hinge line during the flight, +from the air the set met and the deflections it flew with: + +.. jupyter-execute:: + + canards.plots.hinge_moments(test_flight) + +The roll rate the controller was holding: + +.. jupyter-execute:: + + test_flight.w3.plot(0, test_flight.apogee_time) + +What the function recorded is in ``flight.records``, named after the +controller: + +.. jupyter-execute:: + + test_flight.plots.records() + test_flight.prints.controls() + +Compare with the same rocket and no canards, which the canted tail fins spin +up: + +.. jupyter-execute:: + + uncontrolled_flight = Flight( + rocket=calisto_without_canards, + environment=env, + rail_length=5.2, + inclination=85, + heading=0, + terminate_on_apogee=True, + ) + uncontrolled_flight.w3.plot(0, uncontrolled_flight.apogee_time) + +The rocket itself was not changed by flying: ``canards`` is still at its +default deflection, and the next flight starts from it again. + +Steering With the Fins +---------------------- + +The roll controller gives every fin the same deflection. A pitch or yaw +command does not: here the same controller also gives a yaw command for one +second of the coast, from 6 s to 7 s. + +.. jupyter-execute:: + + def steering_controller(context): + error = context.state.w3 - TARGET + context.memory["integral"] += error * context.dt + roll = -(KP * error + KI * context.memory["integral"]) + yaw = 0.05 if 6 <= context.time < 7 else 0.0 + context.controls.canards.update(canards.deflections(roll=roll, yaw=yaw)) + + steering_canards = ControlFins( + canard, n=4, name="Canards", deflection_limits=(-0.2, 0.2) + ) + calisto_steered = deepcopy(calisto_without_canards) + calisto_steered.add_surfaces(steering_canards, positions=0.3) + calisto_steered.add_controller( + Controller( + steering_controller, + sampling_rate=100, + memory={"integral": 0.0}, + name="Steering", + ) + ) + + steered_flight = Flight( + rocket=calisto_steered, + environment=env, + rail_length=5.2, + inclination=85, + heading=0, + terminate_on_apogee=True, + ) + +During that second ``fin_1`` (on ``+y``) and ``fin_3`` (on ``-y``) move apart +by the yaw command, on top of the deflection that holds the roll, while +``fin_2`` and ``fin_4`` keep it: + +.. jupyter-execute:: + + for name in steering_canards.controls: + deflection = steered_flight.controls.canards[name] + print(f"{name}: {deflection(5.5):+.4f} rad at 5.5 s, {deflection(6.5):+.4f} rad at 6.5 s") + + steered_flight.plots.controls() + +Each fin now carries its own load: + +.. jupyter-execute:: + + steering_canards.plots.hinge_moments(steered_flight) + +The positive yaw command raises ``w2``, the angular velocity about the body +``y`` axis: the nose turns toward the rocket's ``+x`` side by about one +degree, and the flight path follows it. Compared with ``test_flight``, which +only holds the roll, the rocket moves away sideways from the moment of the +command: + +.. jupyter-execute:: + + def distance_apart(time): + east = steered_flight.x(time) - test_flight.x(time) + north = steered_flight.y(time) - test_flight.y(time) + return (east**2 + north**2) ** 0.5 + + apogee_time = min(steered_flight.apogee_time, test_flight.apogee_time) + for time in (6, 7, 10, 15, apogee_time): + print(f"{time:5.1f} s: {distance_apart(time):5.1f} m apart") + +A Continuous Controller +----------------------- + +The controller above runs 100 times a second and holds its output in between, +as a flight computer does. To study the law without the sampling, as control +theory writes it, use a :class:`rocketpy.ContinuousController`: its law runs +inside the equations of motion, at every instant. It gets the flight's +conditions, its own states and the dictionary of control inputs, which it +writes. +The integral term is a state of the controller, with its derivative: + +.. jupyter-execute:: + + from rocketpy import ContinuousController + + def integral_derivative(states, controls, conditions): + return [conditions.state.w3 - TARGET] + + def continuous_roll_law(states, controls, conditions): + roll = -(KP * (conditions.state.w3 - TARGET) + KI * states[0]) + controls.canards.update(canards.deflections(roll=roll)) + + continuous_roll_control = ContinuousController( + continuous_roll_law, + states=("integral",), + state_derivative=integral_derivative, + name="Roll Control", + ) + + calisto_continuous = deepcopy(calisto_without_canards) + calisto_continuous.add_surfaces( + ControlFins(canard, n=4, name="Canards", deflection_limits=(-0.2, 0.2)), + positions=0.3, + ) + calisto_continuous.add_controller(continuous_roll_control) + + continuous_flight = Flight( + rocket=calisto_continuous, + environment=env, + rail_length=5.2, + inclination=85, + heading=0, + terminate_on_apogee=True, + ) + continuous_flight.w3.plot(0, continuous_flight.apogee_time) + +A continuous controller has no memory, records or commands. The deflections +it wrote are kept with every stored row of the flight, in +``flight.controls.canards.fin_1``, and its integral is a state of the flight, +``flight.state_history.roll_control.integral``. + +If the sampled controller behaves like the continuous one, the sampling rate +is high enough. If it oscillates where the continuous one does not, the rate +is too low for these gains. + +.. _controlfins_not_covered: + +Not Covered +----------- + +- The interference between the canards and the tail fins. Each surface is + computed on its own, so the swirl a deflected canard sends to the tail, which + reduces the roll the canards give and can reverse it, is not modelled. The + effectiveness above is that of the canards alone. +- Stall. The force of a fin grows in proportion to its deflection plus the + angle of attack it meets, without limit. Past a few tenths of a radian a + real fin loses force, so a simulated controller that asks for large + deflections has more authority than the real one. +- The servos. A fin takes its deflection the instant the controller writes + it. The time a servo needs to get there and the speed it can turn at are + not modelled yet. +- There is no stochastic version of ``ControlFins`` yet: a Monte Carlo study + flies the set unchanged in every sampled rocket. + +.. seealso:: + + :ref:`controllers` for everything a controller can read and do, the + other things it can move, and how controllers share values. + :class:`rocketpy.ControlFins` for the class itself. diff --git a/docs/user/controllers.rst b/docs/user/controllers.rst new file mode 100644 index 000000000..8a0d76fb4 --- /dev/null +++ b/docs/user/controllers.rst @@ -0,0 +1,504 @@ +.. _controllers: + +Controllers and Effectors +========================= + +A **controller** is a function you write that reads what the rocket is doing +and sets the rocket's **control inputs**: how far the air brakes are deployed, +the angle of each canard, how hard a thruster fires. An **effector** is a part +you describe with a function, which pushes the rocket or turns the motor's +thrust according to its control inputs. + +A controlled flight takes three steps: + +1. Add to the rocket something that has control inputs: an effector, air + brakes (:ref:`airbrakes`), control fins (:ref:`controlfins`) or a surface + with controls (:ref:`genericsurfaces`). +2. Add a controller that writes those control inputs. +3. Fly, and read what the controller did from the flight. + +Effectors +--------- + +An effector is built from a function and a list of control names. Each control +becomes a control input named ``.``, with the +effector's name in snake_case: an effector named ``"Wheel"`` with a +control ``command`` gives ``wheel.command``. +``rocket.control_names`` lists every control input of the rocket. + +- ``controls``: the names of the controls. +- ``control_limits``: the lowest and highest value of each control. What a + controller writes is kept inside them. +- ``control_defaults``: the value of each control at the start of the flight + (0 when not given). + +Force effector +~~~~~~~~~~~~~~ + +A :class:`rocketpy.ForceEffector` applies a force and a moment to the rocket. +Its function receives one value per control, then ``conditions``, and returns +the force in N and the moment in N m, both in the rocket's body axes +(:ref:`rocket_axes`): + +.. code-block:: python + + def thruster(firing, conditions): + # 5 N toward +x while firing + return [5.0 * firing, 0, 0], [0, 0, 0] + + rcs = ForceEffector( + thruster, + controls=("firing",), + control_limits={"firing": (0, 1)}, + name="RCS", + ) + rocket.add_effector(rcs, position=1.4) + +``position`` is where the force acts along the rocket, in the rocket's +coordinate system, as for a fin. ``angular_position`` (in degrees) and +``radius`` (in m) place it around the tube. The moment that the force causes +about the center of dry mass is added for you, so the function returns only a +moment that comes with no force, like the torque of a reaction wheel. Without +a position, the force acts at the center of dry mass. + +Thrust effector +~~~~~~~~~~~~~~~ + +A :class:`rocketpy.ThrustEffector` changes the motor's thrust. Its function +receives the thrust vector in N and the position of the nozzle exit in m, both +in the body axes, then one value per control, then ``conditions``. It returns +the new thrust and the new nozzle exit position: + +.. code-block:: python + + import math + from rocketpy import ThrustEffector + + def vanes(thrust, nozzle, pitch, conditions): + # jet vanes turn the thrust by the angle ``pitch`` and keep the exit in place + turned = [thrust[2] * math.sin(pitch), thrust[1], thrust[2] * math.cos(pitch)] + return turned, nozzle + + rocket.add_effector( + ThrustEffector( + vanes, + controls=("pitch",), + control_limits={"pitch": (-0.1, 0.1)}, + name="Vanes", + ) + ) + +A gimbal also moves the nozzle exit, so its function returns the moved +position. + +The conditions +~~~~~~~~~~~~~~ + +``conditions`` describes the flight at that moment: ``conditions.time``, +``conditions.state`` (``conditions.state.vz``, ``conditions.state.w3``, ...), +``conditions.height_agl``, ``conditions.pressure``, ``conditions.density``, +``conditions.mach`` and ``conditions.stream_velocity``. See +:class:`rocketpy.control.FlightConditions`. + +The controller function +----------------------- + +A :class:`rocketpy.Controller` calls your function ``sampling_rate`` times a +second. What the function writes stays in force until the next call. The +function takes one argument, ``context``: + +- ``context.time``, and ``context.dt``, the time since the previous call. +- ``context.state``: the rocket's states by name. ``state.x``, ``state.y``, + ``state.z`` are the position, ``state.vx``, ``state.vy``, ``state.vz`` the + velocity, ``state.e0`` to ``state.e3`` the attitude quaternion and + ``state.w1``, ``state.w2``, ``state.w3`` the angular velocity in the body + axes. +- ``context.state_dot``: the derivative of each state with respect to time, + ``state_dot.az`` for the vertical acceleration. +- ``context.sensors``: the latest reading of each sensor on the rocket, + ``context.sensors.accelerometer.az``. Use these instead of ``state`` to fly + the controller on what a real flight computer measures. See + :ref:`sensorsusage`. +- ``context.controls``: the control inputs, to read and to write: + ``context.controls.wheel.command = 1``. When the name is built in a + loop, write ``context.controls.canards[fin]``. +- ``context.memory``: a dictionary of your own, kept from one call to the + next: an integral, a filter value, a counter. It starts every flight at the + ``memory`` given to the controller. +- ``context.record(name=value, ...)``: keep values with their time, to read + after the flight in ``flight.records``. The function's return value is + ignored. +- ``context.outputs``: values a controller computes for other controllers to + read. See below. +- ``context.commands``: change how the flight goes on, + ``context.commands.disable()`` stops the controller. +- ``context.height_agl``, ``context.pressure``, ``context.mach``, + ``context.rocket``, ``context.environment``: read them, never change the + rocket or the environment. + +The full list is in :ref:`eventusage`. A controller with memory and records: + +.. code-block:: python + + def pi_function(context): + error = TARGET_RATE - context.state.w3 + integral = context.memory["integral"] + error * context.dt + context.memory["integral"] = integral + context.controls.wheel.command = KP * error + KI * integral + context.record(error=error) + + controller = Controller( + pi_function, + sampling_rate=50, + memory={"integral": 0.0}, + name="Roll PI", + ) + +The controller options +~~~~~~~~~~~~~~~~~~~~~~ + +- ``sampling_rate``: how many times a second the function runs, in Hz. +- ``name``: the name the controller's records and outputs are read under. +- ``memory``: the starting content of ``context.memory``. +- ``enabled``: whether the controller runs from the start of the flight + (``True`` by default). +- ``enable_on`` and ``disable_on``: when to start and stop it. Each takes + ``"burnout"``, ``"apogee"`` or another preset of :ref:`eventusage`, a time + in seconds, or a function of the context that returns ``True``. A controller + that should wait for ``enable_on`` needs ``enabled=False``. +- ``outputs``: the names of the values it shares with other controllers. + +Several controllers run in the order they were added to the rocket. + +Sharing values between controllers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A controller writes its outputs, and any other controller reads them, through +``context.outputs``, under the name of the controller that declared them: + +.. code-block:: python + + def guidance_function(context): + context.outputs.guidance.rate_setpoint = 0.5 if context.time < 8 else 0.0 + + def attitude_function(context): + error = context.outputs.guidance.rate_setpoint - context.state.w3 + ... + + guidance = Controller(guidance_function, sampling_rate=10, + name="Guidance", outputs=("rate_setpoint",)) + attitude = Controller(attitude_function, sampling_rate=100, name="Attitude") + rocket.add_controller(guidance) + rocket.add_controller(attitude) + +An output keeps its value until it is written again. It starts every flight as +``None``, or at the value given with a dictionary +(``outputs={"rate_setpoint": 0.2}``). + +.. _continuous_controller: + +The continuous controller +------------------------- + +A :class:`rocketpy.ContinuousController` has no sampling rate: its law acts at +every instant of the flight. Use it to study a control law before choosing a +sampling rate. The law receives the controller's own states, the control +inputs and the conditions: + +.. code-block:: python + + from rocketpy import ContinuousController + + def roll_law(states, controls, conditions): + controls.wheel.command = -2.0 * conditions.state.w3 + + rocket.add_controller(ContinuousController(roll_law, name="Roll Law")) + +A continuous controller has no ``context``, so no memory, records, outputs or +commands. A value it must keep over time, like an integral, is declared with +``states`` and ``state_derivative``. :ref:`controlfins` flies the same law as +a sampled and as a continuous controller, and shows fins that take time to +reach the angle they are told. + +Reading the results +------------------- + +.. code-block:: python + + flight.controls.wheel.command # a control input, as a Function of time + flight.controls.wheel.command(10.0) # its value at 10 s + flight.records.roll_controller.error # a list of (time, value) pairs + flight.event_outputs.guidance.rate_setpoint # a list of (time, value) pairs + + flight.plots.controls() + flight.plots.records() + flight.prints.controls() + flight.prints.controllers() + + controller.info() + wheel.info() + +A flight never changes the rocket: the next flight starts from the default +value of every control input and from each controller's starting memory. + +Under a parachute the air brakes, the control fins and the effectors do +nothing: the descent does not depend on any control input. A controller still +runs there and what it writes is kept, but ``flight.controls`` then has the +control input only at the times of the solver's steps, which are far apart +during a descent. To keep a value at every sample use ``context.record``, and +to stop a controller that is no longer needed give it ``disable_on="apogee"``. + +.. note:: + + In a Monte Carlo study, every sampled rocket flies the same control loop + as the rocket it is sampled from: its effectors, its controllers and its + sensors are carried into each sample. The loop itself is not dispersed + (gains, sampling rates and sensor settings are the same in every sample). + +Example: roll control with a reaction wheel +------------------------------------------- + +A rocket whose fins are slightly canted rolls all the way up. Here a reaction +wheel stops that roll after burnout, then holds a slow roll, with a gyroscope +as the only measurement. A reaction wheel is a flywheel on the rocket's axis: +when its motor speeds it up one way, the rocket is turned the other way. It +burns nothing, so the rocket's mass does not change, but it can only store so +much angular momentum before it reaches its top speed. + +First the rocket, with a ``cant_angle`` on the fins to make it roll: + +.. jupyter-execute:: + + from copy import deepcopy + + from rocketpy import Environment, SolidMotor, Rocket, Flight + + env = Environment(latitude=32.990254, longitude=-106.974998, elevation=1400) + + Pro75M1670 = SolidMotor( + thrust_source="../data/motors/cesaroni/Cesaroni_M1670.eng", + dry_mass=1.815, + dry_inertia=(0.125, 0.125, 0.002), + nozzle_radius=33 / 1000, + grain_number=5, + grain_density=1815, + grain_outer_radius=33 / 1000, + grain_initial_inner_radius=15 / 1000, + grain_initial_height=120 / 1000, + grain_separation=5 / 1000, + grains_center_of_mass_position=0.397, + center_of_dry_mass_position=0.317, + nozzle_position=0, + burn_time=3.9, + throat_radius=11 / 1000, + coordinate_system_orientation="nozzle_to_combustion_chamber", + ) + + calisto = Rocket( + radius=127 / 2000, + mass=14.426, + inertia=(6.321, 6.321, 0.034), + power_off_drag="../data/rockets/calisto/powerOffDragCurve.csv", + power_on_drag="../data/rockets/calisto/powerOnDragCurve.csv", + center_of_mass_without_motor=0, + coordinate_system_orientation="tail_to_nose", + ) + + calisto.set_rail_buttons( + upper_button_position=0.0818, + lower_button_position=-0.618, + angular_position=45, + ) + + calisto.add_motor(Pro75M1670, position=-1.255) + calisto.add_nose(length=0.55829, kind="vonKarman", position=1.278) + calisto.add_trapezoidal_fins( + n=4, + root_chord=0.120, + tip_chord=0.060, + span=0.110, + position=-1.04956, + cant_angle=0.02, + ) + + calisto.add_tail( + top_radius=0.0635, bottom_radius=0.0435, length=0.060, position=-1.194656 + ) + + # A copy without the wheel, to compare with at the end + calisto_without_wheel = deepcopy(calisto) + +| + +**The sensor.** The flight computer does not know the true roll rate: it reads +a gyroscope, with noise and a small bias. + +.. jupyter-execute:: + + from rocketpy import Gyroscope + + gyroscope = Gyroscope( + sampling_rate=100, + noise_density=0.01, + constant_bias=0.02, + name="Gyroscope", + ) + calisto.add_sensor(gyroscope, position=0.2) + +**The effector.** The wheel turns the rocket about its axis without pushing +it. That is a :class:`rocketpy.ForceEffector` whose function returns no force +and a roll moment. Its one control, ``command``, goes from -1 (full torque one +way) to 1 (full torque the other way): + +.. jupyter-execute:: + + from rocketpy import ForceEffector + + MAX_TORQUE = 0.1 # N m, the most the wheel's motor gives + + def wheel_torque(command, conditions): + force = [0, 0, 0] + moment = [0, 0, MAX_TORQUE * command] # about the rocket's axis + return force, moment + + wheel = ForceEffector( + wheel_torque, + controls=("command",), + control_limits={"command": (-1, 1)}, + control_defaults={"command": 0}, + name="Wheel", + ) + calisto.add_effector(wheel) + + print(calisto.control_names) + +**The guidance.** A first controller decides the roll rate the rocket should +have: none until 12 s, then 1 rad/s. It runs 10 times a second, starts at +burnout, and shares the target as an output: + +.. jupyter-execute:: + + from rocketpy import Controller + + def guidance_function(context): + context.outputs.guidance.roll_rate_target = 0.0 if context.time < 12 else 1.0 + + guidance = Controller( + guidance_function, + sampling_rate=10, + name="Guidance", + outputs=("roll_rate_target",), + enabled=False, + enable_on="burnout", + disable_on="apogee", + ) + calisto.add_controller(guidance) + +**The roll controller.** A second controller runs 50 times a second and +drives the wheel to reach the target. It: + +- waits while the target is ``None``, which is the case until the guidance + first runs; +- reads the gyroscope and smooths the reading, keeping the smoothed value in + its memory; +- works out the command from the error and from the integral of the error, + also kept in its memory; +- adds up the angular momentum the wheel has stored, and when the wheel is at + its top speed it stops the torque and disables itself; +- records the reading, the error and the stored momentum. + +.. jupyter-execute:: + + KP = 2.0 # command per rad/s of error + KI = 1.0 # command per rad of accumulated error + SMOOTHING = 0.3 # share of each new reading in the smoothed roll rate + MAX_MOMENTUM = 1.0 # N m s, what the wheel stores at its top speed + + def roll_function(context): + target = context.outputs.guidance.roll_rate_target + if target is None: # the guidance has not started yet + return + + memory = context.memory + measured = context.sensors.gyroscope.wz + memory["smoothed"] += SMOOTHING * (measured - memory["smoothed"]) + + error = target - memory["smoothed"] + command = KP * error + KI * memory["integral"] + if abs(command) < 1: # stop adding up while at full torque + memory["integral"] += error * context.dt + command = max(-1, min(1, command)) + + # the wheel gains what it gives the rocket, with the opposite sign + memory["momentum"] -= MAX_TORQUE * command * context.dt + if abs(memory["momentum"]) > MAX_MOMENTUM: + context.controls.wheel.command = 0 + context.commands.disable() + return + + context.controls.wheel.command = command + context.record(measured=measured, error=error, momentum=memory["momentum"]) + + roll = Controller( + roll_function, + sampling_rate=50, + name="Roll Controller", + memory={"smoothed": 0.0, "integral": 0.0, "momentum": 0.0}, + disable_on="apogee", + ) + calisto.add_controller(roll) + + wheel.info() + guidance.info() + roll.info() + +**The flight.** Nothing changes in the :class:`rocketpy.Flight`: it finds the +sensor, the wheel and the controllers on the rocket. + +.. jupyter-execute:: + + flight = Flight( + rocket=calisto, + environment=env, + rail_length=5.2, + inclination=85, + heading=0, + terminate_on_apogee=True, + ) + flight_without_wheel = Flight( + rocket=calisto_without_wheel, + environment=env, + rail_length=5.2, + inclination=85, + heading=0, + terminate_on_apogee=True, + ) + +**The results.** The wheel stops the roll, then brings it to 1 rad/s, until +it reaches its top speed and the canted fins take over again: + +.. jupyter-execute:: + + flight.prints.controllers() + flight.prints.controls() + flight.plots.controls() + flight.plots.records() + + command = flight.controls.wheel.command + target = flight.event_outputs.guidance.roll_rate_target + momentum = flight.records.roll_controller.momentum + print(f"Command at 10 s: {command(10.0):.2f}") + print(f"First target: {target[0][1]} at {target[0][0]:.1f} s") + print(f"Wheel at its top speed at {momentum[-1][0]:.2f} s") + for time in (5, 10, 16, 20): + print( + f"Roll rate at {time} s: {flight.w3(time):.2f} rad/s with the wheel, " + f"{flight_without_wheel.w3(time):.2f} rad/s without" + ) + +See also +-------- + +- :ref:`eventusage` for everything a controller function can read and do. +- :ref:`airbrakes` and :ref:`controlfins` for complete examples. +- :ref:`sensorsusage` for feeding a controller with sensor readings. diff --git a/docs/user/event_usage.rst b/docs/user/event_usage.rst index 596c539ad..2f5c3c653 100644 --- a/docs/user/event_usage.rst +++ b/docs/user/event_usage.rst @@ -1,8 +1,8 @@ +.. _eventusage: + Event Usage =========== -.. _eventusage: - This page explains how to build and use :class:`rocketpy.Event` objects in a RocketPy simulation. It focuses on practical usage: how to write a custom event, how the trigger and callback flow works, and which configuration @@ -161,8 +161,14 @@ The following values are available: that state's name followed by ``_dot``, so for a state the phase calls ``my_state`` it is ``context.state_dot.my_state_dot``. Worked out when first read, by evaluating the equations of motion once more. -- ``pressure`` (float): Current atmospheric pressure in Pa at the rocket's - altitude. Worked out when first read. +- The air around the rocket at this moment, each worked out when first + read: ``context.pressure`` (Pa), ``context.density`` (kg/m³), + ``context.speed_of_sound`` (m/s), ``context.mach``, + ``context.wind_velocity`` (m/s, Earth frame), ``context.stream_velocity`` + (m/s, in the rocket's body frame) and ``context.stream_speed`` (m/s). They + are the values a controllable's methods receive as ``conditions`` inside the + equations of motion (:class:`rocketpy.control.FlightConditions`), also + available as one object, ``context.conditions``, to hand on. - ``previous_state``: The ``state`` from the previous time this same event was checked, or ``None`` on the first check. It is read like ``state``, as ``context.previous_state.vz``. @@ -184,63 +190,127 @@ The following values are available: # vz turned negative return previous.vz > 0 >= context.state.vz - Do not reach into ``context.flight.solution`` for this. It holds the stored - trajectory points, which advance independently of when your event is checked, - so a crossing can fall between two of them and never be seen. Use the flight - solution when you want the trajectory itself, not the previous value this - event saw. -- ``step_size`` (float): How long the simulation has been inside the - solver step your callback is being evaluated in, in seconds. At the end of a - step that is the whole step the solver just took; at a point interpolated - inside a step it is the part of the step up to that point. - - This is a property of the integrator, not of your event. It is **not** the - time since your callback last ran, and it is **not** ``1 / sampling_rate``: a - sampled event is checked on its own schedule, which has nothing to do with - where the solver put its step boundaries, and the solver changes its step size - throughout the flight. To measure how much time passed between two checks of - your own event, subtract ``previous_time`` from ``time``. + This is the value this event saw at its own previous check. +- ``dt`` (float or ``None``): The time since this event was last checked, in + seconds: ``time - previous_time``. For a controller, that is the time since + its previous run:: + + def controller_function(context): + error = context.state.vz - 50 + context.memory["integral"] = ( + context.memory.get("integral", 0.0) + error * context.dt + ) + + On the first check there is no previous one, so ``dt`` is + ``1 / sampling_rate``, the time a run normally covers. An event without a + ``sampling_rate``, checked at every solver step, gets ``None`` there. **Simulation objects:** -- ``flight`` (:class:`rocketpy.Flight`): The Flight instance orchestrating - the simulation. - ``rocket`` (:class:`rocketpy.Rocket`): The Rocket object being simulated. -- ``environment`` (:class:`rocketpy.Environment`): The Environment conditions - for the flight. -- ``phase``: The flight phase being flown, as listed in - ``flight.flight_phases``. +- ``environment`` (:class:`rocketpy.Environment`): The Environment conditions + for the flight, such as ``context.environment.wind_velocity_x(z)``. +- ``phase_name`` (str): The flight phase being flown: ``"initial_phase"`` + from the start (on the rail), ``"free_flight"`` after leaving the rail, and + ``"_parachute_descent"`` under a parachute. + +Read the rocket and the environment, but never change them: the next flight +flies the same objects, and the flight cannot see such a change, so it would +not act from the right moment or be undone. **Event and sensor data:** - ``event`` (:class:`rocketpy.Event`): A reference to the Event object itself, - allowing access to ``memory``, ``commands``, and other event state. -- ``sensors`` (list): The sensors attached to the rocket. Each sensor has a - ``measurement`` attribute with the most recent value. -- ``sensors_by_name`` (dict): The same sensors keyed by name (or class name). - If multiple sensors share the same name, the value is a list. + allowing access to ``commands`` and other event state. +- ``memory`` (dict): The event's own dictionary, kept from one check to the + next (the same as ``context.event.memory``). See below. +- ``commands``: The requests this event makes to the flight (the same as + ``context.event.commands``). See below. +- ``sensors``: The latest reading of each sensor attached to the rocket. Find + a sensor by its name as given or by that name in snake_case as an + attribute, then read a channel: ``context.sensors["Barometer"].pressure`` or + ``context.sensors.barometer.pressure``. Every sensor reads once on the pad + when the flight starts, so there is always a reading. See :ref:`sensorsusage`. - ``sampling_rate`` (float or None): The sampling rate of the event in Hz, or ``None`` for a continuous event. -**Inside a controller function only:** - -- ``controller``: The controller being run. Its own dictionary, kept from one - run to the next, is ``context.controller.memory``. -- ``controlled``: The objects the controller drives. Read one by the name it - was given, such as ``context.controlled.air_brakes``, or by its position, - such as ``context.controlled[0]``. Looping over ``context.controlled`` gives - all of them, in the order they were passed to the controller. - -Both are ``None`` in an event that is not a controller. +**Control inputs:** + +- ``controls``: The flight's control inputs. The controls of each controllable + of the rocket, such as air brakes, :class:`rocketpy.ControlFins` or a + surface built with ``controls``, written as + ``context.controls.air_brakes.deployment_level = 0.5``. The controllable is + its name in snake_case. A name that is not a plain word is written as given, + ``context.controls["Main Brakes"]``, and a control whose name is built in a + loop as ``context.controls.canards[fin]``. ``list(context.controls)`` gives + the names of the controllables, and ``rocket.control_names`` lists every + control input as ``.``. A value written here is + kept inside the control's limits once the callback returns, + and acts from this moment on. + +**Sharing values between events:** + +- ``outputs``: The values the events of the flight share with each other. An + event declares its outputs when it is built, writes them under its own name + in snake_case, and every other event reads them:: + + def guidance_function(context): + context.outputs.guidance.pitch_setpoint = 0.1 # rad + + def attitude_function(context): + error = context.outputs.guidance.pitch_setpoint - pitch(context) + context.controls.canards.fin_1 = 2.0 * error + + guidance = Controller(guidance_function, sampling_rate=10, + name="Guidance", outputs=("pitch_setpoint",)) + attitude = Controller(attitude_function, sampling_rate=100, name="Attitude") + + An output can hold any value and keeps it until it is written again. Only the + event that declared an output can write it. Outputs start every flight as + ``None`` (or at the value given with a dictionary, + ``outputs={"pitch_setpoint": 0.05}``). After the flight, + ``flight.event_outputs.guidance.pitch_setpoint`` is the list of + ``(time, value)`` pairs written. They are the way to share a value between + events: a value kept in a Python object outside the flight is not reset + between flights. **Keeping your own data:** -- The event's own dictionary is ``context.event.memory``. It is kept from - one check to the next, so keep counters, thresholds and anything shared - between trigger and callback there. +- The event's own dictionary is ``context.memory``. It is kept from + one check to the next, so keep what the next call needs there: counters, + thresholds, a filter state, anything shared between trigger and callback. It + is restored to its starting values at every flight. +- To see a value after the flight, record it: ``context.record(error=0.4)`` + stores named values at the current time. After the flight, + ``event.records["error"]`` is the list of ``(time, value)`` pairs recorded, + with each value exactly as it was given, and ``flight.records`` holds the + records of every event, by the event's name as given or in snake_case: + ``flight.records["My Event"].error`` or ``flight.records.my_event.error``. A + record can hold anything, a number, a vector, a text, a dictionary + (``context.record(command=[0.1, -0.2], mode="coast")``); + ``flight.plots.records()`` plots the ones made of numbers. Do not add values to the ``context`` passed to your function: it is shared by every event checked in the same solver step. +**What your function can do:** + +Besides reading values, a trigger or callback can do four things, each +through the context: + +- **Set a control input**: ``context.controls.air_brakes.deployment_level = 0.5``. + The new value is used from this moment on. +- **Keep something for its next call**: ``context.memory["integral"] += error``. +- **Log a value to look at after the flight**: ``context.record(error=error)``. +- **Change how the flight goes on**: ``context.commands``, such as + ``context.commands.terminate_flight()``, ``set_dynamics(...)``, + ``start_flight_phase(...)``, adding, enabling or disabling events, and + switching surfaces on or off. Commands are requests to the flight itself: + they are queued while your function runs and applied by the flight once it + returns. See :ref:`event_commands`. + +The first three take effect as you write them. Writing a control or a record +is not a command. + Understanding Event Parameters ------------------------------ @@ -249,11 +319,11 @@ practical examples and demonstrate proper activation. **callback** (required) The function that runs when the event triggers. It takes the ``context`` - as its single argument, and all of its returns are saved on the ``callback_log`` list for later - inspection. The callback can also queue commands to modify the simulation - state through the ``event.commands`` interface. Access to the - ``event.memory`` dictionary is also possible, and allows the callback to - store data across triggers. + as its single argument, and what it returns is ignored. Values to look at + after the flight are kept with ``context.record(...)``, and read as + ``event.records``. The callback can also queue commands to modify the + simulation state through the ``context.commands`` interface. The event's + ``context.memory`` dictionary lets the callback keep data across triggers. .. seealso:: Check the :ref:`event_commands` section for details. @@ -261,8 +331,7 @@ practical examples and demonstrate proper activation. .. jupyter-execute:: def my_callback(context): - time = context.time - return {"time": time} + context.record(altitude=context.state.z) simple_event = Event( callback=my_callback, @@ -285,7 +354,8 @@ practical examples and demonstrate proper activation. print(f"Flight time = {simple_flight.t:.4f} s\n") - print(f"Callback log: {simple_event.callback_log}\n") + altitude = simple_event.records["altitude"] + print(f"Altitudes recorded: {[value for _, value in altitude]}\n") print(simple_event) @@ -308,7 +378,11 @@ practical examples and demonstrate proper activation. .. tip:: - A list of all triggered times can be accessed with ``event.triggered_times``. + A list of all triggered times can be accessed with ``event.triggered_times``, + and the times the event was turned on or off with ``event.enabled_times`` + and ``event.disabled_times``. Like the records, they only hold moments of + the trajectory that was flown: when the simulation goes back in time, the + later ones are dropped. .. jupyter-execute:: @@ -318,7 +392,7 @@ practical examples and demonstrate proper activation. return context.state.vz > 50 # m/s def simple_callback(context): - return {"status": "event triggered!"} + context.record(status="event triggered!") simple_event = Event( callback=simple_callback, @@ -410,26 +484,29 @@ practical examples and demonstrate proper activation. **memory** (optional) The event's own dictionary, kept from one check to the next. Useful for counters, thresholds and data shared between trigger and callback. Read and - write it as ``context.event.memory`` inside the trigger and callback. It + write it as ``context.memory`` inside the trigger and callback. It is restored to the values given here when the event is reset for a new flight. .. note:: - ``memory`` is not logged: what the callback writes there is **not** - persisted to output logs or files. + ``memory`` holds what the next call needs, not a history: what the + callback writes there is **not** kept over time nor saved. To see a value + after the flight, record it with ``context.record`` instead. + + Here the count is what the next call needs, so it lives in ``memory``. The + time of each call is only wanted afterwards, so it is recorded: .. jupyter-execute:: def counting_callback(context): - event = context.event - event.memory["count"] += 1 - event.memory["last_time"] = context.time + context.memory["count"] += 1 + context.record(count=context.memory["count"]) return None counter_event = Event( callback=counting_callback, name="Counting event", - memory={"count": 0, "last_time": None}, + memory={"count": 0}, ) counter_flight = Flight( @@ -450,6 +527,8 @@ practical examples and demonstrate proper activation. f"{len(counter_event.triggered_times)} time(s)\n" ) print(f"Final event memory: {counter_event.memory}") + count = counter_event.records["count"] + print(f"Calls recorded from {count[0][0]:.2f} s to {count[-1][0]:.2f} s") **disable_on** (optional) Automatically disable the event based on a condition. Can be: @@ -635,7 +714,7 @@ practical examples and demonstrate proper activation. def my_state_crosses_target(context): return context.state.my_state - target_value - ``state_dot`` and ``pressure`` are worked out at each moment tried as well, + ``state_dot`` and ``conditions`` are worked out at each moment tried as well, if the function reads them, so each adds cost to every step of the search. Exact-time solving is only available for continuous events @@ -684,7 +763,7 @@ practical examples and demonstrate proper activation. def altitude_trigger(context): """Check when altitude crosses the target value from below.""" - target_altitude = context.event.memory["target_altitude"] + target_altitude = context.memory["target_altitude"] return context.height_agl > target_altitude def altitude_exact_time_function(context): @@ -750,12 +829,6 @@ practical examples and demonstrate proper activation. will cause the simulation to be many times slower, with no improvement in accuracy. -**changes_dynamics** (optional) - Signals that the event's callback will change the simulation dynamics or - parameters that affect the ODE derivative. Examples changing a motor thrust - profile, changing a parameter that affects the aerodynamic forces, or any - object mutation that affects the current rocket configuration. - **name** (optional) Human-readable identifier used in logs and debugging. If omitted, RocketPy uses the default string ``"Event"``. @@ -765,38 +838,52 @@ practical examples and demonstrate proper activation. via ``enable_on`` parameter. **verbose** (optional) - When ``True``, the event prints a message and stores extra execution logs - whenever it triggers. + When ``True``, every check of the event is reported by RocketPy's logger at + the ``INFO`` level, which is shown with ``Flight(..., verbose=True)`` or + ``rocketpy.enable_logging()``. Useful to see why an event did or did not + fire. .. _event_commands: Using Commands to Modify Simulation State ----------------------------------------- -When a callback needs to change the simulation loop state, it does so through -``event.commands``. The callback queues one or more commands, and ``Flight`` -applies them after the callback returns. +When a callback needs to change how the flight goes on, it does so through +``context.commands`` (the same as ``context.event.commands``). The callback +queues one or more commands, and ``Flight`` applies them after the callback +returns. Available commands include: -- ``event.commands.disable() / enable()``: Disable or re-enable the current event. -- ``event.commands.add_event(event)``: Schedule a new event during the simulation. Not for events with ``changes_dynamics=True``; see the warning below. -- ``event.commands.disable_event(event)``: Disable another event or controller event. -- ``event.commands.set_dynamics(dynamics, **phase_kwargs)``: Fly the rest of the flight with a different set of equations of motion. -- ``event.commands.start_flight_phase(phase_name=None, lag=0)``: Start a new flight phase. -- ``event.commands.terminate_flight()``: Request to end the flight simulation immediately after the current step. -- ``event.commands.activate_surface(surface) / deactivate_surface(surface)``: Make an aerodynamic surface start or stop producing force. - -**event.commands.disable() / enable()** - Disable or re-enable the event that is currently running. This is useful for - one-shot behaviors or for temporarily muting an event after it fires. +- ``context.commands.disable() / enable()``: Disable or re-enable the current event. +- ``context.commands.add_event(event)``: Schedule a new event during the simulation. +- ``context.commands.disable_event(event) / enable_event(event)``: Disable or enable another event or controller event. +- ``context.commands.set_dynamics(dynamics, **phase_kwargs)``: Fly the rest of the flight with a different set of equations of motion. +- ``context.commands.start_flight_phase(phase_name=None, lag=0)``: Start a new flight phase. +- ``context.commands.terminate_flight()``: Request to end the flight simulation immediately after the current step. +- ``context.commands.activate_surface(surface) / deactivate_surface(surface)``: Make an aerodynamic surface start or stop producing force. + +**context.commands.disable() / enable()** + Disable the event that is currently running, from now on. ``enable()`` only + cancels a ``disable()`` made earlier in the same call: a disabled event does + not run, so it cannot turn itself back on (give it an ``enable_on`` for + that). + + These commands act on the flight being flown. To choose how an event starts + every flight, set ``event.enabled`` before the flight, such as + ``event.enabled = False``. Do not set ``context.event.enabled`` inside a + callback: that changes the event itself, for every later flight too. + + ``disable()`` and ``disable_on`` do the same thing. Use ``disable_on`` for a + condition you know when you build the event, such as ``"apogee"`` or a time: + it is checked for you and saved with the event. Use ``disable()`` when the + function itself decides to stop, such as a controller that gives up after + detecting a fault. .. jupyter-execute:: def disable_after_first_hit(context): - event = context.event - event.commands.disable() - return {"action": "disabled self"} + context.commands.disable() disable_event = Event( callback=disable_after_first_hit, @@ -818,18 +905,16 @@ Available commands include: print(f"Flight time = {disable_flight.t:.4f} s") print(f"Event enabled after run? {disable_event.enabled}") - print(f"Disable log entries: {disable_event.callback_log}") + print(f"Disabled at: {disable_event.disabled_times}") -**event.commands.add_event(event)** +**context.commands.add_event(event)** Schedule a new event during the simulation. This is useful when one event should introduce a follow-up action later in the flight. .. jupyter-execute:: def add_follow_up(context): - event = context.event - def follow_up_callback(follow_up_context): return f"Follow-up event fired at {follow_up_context.time:.2f} s" @@ -840,8 +925,7 @@ Available commands include: sampling_rate=10, trigger_only_once=True, ) - event.commands.add_event(follow_up_event) - return f"Added follow-up event at {context.time:.2f} s" + context.commands.add_event(follow_up_event) add_event = Event( callback=add_follow_up, @@ -864,62 +948,28 @@ Available commands include: print(f"Flight time = {add_event_flight.t:.4f} s") print(f"Total custom events after run: {len(add_event_flight.custom_events)}") - print(f"First Event log: {add_event.callback_log}") - print(f"Follow-up Event log: {add_event_flight.custom_events[1].callback_log}") - - .. warning:: - - Avoid adding an event with ``changes_dynamics=True`` this way. A flight - decides before it starts, from the events it was built with, whether to - record the accelerations, aerodynamic forces and moments and net thrust - step by step. An event added mid-flight arrives too late for that: the - trajectory is still right, but those variables are worked out afterwards - from the rocket as it ends the flight, so what the event changed is - reported for the whole flight. RocketPy raises a ``UserWarning`` when - this happens. - - Instead, give the event to the ``Flight`` with ``enabled=False`` and turn - it on with ``enable_on`` or the ``enable`` command. If the events really - cannot be written in advance, give the ``Flight`` one disabled placeholder - with ``changes_dynamics=True``, which makes it record from the start: - - .. code-block:: python - - recording_placeholder = Event( - callback=lambda context: None, - trigger=lambda context: False, - name="Force post-process recording", - enabled=False, - changes_dynamics=True, - ) - - Recording costs one extra evaluation of the equations of motion per - stored step, so only add the placeholder when you will need it. - -**event.commands.disable_event(event)** + print(f"Follow-up event added at: {add_event.triggered_times}") + print(f"Follow-up event ran at: {add_event_flight.custom_events[1].triggered_times}") + +**context.commands.disable_event(event)** Disable another event or controller event. This is useful when one trigger should shut off a later response. .. jupyter-execute:: - def disable_other_event(context): - event = context.event - flight = context.flight - target_event = flight.custom_events[0] # Assuming the target event is the first one added to the flight. - event.commands.disable_event(target_event) - return {"action": f"disabled {target_event.name}"} - target_event = Event( callback=lambda context: f"Called at {context.time:.2f} s", name="Target event", sampling_rate=2, ) + def disable_other_event(context): + context.commands.disable_event(target_event) + disable_other = Event( callback=disable_other_event, - trigger=lambda context: context.time>= 2, + trigger=lambda context: context.time >= 2, name="Disabler", - memory={"target_event": target_event}, sampling_rate=10, trigger_only_once=True, ) @@ -938,10 +988,9 @@ Available commands include: print(f"Target event enabled after run? {target_event.enabled}") print(f"Target event disabled at: {target_event.disabled_times}") - print(f"Target event log: {target_event.callback_log}") -**event.commands.set_dynamics(dynamics, \*\*phase_kwargs)** +**context.commands.set_dynamics(dynamics, \*\*phase_kwargs)** Fly the rest of the flight with a different set of equations of motion. RocketPy ships five of them, importable from ``rocketpy.simulation.helpers``: @@ -955,8 +1004,6 @@ Available commands include: how a parachute descent knows which parachute is open: ``set_dynamics(PARACHUTE_DYNAMICS, parachute=main)``. - The event must be created with ``changes_dynamics=True``. - Writing your own set of equations is possible but internal for now, so it is not covered here. Below, a flight switches to a three degree of freedom model partway up, and the phases it flew are printed at the end. @@ -966,16 +1013,13 @@ Available commands include: from rocketpy.simulation.helpers import THREE_DOF_DYNAMICS def switch_dynamics(context): - event = context.event - event.commands.set_dynamics(THREE_DOF_DYNAMICS) - return {"action": "switched to three degrees of freedom"} + context.commands.set_dynamics(THREE_DOF_DYNAMICS) dynamics_event = Event( callback=switch_dynamics, trigger=lambda context: context.time >= 6, name="Dynamics switcher", trigger_only_once=True, - changes_dynamics=True, ) dynamics_flight = Flight( @@ -991,28 +1035,26 @@ Available commands include: ) print(f"Flight time = {dynamics_flight.t:.4f} s") - print(f"Dynamics event log: {dynamics_event.callback_log}") + print(f"Switched dynamics at: {dynamics_event.triggered_times}") print("Flight phases: ") for _, phase in dynamics_flight.flight_phases: print(phase) print(dynamics_flight.flight_phases[-1]) -**event.commands.start_flight_phase(phase_name=None, lag=0)** +**context.commands.start_flight_phase(phase_name=None, lag=0)** Start a new flight phase at the trigger, or ``lag`` seconds after it. During the lag the flight keeps its current equations of motion, which is how a parachute keeps falling freely while it opens. Use it when the callback wants the solver restarted at the trigger. To fly the new phase with different equations of motion, such as those of a deployed parachute, use ``set_dynamics`` instead, for example - ``event.commands.set_dynamics(PARACHUTE_DYNAMICS, parachute=main)``. + ``context.commands.set_dynamics(PARACHUTE_DYNAMICS, parachute=main)``. .. jupyter-execute:: def start_new_phase(context): - event = context.event - event.commands.start_flight_phase(phase_name="custom_descent") - return {"action": "started new phase"} + context.commands.start_flight_phase(phase_name="custom_descent") phase_event = Event( callback=start_new_phase, @@ -1041,19 +1083,13 @@ Available commands include: print(phase_flight.flight_phases[-1]) -**event.commands.terminate_flight()** +**context.commands.terminate_flight()** End the simulation immediately. .. jupyter-execute:: def stop_on_trigger(context): - event = context.event - event.commands.terminate_flight() - return { - "action": "termination requested", - "trigger_time": context.time, - "flight_time": context.flight.t, - } + context.commands.terminate_flight() stop_event = Event( callback=stop_on_trigger, @@ -1073,12 +1109,9 @@ Available commands include: ) print(f"Flight terminated at t = {stop_flight.t:.4f} s") - if stop_event.callback_log and stop_event.callback_log[-1]: - log = stop_event.callback_log[-1] - print(f"Trigger time: {log['trigger_time']:.4f} s") - print(f"Flight time reported by callback: {log['flight_time']:.4f} s") + print(f"Trigger time: {stop_event.triggered_times[-1]:.4f} s") -**event.commands.activate_surface(surface) / deactivate_surface(surface)** +**context.commands.activate_surface(surface) / deactivate_surface(surface)** Make an aerodynamic surface start or stop producing force from this moment on. Use it for a part of the rocket that appears or disappears during the flight. The surface must already be one of the rocket's aerodynamic surfaces. A surface that should @@ -1092,7 +1125,7 @@ Available commands include: .. code-block:: python def switch_off(context): - context.event.commands.deactivate_surface(my_surface) + context.commands.deactivate_surface(my_surface) switch_event = Event( callback=switch_off, diff --git a/docs/user/first_simulation.rst b/docs/user/first_simulation.rst index 959a34c11..b4fa6d080 100644 --- a/docs/user/first_simulation.rst +++ b/docs/user/first_simulation.rst @@ -658,6 +658,10 @@ of ``[[time, speed], ...]``: :class:`rocketpy.Flight`. These attributes are usually instances of the :class:`rocketpy.Function` class, see the :ref:`Function Class Usage ` for more information. + The same results are in ``test_flight.solution`` as the numbers the + simulation stored at each time step: ``test_flight.solution.vz``, + ``test_flight.solution.at(t)``. See :ref:`flight_solution`. + Exporting Flight Data --------------------- @@ -712,8 +716,9 @@ This exports the same data at a sampling rate of 1 second. The flight data is interpolated to match the new sampling rate. Finally, ``test_flight.exports.data`` also provides a convenient way to -export the entire flight solution (see :meth:`rocketpy.Flight.solution_array`) -by not passing any attribute names: +export the states of the whole flight (the table in +``test_flight.solution.canonical_array``, see :ref:`flight_solution`) by not +passing any attribute names: .. jupyter-execute:: diff --git a/docs/user/flight.rst b/docs/user/flight.rst index 53973e7f5..de50ecd4c 100644 --- a/docs/user/flight.rst +++ b/docs/user/flight.rst @@ -170,6 +170,18 @@ be positive. This is particularly useful for multi-stage simulations or when analyzing different scenarios from a specific flight condition. +.. note:: + + Events, sensors and controllers start again in the new flight: an event + that fired in the previous flight may fire again, and a controller's + ``memory`` is back to its initial value. + + The control inputs and the states of the rocket's controllables (see + :ref:`controllers`) are carried over instead: an air brake left half open + stays half open, and a fin that was still moving toward its command keeps + moving from where it was. Only the control inputs the new flight's rocket + also has are carried over, each kept within that rocket's limits. + Simulation Control Parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -203,8 +215,19 @@ Simulation Control Parameters Accessing Simulation Results ---------------------------- -Once a Flight simulation is complete, you can access a wealth of data about -the rocket's trajectory and performance. +Once a Flight simulation is complete, every result is read from the ``flight`` +object by its name. The same result can be read in two forms: + +- ``flight.z`` is a :class:`rocketpy.Function` of time. It can be evaluated at + any time, ``flight.z(10)``, plotted, ``flight.z.plot()``, and combined with + other Functions (see :ref:`Function Class Usage `). This is + the form to use for most analyses. +- ``flight.solution.z`` is the same result as the numbers the simulation + stored: an array with one ``(time, value)`` row per time step. See + :ref:`flight_solution`. + +The next sections go through the results as Functions, and +:ref:`flight_solution` covers the stored numbers. Trajectory Data ~~~~~~~~~~~~~~~ @@ -266,9 +289,9 @@ The Flight object provides access to all forces and accelerations acting on the R3 = flight.R3 # Z-axis aerodynamic force (drag) # Aerodynamic moments in body frame (N⋅m) - M1 = flight.M1 # Roll moment - M2 = flight.M2 # Pitch moment - M3 = flight.M3 # Yaw moment + M1 = flight.M1 # Moment about the body x-axis (pitch) + M2 = flight.M2 # Moment about the body y-axis (yaw) + M3 = flight.M3 # Moment about the body z-axis (roll) Rail Button Forces and Bending Moments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -314,9 +337,9 @@ Rocket orientation throughout the flight: e0, e1, e2, e3 = flight.e0, flight.e1, flight.e2, flight.e3 # Angular velocities in body frame (rad/s) - w1 = flight.w1 # Roll rate - w2 = flight.w2 # Pitch rate - w3 = flight.w3 # Yaw rate + w1 = flight.w1 # About the body x-axis (pitch rate) + w2 = flight.w2 # About the body y-axis (yaw rate) + w3 = flight.w3 # About the body z-axis (roll rate) # Derived attitude angles attitude_angle = flight.attitude_angle @@ -337,93 +360,158 @@ Key performance indicators: static_margin = flight.static_margin stability_margin = flight.stability_margin -Accessing Raw Simulation Data -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. _flight_solution: + +The Flight Solution +~~~~~~~~~~~~~~~~~~~ -For users who need direct access to the raw numerical simulation results, -the Flight object provides the complete solution array through the ``solution`` -and ``solution_array`` attributes. +``flight.solution`` holds everything the simulation stored over time, as plain +numbers: one row for each time step the solver took. It is a +:class:`rocketpy.simulation.solution.Solution`. Use it when you want the values +exactly as the simulation stored them, with nothing interpolated between time +steps. -**Flight.solution** +**One result over the whole flight** -The ``Flight.solution`` attribute contains the raw simulation data as a list of -state vectors, where each row represents the rocket's complete state at a specific time: +Every result is read by its name, as an attribute or as a key. Both give the +same array, with one row per time step and two columns, time and value: .. jupyter-execute:: - # Access the raw solution list - raw_solution = flight.solution + vz = flight.solution.vz # the same as flight.solution["vz"] + + print(vz.shape) # (number of time steps, 2) + print(vz[:3]) # the first rows: [time (s), vz (m/s)] + +The time steps alone are in ``flight.solution.time``, and +``flight.solution.names`` lists every name the flight holds: + +.. jupyter-execute:: + + print(flight.solution.names) + +These names are: + +- **The 13 states the simulation integrates**: the position ``x``, ``y``, + ``z`` (m), the velocity ``vx``, ``vy``, ``vz`` (m/s), the attitude ``e0``, + ``e1``, ``e2``, ``e3`` (Euler parameters) and the angular velocity ``w1``, + ``w2``, ``w3`` (rad/s, in the rocket's body frame). +- **The variables calculated from the states at each time step**: the + accelerations ``ax``, ``ay``, ``az`` (m/s²), the angular accelerations + ``alpha1``, ``alpha2``, ``alpha3`` (rad/s²), the aerodynamic forces ``R1``, + ``R2``, ``R3`` (N) and moments ``M1``, ``M2``, ``M3`` (N⋅m) and the + ``net_thrust`` (N). +- **The control inputs and the states of the rocket's controllables**, for a + rocket with air brakes, control fins or controllers (see :ref:`controllers`). + +``flight.vz`` is this same array wrapped in a :class:`rocketpy.Function`. - # Each element is a 14-element state vector: - # [time, x, y, z, vx, vy, vz, e0, e1, e2, e3, w1, w2, w3] - initial_state = flight.solution[0] # First time step - final_state = flight.solution[-1] # Last time step +.. note:: - print(f"Initial state: {initial_state}") - print(f"Final state: {final_state}") + The calculated variables are worked out from the stored states the first + time one of them is read, so that first read takes longer. A flight loaded + from a file holds the states but cannot work these variables out again. -**Flight.solution_array** +**Everything at one time** -For easier numerical analysis, use ``solution_array`` which provides the same data -as a NumPy array: +``flight.solution.at(t)`` gives every result at the stored time step nearest to +``t``, as a dictionary of name to value: .. jupyter-execute:: - import numpy as np + at_apogee = flight.solution.at(flight.apogee_time) + + print(f"Altitude: {at_apogee['z']:.1f} m") + print(f"Vertical velocity: {at_apogee['vz']:.3f} m/s") + print(f"Vertical acceleration: {at_apogee['az']:.2f} m/s²") - # Get solution as NumPy array for easier manipulation - solution_array = flight.solution_array # Shape: (n_time_steps, 14) +No value is interpolated: if the nearest time step is more than ``atol`` +seconds away from ``t`` (1e-3 by default), a warning tells which time was used. +For a value at any time, interpolated between the time steps, call the Function +instead, as in ``flight.z(10)``. - # Extract specific columns (state variables) - time_array = solution_array[:, 0] # Time values - position_data = solution_array[:, 1:4] # X, Y, Z positions - velocity_data = solution_array[:, 4:7] # Vx, Vy, Vz velocities - quaternions = solution_array[:, 7:11] # e0, e1, e2, e3 - angular_velocities = solution_array[:, 11:14] # w1, w2, w3 +The dictionary holds the variables the flight phase at that time calculates, +so under a parachute it has no moments, angular accelerations or thrust. - # Example: Calculate velocity magnitude manually - velocity_magnitude = np.sqrt(np.sum(velocity_data**2, axis=1)) +``flight.solution.at_index(i)`` gives the states and the control inputs of +time step ``i``, counted from the start of the flight, or from its end when +negative: ``flight.solution.at_index(-1)`` is the last one. -**State Vector Format** +**The states as a table** -Each row in the solution array follows this 14-element format: +``flight.solution.canonical_array`` is the 13 states of the whole flight as a +NumPy array, one row per time step and 14 columns: .. code-block:: python [time, x, y, z, vx, vy, vz, e0, e1, e2, e3, w1, w2, w3] -Where: - - ``time``: Simulation time in seconds - - ``x, y, z``: Position coordinates in meters (East, North, Up) - - ``vx, vy, vz``: Velocity components in m/s (East, North, Up) - - ``e0, e1, e2, e3``: Euler parameters (quaternions) for attitude - - ``w1, w2, w3``: Angular velocities in rad/s (body frame: roll, pitch, yaw rates) +.. jupyter-execute:: + + import numpy as np + + table = flight.solution.canonical_array # Shape: (number of time steps, 14) + + time = table[:, 0] # Time (s) + position = table[:, 1:4] # x, y, z (m) + velocity = table[:, 4:7] # vx, vy, vz (m/s) + attitude = table[:, 7:11] # e0, e1, e2, e3 + angular_velocity = table[:, 11:] # w1, w2, w3 (rad/s) + + # Example: the speed at every time step + speed = np.sqrt(np.sum(velocity**2, axis=1)) -**Getting State at Specific Time** +This table cannot be written to. For a copy of your own to change, use +``np.array(flight.solution)``. -You can extract the rocket's state at any specific time during the flight: +The solution also reads like a list of these rows: ``flight.solution[0]`` is +the first time step, ``flight.solution[-1]`` the last, ``len(flight.solution)`` +the number of time steps, and slicing or looping gives the rows in order. A row +always has these 14 values, also in a flight phase that integrates fewer +states. + +**The flight phases** + +A flight is simulated as a sequence of phases, each with its own equations of +motion: on the rail, in free flight, under each parachute. +``flight.solution.phases`` lists them in the order they were flown, and +``flight.solution.phase_span`` gives the first row of a phase and one past its +last row: .. jupyter-execute:: - # Get complete state vector at t=10 seconds - state_at_10s = flight.get_solution_at_time(10.0) + for index, phase in enumerate(flight.solution.phases): + start, stop = flight.solution.phase_span(index) + print(f"{phase.name}: starts at {phase.t_start:.2f} s, {stop - start} rows") + +With these two positions, ``flight.solution.vz[start:stop]`` and +``flight.solution.canonical_array[start:stop]`` read that phase alone. + +**Control inputs and sensor readings** - print(f"State at t=10s: {state_at_10s}") +A rocket with controllers or sensors keeps their results in the solution too: - # Extract specific values from the state vector - time_10s = state_at_10s[0] - altitude_10s = state_at_10s[3] # Z coordinate - speed_10s = np.sqrt(state_at_10s[4]**2 + state_at_10s[5]**2 + state_at_10s[6]**2) +- ``flight.solution.controls.air_brakes.deployment_level`` is a control input + over the flight (see :ref:`controllers`). +- ``flight.solution.sensors.barometer.pressure`` is what a sensor read, at the + sensor's own sampling times (see :ref:`sensors_flight_data`). - print(f"At t={time_10s}s: altitude={altitude_10s:.1f}m, speed={speed_10s:.1f}m/s") +Both are arrays of time and value. ``flight.controls`` and +``flight.sensor_history`` give the same results as Functions of time. -This raw data access is particularly useful for: +.. note:: + + ``flight.solution_array`` and ``flight.get_solution_at_time(t)`` are + deprecated. Use ``flight.solution.canonical_array`` for the table of + states, and ``flight.solution.at(t)`` for the results at one time, which + gives a dictionary by name where ``get_solution_at_time`` gave a row of + 14 values. + +.. seealso:: -- Custom post-processing and analysis -- Exporting data to external tools -- Implementing custom flight metrics -- Monte Carlo analysis and statistical studies -- Integration with other simulation frameworks + :class:`rocketpy.simulation.solution.Solution` in the API reference lists + every method of the solution. To write results to a file, see + ``flight.exports`` in :doc:`First Simulation `. Plotting Flight Data diff --git a/docs/user/index.rst b/docs/user/index.rst index 27b303532..22c48268b 100644 --- a/docs/user/index.rst +++ b/docs/user/index.rst @@ -19,6 +19,7 @@ RocketPy's User Guide Environment Flight Event Usage + Controllers and Effectors .. toctree:: :maxdepth: 2 @@ -27,6 +28,7 @@ RocketPy's User Guide Compare Flights Class Deployable Payload Air Brakes Example + Control Fins Sensors ../matlab/matlab.rst diff --git a/docs/user/rocket/generic_surface.rst b/docs/user/rocket/generic_surface.rst index 11fc3243a..ec693bf41 100644 --- a/docs/user/rocket/generic_surface.rst +++ b/docs/user/rocket/generic_surface.rst @@ -151,6 +151,46 @@ length :math:`L_{ref}`: where :math:`L_{ref}` is the reference length (commonly the rocket's diameter). +Each coefficient is a moment about one body axis, following the right-hand +rule. A positive value turns the rocket as follows (the angles :math:`\alpha` +and :math:`\beta` are defined in the next section): + +.. list-table:: + :header-rows: 1 + :widths: 14 16 22 24 24 + + * - Coefficient + - Moment about + - Angular velocity that grows + - Where the nose moves + - Flow angle + * - :math:`C_m` + - :math:`x_B` + - ``w1`` + - toward :math:`-y_B` + - :math:`\alpha` increases + * - :math:`C_n` + - :math:`y_B` + - ``w2`` + - toward :math:`+x_B` + - :math:`\beta` decreases + * - :math:`C_l` + - :math:`z_B` + - ``w3`` + - it stays; the rocket rolls from :math:`x_B` toward :math:`y_B` + - :math:`\alpha_{\text{tot}}` unchanged + +The two planes do not mirror each other: a positive :math:`C_m` raises the +angle of attack, while a positive :math:`C_n` lowers the sideslip angle. A +statically stable rocket therefore has a :math:`C_m` that decreases with +:math:`\alpha` (negative :math:`C_{m\alpha}`) and a :math:`C_n` that increases +with :math:`\beta` (positive :math:`C_{n\beta}`). + +.. important:: + Data from a wind tunnel report or another program may define a positive + moment, or a positive control deflection, the other way round. Compare it + with this table before using it, and change the sign where it differs. + Angles of attack and sideslip ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -362,9 +402,8 @@ The angles can also be given in other forms. RocketPy converts them for you: - Roll angle of the wind, in degrees. These are all the accepted names. A coefficient cannot use the same angle under -two names, such as ``alpha`` and ``alpha_deg`` together. A -:class:`rocketpy.ControllableGenericSurface` adds the names of its own control -variables. +two names, such as ``alpha`` and ``alpha_deg`` together. A surface built with +``controls`` adds the names of its controls (see :ref:`surface_controls`). .. important:: The angular rates are the conventional **non-dimensional reduced rates**, not @@ -640,8 +679,8 @@ one step. Every coefficient is read against all the variable columns: Any other argument of the class (``center_of_pressure``, ``name``, ``active_during``, ...) can be passed along. The same method exists on :class:`rocketpy.LinearGenericSurface`, with derivative columns such as -``cN_alpha`` and ``cm_q``, and on :class:`rocketpy.ControllableGenericSurface`, -where a control can be one of the variable columns. +``cN_alpha`` and ``cm_q``. Pass ``controls`` to make a control one of the +variable columns. A file written by another program has its own column names. Translate them with ``columns``; the columns you do not list are ignored: @@ -731,6 +770,16 @@ for example :math:`C_m = C_m(\alpha, Ma) + C_{m_q}\, q^{*}`. Some rules: ``cN_q``). This also holds for data against ``alpha_total``. - A coefficient that already depends on a rate, through a ``pitch_rate`` column for example, cannot take the derivative for that rate too. +- **Where the surface sits matters.** The flight gives every surface the air at + its own position, including the velocity from the rocket's rotation, so a + surface placed away from the center of dry mass already damps through its + slope times its lever arm, as a real fin does. A rate derivative on such a + surface should hold only what that leaves out, usually nothing. A + whole-vehicle dataset is the other way round: its :math:`C_{m_q}` already + includes the lever arms of the fins and the body, so the surface belongs at + the center of dry mass, where the rotation adds nothing. That is the default + position of :meth:`rocketpy.Rocket.add_full_body_aerodynamics`. Placed one + caliber or more away, the lever term can exceed the derivative itself. Only the rate derivatives are accepted. A slope against the angle, such as ``cm_alpha``, belongs to a :class:`rocketpy.LinearGenericSurface`. @@ -751,7 +800,7 @@ Once defined, the surface is added to the rocket like any other: rocket = Rocket( ... ) - rocket.add_surfaces(generic_surface, position=(0,0,0)) + rocket.add_surfaces(generic_surface, positions=(0,0,0)) The position is given in the User Defined Coordinate System; see :ref:`rocket_axes` for more information. @@ -944,7 +993,7 @@ An example defining **all** the coefficient derivatives: "cl_p": "cl_p.csv", }, ) - rocket.add_surfaces(linear_generic_surface, position=(0,0,0)) + rocket.add_surfaces(linear_generic_surface, positions=(0,0,0)) .. _lineargenericsurface_axisymmetric: @@ -1142,6 +1191,97 @@ an extreme condition beyond your data. :meth:`rocketpy.Function.set_extrapolation` for the full list of methods. +.. _surface_controls: + +Controls +-------- + +A surface's coefficients can also depend on controls that a controller moves +during the flight, such as the deflection of canards. List their names in +``controls``; each becomes one more variable the coefficients can use: + +.. code-block:: python + + canards = GenericSurface( + reference_area=rocket.area, + reference_length=2 * rocket.radius, + coefficients={ + "cN": lambda alpha, mach, deflection: 2.0 * (alpha + deflection), + "cl": lambda deflection: 0.5 * deflection, + }, + name="Canards", + controls=("deflection",), + control_defaults={"deflection": 0.0}, + control_limits={"deflection": (-0.2, 0.2)}, + ) + +A :class:`rocketpy.LinearGenericSurface` takes controls the same way. Its +derivatives are slopes against the angles and rates, so a control enters +through the zero-angle terms or through a derivative that depends on it: + +.. code-block:: python + + canards = LinearGenericSurface( + reference_area=rocket.area, + reference_length=2 * rocket.radius, + coefficients={ + "cN_alpha": 2.0, + "cl_0": lambda mach, deflection: 0.3 * deflection, + "cl_p": -0.5, + }, + name="Canards", + controls=("deflection",), + control_limits={"deflection": (-0.2, 0.2)}, + ) + +A table with a control column works too: name the column after the control in +a file read with ``from_csv`` and pass ``controls=("deflection",)``. + +During a flight the value of each control is a control input of the flight, +named after the surface: an event or a controller writes it as +``context.controls.canards.deflection = 0.1``. ``rocket.control_names`` +lists every control input. A value outside ``control_limits`` is moved to the +nearest limit. The surface itself +is never changed by a flight: every flight starts from ``control_defaults``, +and those values are also the ones used outside a flight, for the stability +margin and the plots. + +A controller for the first surface above, which turns the canards against the +roll rate 50 times a second: + +.. code-block:: python + + from rocketpy import Controller + + def roll_function(context): + # cl = 0.5 * deflection: a positive deflection rolls toward positive w3 + context.controls.canards.deflection = -0.05 * context.state.w3 + + rocket.add_surfaces(canards, positions=1.2) + rocket.add_controller(Controller(roll_function, sampling_rate=50)) + +.. note:: + Where the surface is placed decides which moments its coefficients must + hold: + + - Placed where it sits on the rocket (the canards at ``positions=1.2``), + its force already gives a moment about the center of dry mass, and the + rocket's pitch and yaw rotation is already damped through that force. + Give the force coefficients and the moments about the surface's own + reference point, without a ``cm_q`` or ``cn_r`` that repeats that + damping. Roll damping (``cl_p``) is not repeated and still belongs + there. + - With coefficients measured for the whole rocket about its center of dry + mass, with the moment each control causes and damping derivatives + (``cm_q``, ``cn_r``, ``cl_p``) included, place the surface at the center + of dry mass. Anywhere else the moment of the force and the damping are + counted twice. + + See :ref:`generic_surface_damping`. + +How to write the controller and read the deflections flown is in +:ref:`controllers`. + .. _active_during: Activation Window @@ -1149,8 +1289,7 @@ Activation Window By default a surface produces aerodynamic force throughout the flight. There are two ways to restrict it to part of the flight. Both are accepted by -:class:`rocketpy.GenericSurface`, :class:`rocketpy.LinearGenericSurface` and -:class:`rocketpy.ControllableGenericSurface`. +:class:`rocketpy.GenericSurface` and :class:`rocketpy.LinearGenericSurface`. By motor phase ~~~~~~~~~~~~~~ @@ -1182,9 +1321,9 @@ To switch a surface on or off at any other moment, such as apogee, a given altitude or a sensor reading, use an :class:`rocketpy.Event`. Its callback switches the surface with one of two commands: -- ``context.event.commands.deactivate_surface(surface)``: the surface stops +- ``context.commands.deactivate_surface(surface)``: the surface stops producing force from that moment on. -- ``context.event.commands.activate_surface(surface)``: the surface starts +- ``context.commands.activate_surface(surface)``: the surface starts producing force from that moment on. For example, to switch a surface off at apogee: @@ -1192,7 +1331,7 @@ For example, to switch a surface off at apogee: .. code-block:: python def switch_off(context): - context.event.commands.deactivate_surface(my_surface) + context.commands.deactivate_surface(my_surface) switch_event = Event( callback=switch_off, @@ -1246,6 +1385,38 @@ lowers the base drag). To capture this, build two surfaces, set each one's ``active_during`` to ``"power_on"`` and ``"power_off"``, and pass them as a list; each then produces force only during its phase. +Whole-vehicle coefficients that depend on a control are given the same way: +build the surface with ``controls`` (see :ref:`surface_controls`) and write +the control input from a controller. The surface is placed at the center of +dry mass, so the coefficients must hold the moment each control causes: + +.. code-block:: python + + from rocketpy import Controller + + vehicle = GenericSurface( + reference_area=rocket.area, + reference_length=2 * rocket.radius, + coefficients={ + "cN": "cN.csv", # columns: alpha, mach, deflection, cN + "cm": "cm.csv", # columns: alpha, mach, deflection, cm + "cl": lambda deflection: 0.5 * deflection, + "cm_q": -800, + "cl_p": -2.0, + ... + }, + name="Vehicle", + controls=("deflection",), + control_limits={"deflection": (-0.2, 0.2)}, + ) + rocket.add_full_body_aerodynamics(vehicle, overwrite=True) + + def roll_function(context): + # turn the control against the roll rate + context.controls.vehicle.deflection = -0.05 * context.state.w3 + + rocket.add_controller(Controller(roll_function, sampling_rate=50)) + Which drag is used ~~~~~~~~~~~~~~~~~~ @@ -1253,10 +1424,15 @@ The drag of a rocket in flight is the sum of two things: - **The rocket's own drag curves**, ``power_on_drag`` before burnout and ``power_off_drag`` after it. They are always used. -- **The axial force of every surface**, which is added on top. The predefined - surfaces (nose cone, fins, tail) have no axial coefficient, so they add no - drag. A generic surface adds drag only if it is given a ``cA`` (or ``cD``) - coefficient. +- **The axial force of every surface**, which is added on top. The nose cone + and the tail have no axial coefficient, so they add no drag; a fin adds only + the part of its force that its cant angle tilts along the axis, which is + zero for an uncanted fin. A generic surface adds drag only if it is given a + ``cA`` (or ``cD``) coefficient. + +The same rule holds on the launch rail, where only the forces along the +rocket's axis count: the drag curves, the air brakes and a generic surface's +``cA`` all slow the rocket on the rail. A full-vehicle surface follows the same rule, since it is an ordinary generic surface. What changes is the ``overwrite`` argument: @@ -1266,7 +1442,8 @@ surface. What changes is the ``overwrite`` argument: to the other surfaces. - ``overwrite=True``: every surface already on the rocket is removed and both drag curves are set to zero, so the new surface is the only source of - aerodynamic forces. + aerodynamic forces. Air brakes are the exception: they are kept, with their + controller, and add their drag to the new surface's. .. warning:: If your full-vehicle data already includes drag, use ``overwrite=True``, or @@ -1294,8 +1471,8 @@ stability-derivative model about its center of dry mass: The slopes a generic surface reports for the stability analysis (its ``cN_alpha``, ``cm_alpha``, ``cY_beta``, ``cn_beta`` and the center of pressure built from them) are taken at zero angle of attack and sideslip, - zero rotation rates, Reynolds number 0 and, for a controllable surface, - zero control. A table that changes with the Reynolds number is therefore + zero rotation rates, Reynolds number 0 and, for a surface with controls, + each control at its default. A table that changes with the Reynolds number is therefore linearized at its low-Reynolds edge; the flight itself always reads the table at the actual Reynolds number. @@ -1338,7 +1515,7 @@ optional arguments of both methods keep the dependence: # read the coefficients at these Reynolds numbers (based on the # rocket's diameter); they gain "reynolds" as an input reynolds=[1e5, 1e6, 1e7], - # keep a control of a ControllableGenericSurface as an input + # keep a control of a surface (see "Controls") as an input controls={"deflection": np.radians([-10, 0, 10])}, # read the damping at every angle of the table, not only at zero rates="at_each_angle", @@ -1349,8 +1526,8 @@ optional arguments of both methods keep the dependence: - ``reynolds`` also takes a single number, which sets the Reynolds number the coefficients are read at without adding an input. It works with both models. - ``controls`` works with both models in ``to_coefficients``. In - ``to_surface`` it needs ``model="table"``, and the surfaces returned are - :class:`rocketpy.ControllableGenericSurface` objects with those controls. + ``to_surface`` it needs ``model="table"``, and the surfaces returned have + those controls. When two surfaces of the rocket use the same control name, each is kept as its own input, named ``_``. - ``rates="at_each_angle"`` needs ``model="table"``. diff --git a/docs/user/rocket/rocket_axes.rst b/docs/user/rocket/rocket_axes.rst index aa99cb231..938d35e22 100644 --- a/docs/user/rocket/rocket_axes.rst +++ b/docs/user/rocket/rocket_axes.rst @@ -69,7 +69,8 @@ Angular Position Inputs Angular position inputs (``angular_position``) refer to the roll angle position of that surface along the rocket's tube. The roll angle is defined as the angle from the ``y`` axis to the surface. -Currently, only the :class:`rocketpy.RailButtons` class uses this kind of input. +:class:`rocketpy.RailButtons`, the fins and :meth:`rocketpy.Rocket.add_effector` +take this kind of input. The following figure shows the roll angle definition for both ``coordinate_system_orientation`` options: diff --git a/docs/user/rocket/rocket_usage.rst b/docs/user/rocket/rocket_usage.rst index a3c4d2845..22f53b420 100644 --- a/docs/user/rocket/rocket_usage.rst +++ b/docs/user/rocket/rocket_usage.rst @@ -404,8 +404,9 @@ most used ones are listed below. For the complete list, with every value - ``pressure`` (float): current atmospheric pressure in Pa at the rocket's altitude. - ``height_agl`` (float): height above ground level in meters. -- ``step_size`` (float): how long the simulation has been inside the solver - step being evaluated, in seconds. +- ``dt`` (float or ``None``): time since this trigger was last checked, in + seconds. On the first check it is ``1 / sampling_rate``, or ``None`` for a + trigger without one. **Simulation objects:** @@ -417,10 +418,9 @@ most used ones are listed below. For the complete list, with every value **Sensor and Event data:** -- ``sensors`` (list): the sensors attached to the rocket, each exposing its - most recent ``measurement``. -- ``sensors_by_name`` (dict): the same sensors keyed by name (or class name). - If several sensors share a name, the value is a list. +- ``sensors``: the latest reading of each sensor attached to the rocket, such + as ``context.sensors.barometer.pressure``. Every sensor reads once on the + pad when the flight starts, so there is always a reading. - ``sampling_rate`` (float or None): the sampling rate of the parachute trigger in Hz (or ``None`` for a continuous trigger). - ``event`` (:class:`rocketpy.Event`): a reference to the wrapping Event object, @@ -466,8 +466,9 @@ reading them from ``context``: pressure**. - ``y`` (list of float): the state vector (the same thirteen values as ``context.state``, in the same order). -- ``sensors`` (list, optional fourth argument): the same list as - ``context.sensors``. +- ``sensors`` (list, optional fourth argument): the sensors attached to the + rocket, in the order they were added, each with its latest + ``measurement``. .. note:: The legacy positional ``p`` and ``h`` carry the parachute noise signal, diff --git a/docs/user/sensors_usage.rst b/docs/user/sensors_usage.rst index 5fef34da5..ac2a48184 100644 --- a/docs/user/sensors_usage.rst +++ b/docs/user/sensors_usage.rst @@ -177,6 +177,11 @@ coordinate system. The position matters for inertial sensors: a sensor mounted off the center of mass experiences extra acceleration due to the rocket's rotation (see :ref:`sensors_technical`). +Each sensor's readings go by its name in snake_case: the ``"GnssReceiver"`` +above is read as ``gnss_receiver``. Give each sensor its own ``name``: a name +used again is numbered from 2 in the order the sensors were added +(``accelerometer``, ``accelerometer_2``). + .. jupyter-execute:: calisto.add_sensor(accelerometer, 1.278) @@ -220,11 +225,10 @@ Using Sensors With a Controller (Air Brakes) The main motivation for simulating sensors is to feed their measurements into a controller, such as an air brakes system, exactly as the real avionics would. -Inside a controller function, every sensor attached to the rocket is available -through ``context.sensors`` (a list, in the order they were added) -and through ``context.sensors_by_name`` (a dictionary keyed by the sensor -``name``). -Each sensor exposes its *latest* reading via the ``measurement`` attribute. +Inside a controller function, ``context.sensors`` holds the *latest* reading +of every sensor attached to the rocket. Find a sensor by its name as given, or +by that name in snake_case as an attribute, then read a channel: +``context.sensors["Accelerometer"].az`` or ``context.sensors.accelerometer.az``. The controller below reads the accelerometer to detect motor burnout (measured vertical acceleration turning negative) before it starts deploying the air @@ -233,63 +237,61 @@ brakes: .. jupyter-execute:: def controller_function(context): - time = context.time sampling_rate = context.sampling_rate state = context.state # the states, by name - air_brakes = context.controlled.air_brakes - sensors = context.sensors + air_brakes = context.controls.air_brakes # the air brakes' controls - # Read the sensor measurement instead of the true state. - # Sensors can also be retrieved by name, e.g. - # accelerometer = context.sensors_by_name["Accelerometer"] - accelerometer = sensors[0] + # Read the sensor measurement instead of the true state + measured_az = context.sensors.accelerometer.az + context.record(measured_az=measured_az) # Do not deploy while the motor is still burning (measured az > 0) - if accelerometer.measurement[2] > 0: - return None + if measured_az > 0: + return - altitude_AGL = context.height_agl - vz = state.vz + deployment_level = air_brakes.deployment_level # Below 1500 m AGL, keep the air brakes closed - if altitude_AGL < 1500: + if context.height_agl < 1500: air_brakes.deployment_level = 0 else: - new_deployment_level = air_brakes.deployment_level + 0.1 * vz + new_deployment_level = deployment_level + 0.1 * state.vz # Limit the deployment rate to 0.2 per second max_change = 0.2 / sampling_rate - lower_bound = air_brakes.deployment_level - max_change - upper_bound = air_brakes.deployment_level + max_change - new_deployment_level = min( + lower_bound = deployment_level - max_change + upper_bound = deployment_level + max_change + air_brakes.deployment_level = min( max(new_deployment_level, lower_bound), upper_bound ) - air_brakes.deployment_level = new_deployment_level - - return time, air_brakes.deployment_level .. note:: - The controller reads ``accelerometer.measurement`` rather than the true - ``state`` vector. This is what makes the test realistic: the controller only + The controller reads ``context.sensors.accelerometer.az`` rather than the + true ``context.state_dot.az``. This is what makes the test realistic: the controller only sees the misaligned, noisy, quantized and biased data the physical sensor would actually provide. -Register the controller through the air brakes. See the +Add the air brakes and the controller to the rocket. See the :ref:`Air Brakes ` example for a detailed explanation of these arguments. .. jupyter-execute:: - air_brakes = calisto.add_air_brakes( + from rocketpy import AirBrakes, Controller + + air_brakes = AirBrakes( drag_coefficient_curve="../data/rockets/calisto/air_brakes_cd.csv", - controller_function=controller_function, - sampling_rate=10, - reference_area=None, - clamp=True, - initial_observed_variables=[0, 0], - override_rocket_drag=False, + reference_area=calisto.area, name="AirBrakes", ) + calisto.add_surfaces(air_brakes, positions=-0.5) # where they are, in meters + + controller = Controller( + controller_function, + sampling_rate=10, + name="AirBrakes Controller", + ) + calisto.add_controller(controller) Simulating the Flight --------------------- @@ -308,67 +310,139 @@ configuration is needed in the :class:`rocketpy.Flight` class. terminate_on_apogee=True, ) +Reading sensors in a controller +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A controller reads the **latest measurement** of each sensor, as a flight +computer reads the last sample its sensor sent. ``context.sensors`` holds them +all, read-only, by ``.``: + +.. list-table:: + :header-rows: 1 + + * - Sensor + - Channels + * - :class:`rocketpy.Accelerometer` + - ``ax``, ``ay``, ``az`` (m/s²) + * - :class:`rocketpy.Gyroscope` + - ``wx``, ``wy``, ``wz`` (rad/s) + * - :class:`rocketpy.Barometer` + - ``pressure`` (Pa) + * - :class:`rocketpy.GnssReceiver` + - ``latitude``, ``longitude`` (°), ``altitude`` (m) + +``list(context.sensors)`` gives the names of the sensors on your rocket, as +given (see above). Every +sensor reads once on the pad when the flight starts, so there is always a +reading, even for a sensor that samples more slowly than the controller. The +sensor objects themselves, with their settings, are in +``context.rocket.sensors``. + +Keep **older measurements yourself**, in ``context.memory``, as the software +of a flight computer keeps what it needs. For example, a moving average of the +last five pressures the controller read: + +.. code-block:: python + + def controller_function(context): + pressures = context.memory.setdefault("pressures", []) + pressures.append(context.sensors.barometer.pressure) + del pressures[:-5] # keep the last five + average_pressure = sum(pressures) / len(pressures) + ... + +The memory follows the flight: when the simulation goes back in time (for +instance to find the exact rail exit or apogee time), the memory, the controls +and every sensor's reading go back with it, so a controller never sees a +measurement from a stretch of trajectory that was not flown. To see every +reading after the flight, use ``flight.sensor_history`` (see +:ref:`sensors_flight_data`). + +.. note:: + + The controller runs only at its own sampling rate. A sensor sampling + faster than the controller makes measurements the controller never sees: + with a 100 Hz barometer and a 10 Hz controller, it reads one measurement + in ten. To use every measurement, run the controller at the sensor's rate + and act on every tenth call. + .. _sensors_flight_data: Accessing Sensor Data via the Flight Class ------------------------------------------ -The recorded measurements are stored on the resulting flight, in the -``sensor_data`` attribute. This is the **canonical, per-flight record** of every -sensor's output and the recommended way to access sensor data. +The readings are kept by the resulting flight, in its solution: +``flight.solution.sensors`` holds them as arrays, and +``flight.sensor_history`` as functions of time, the same way +``flight.solution.controls`` and ``flight.controls`` keep the control inputs. +A sensor is found as a controller finds it in ``context.sensors``: by its +name as given, ``test_flight.solution.sensors["Barometer"]``, or by that name +in snake_case, ``test_flight.solution.sensors.barometer``. Looping gives the +names: -.. important:: +.. jupyter-execute:: + + print(list(test_flight.solution.sensors)) - A sensor object only retains the measurements of its *most recent* flight in - ``sensor.measured_data`` - running another flight with the same rocket (for - example in a Monte Carlo analysis, or when comparing two flights) overwrites - it. ``flight.sensor_data`` is captured per flight, so always prefer it when a - rocket or sensor is reused across simulations. +Each channel is an ``(n, 2)`` array with one row per reading, time then +value, with the sensor's noise and resolution: -``flight.sensor_data`` is a dictionary keyed by the sensor object. Each value is -a list of ``(time, *measurement)`` tuples (or a list of such lists if the same -sensor object was added to the rocket in more than one position): +.. jupyter-execute:: + + pressure = test_flight.solution.sensors.barometer.pressure + print("Number of readings:", len(pressure)) + print("First reading (t, pressure):", pressure[0]) + +In ``flight.sensor_history`` the same channel is a :class:`rocketpy.Function` +of time in which a reading holds until the next one, since that is what a +flight computer reading the sensor sees between two samples. Calling it at +any time gives the last reading at or before that time: .. jupyter-execute:: - data = test_flight.sensor_data[accelerometer] - print("Number of accelerometer samples:", len(data)) - print("First sample (t, ax, ay, az):", data[0]) + pressure = test_flight.sensor_history["Barometer"].pressure + print("Pressure read at 5 s:", pressure(5.0), "Pa") + +.. important:: + + The readings are part of the flight: they are saved and loaded with it, + and the readings taken on a stretch of trajectory that the simulation went + back over (for instance to find the exact rail exit or apogee time) are + dropped. A sensor object only keeps the readings of its *most recent* + flight in ``sensor.measured_data``, so prefer the flight's readings when a + rocket or sensor is used in more than one simulation. Prints and plots ~~~~~~~~~~~~~~~~~ -The flight's ``prints`` and ``plots`` objects expose sensor-aware helpers that -read directly from ``flight.sensor_data``. Use them to summarize and visualize -every sensor at once. - -``flight.prints.sensors()`` prints a per-sensor summary (type, sampling rate, -number of samples and per-channel min/max/mean): +``flight.prints.sensors()`` lists each sensor (the name its readings go by, +type, sampling rate and number of readings), then the smallest, largest and +final reading of every channel: .. jupyter-execute:: test_flight.prints.sensors() -``flight.plots.sensor_data()`` plots every channel of every sensor against time: +``flight.plots.sensors()`` plots every channel of every sensor against time, +one plot per sensor, each reading held until the next: .. jupyter-execute:: - test_flight.plots.sensor_data() + test_flight.plots.sensors() Working with the raw data ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Because ``flight.sensor_data`` holds plain tuples, the data can be unpacked and -post-processed directly. For example, to plot the measured vertical -acceleration: +The arrays in ``flight.solution.sensors`` are the readings themselves. For +example, to plot the measured vertical acceleration: .. jupyter-execute:: import matplotlib.pyplot as plt - time, ax, ay, az = zip(*test_flight.sensor_data[accelerometer]) + az = test_flight.solution.sensors["Accelerometer"].az - plt.plot(time, az, label="Measured az") + plt.step(az[:, 0], az[:, 1], where="post", label="Measured az") plt.xlabel("Time (s)") plt.ylabel("Acceleration az (m/s^2)") plt.legend() diff --git a/rocketpy/__init__.py b/rocketpy/__init__.py index b44f0b594..3df6cff55 100644 --- a/rocketpy/__init__.py +++ b/rocketpy/__init__.py @@ -1,5 +1,10 @@ from ._logging import enable_logging, logger, set_log_level -from .control import _Controller +from .control import ( + ContinuousController, + Controller, + ForceEffector, + ThrustEffector, +) from .environment import Environment, EnvironmentAnalysis from .mathutils import ( Function, @@ -31,7 +36,7 @@ AeroSurface, AirBrakes, Components, - ControllableGenericSurface, + ControlFins, EllipticalFin, EllipticalFins, Fin, diff --git a/rocketpy/_encoders.py b/rocketpy/_encoders.py index 463d492ee..0560e9d75 100644 --- a/rocketpy/_encoders.py +++ b/rocketpy/_encoders.py @@ -9,7 +9,9 @@ from rocketpy.mathutils.function import Function from rocketpy.plots.flight_plots import _FlightPlots from rocketpy.prints.flight_prints import _FlightPrints -from rocketpy.simulation.solution import Solution +from rocketpy.simulation.events.views import sensor_positions +from rocketpy.simulation.flight_data_exporter import FlightDataExporter +from rocketpy.simulation.solution import Solution, _ResultsDict class RocketPyEncoder(json.JSONEncoder): @@ -221,6 +223,9 @@ def set_minimal_flight_attributes(flight, obj): ) flight.t_initial = flight.initial_solution[0] + # The events are not saved, so what they recorded is kept with the flight + flight._records = _ResultsDict(obj.get("records", {})) + flight._event_outputs = _ResultsDict(obj.get("event_outputs", {})) # Integration settings serialized by to_dict. Defaults cover older .rpy # files saved before these fields existed. @@ -233,12 +238,13 @@ def set_minimal_flight_attributes(flight, obj): # serialized separately. Mirror that derivation here so prints/plots that # iterate them work on flights loaded from .rpy files (which bypass # __init__). - flight._controllers = getattr(flight.rocket, "_controllers", [])[:] + flight.controllers = list(flight.rocket.controllers) + flight._control_owners = flight.rocket.controllables flight.sensors = flight.rocket.sensors.get_components() flight.sensors_by_name = flight.rocket.sensors_by_name - # No simulation was run, so there is no recorded sensor data. Set an empty - # mapping so code that reads ``sensor_data`` behaves like a real flight. - flight.sensor_data = {} + flight._sensors_by_key = sensor_positions( + getattr(flight.rocket, "_sensor_events", ()) + ) # The surfaces the flight's events switched on or off, with the times, # rebuilt for the surfaces of the loaded rocket. A file saved before this # was stored has none. @@ -251,6 +257,7 @@ def set_minimal_flight_attributes(flight, obj): # serialization/deserialization for custom_events and restore them here # instead of defaulting to an empty list. flight.custom_events = [] + flight.exports = FlightDataExporter(flight) def get_class_signature(obj): @@ -296,6 +303,11 @@ def get_class_from_signature(signature): type Class defined by the signature. """ + replacement = _REPLACED_CLASSES.get((signature["module"], signature["name"])) + if replacement is not None: + module_name, class_name = replacement + return getattr(import_module(module_name), class_name) + module = import_module(signature["module"]) inner_class = None @@ -305,6 +317,17 @@ def get_class_from_signature(signature): return inner_class +# Classes that no longer exist, with the class that loads what they saved. +# _Controller became the public Controller, which loads the function, rate, +# memory and gates it saved. +_REPLACED_CLASSES = { + ( + "rocketpy.control.controller", + "_Controller", + ): ("rocketpy.control.controller", "Controller"), +} + + def remove_circular_references(obj_dict): """Removes circular references from a dictionary. diff --git a/rocketpy/control/__init__.py b/rocketpy/control/__init__.py index c7fc6328a..4fe22c081 100644 --- a/rocketpy/control/__init__.py +++ b/rocketpy/control/__init__.py @@ -1,2 +1,8 @@ -from .controlled import Controlled -from .controller import _Controller +from ..simulation.helpers.conditions import FlightConditions +from .continuous_controller import ContinuousController +from .controllable import ( + Controllable, + ForceEffector, + ThrustEffector, +) +from .controller import Controller diff --git a/rocketpy/control/_helpers.py b/rocketpy/control/_helpers.py new file mode 100644 index 000000000..c61a45b43 --- /dev/null +++ b/rocketpy/control/_helpers.py @@ -0,0 +1,335 @@ +"""Helpers of the control package: the control inputs of a flight, and what +loading a saved controller or controllable needs. + +During a flight the control inputs are a plain dictionary from name to value, +such as ``{"air_brakes.deployment_level": 0.0}``: one control input per +control of each controllable on the rocket. Events and controllers write it +as ``context.controls.air_brakes.deployment_level = 0.5``, and the equations +of motion read it as ``controls``. These functions build that dictionary +(:func:`initial_controls`), keep a value inside its limits +(:func:`limited_value`) and check what an event wrote to it +(:func:`check_writes`). + +Below them: what loading a saved controller or controllable can raise, what +stands for one that could not be loaded, and the checks of the functions a +controller or an effector is built from. The deprecated positional controller +functions of v1.13 are in :mod:`rocketpy.control._legacy`. +""" + +import inspect +import math +import pickle +import warnings + +from rocketpy.tools import snake_case_key + + +def not_finite_error(name, value, writer=None): + """Return the error for a control input set to a value that is not a + finite number. ``writer`` says what wrote it, such as ``"'Roll loop'"``, + the name of an event or controller, when that is known.""" + by = f" by {writer}" if writer else "" + return ValueError( + f"The control input {name!r} was set to {value}{by}. A control input " + "must be a finite number. Check what writes it, for example for a " + "division by zero." + ) + + +def limited_value(value, limits, name="control", writer=None): + """Return ``value`` as a float, moved to the nearest of ``limits`` when it + is outside them. + + Parameters + ---------- + value : float + The value written to a control. + limits : tuple of float or None + ``(low, high)``, or ``None`` for a control without limits. + name : str, optional + The name of the control input, for the error message. + writer : str, optional + What wrote the value, for the error message. + + Returns + ------- + float + + Raises + ------ + ValueError + If the value is not a number (NaN), or is infinite and the control + has no limit on that side to bring it back to. + """ + if limits is not None: + low, high = limits + # In this order a NaN stays a NaN, and is refused below + value = min(max(value, low), high) + value = float(value) + if not math.isfinite(value): + raise not_finite_error(name, value, writer) + return value + + +def initial_controls(controllables): + """Return what a flight needs to fly the controls of ``controllables``. + + Parameters + ---------- + controllables : sequence of Controllable + The rocket's controllables, in the order they were added. + + Returns + ------- + controls : dict + Name to value, every control input at its default: the flight's + control inputs. + names : dict + Controllable to the tuple of its control input names, ``"."`` + in the order of its ``controls``, for the controllables that have controls. + limits : dict + Control input name to its ``(low, high)``, or ``None`` for no limits, + used to keep what is written inside them. + + Raises + ------ + ValueError + If two controllables have names that give the same key, since + a controller could not tell their control inputs apart. + """ + controls, names, limits = {}, {}, {} + owners = {} + for controllable in controllables: + if not controllable.controls: + continue + key = snake_case_key(controllable.name) + if key in owners: + raise ValueError( + f"The controllables '{owners[key]}' and '{controllable.name}' " + f"both have controls, and their control inputs would both be named " + f"'{key}.'. Give them different names." + ) + owners[key] = controllable.name + names[controllable] = tuple( + f"{key}.{control}" for control in controllable.controls + ) + for control, name in zip(controllable.controls, names[controllable]): + controls[name] = float(controllable.control_defaults[control]) + bounds = controllable.control_limits.get(control) + limits[name] = None if bounds is None else tuple(float(b) for b in bounds) + return controls, names, limits + + +def check_writes(controls, before, limits, writer=None): + """Check the writes an event made to the control inputs. + + Called right after an event's callback, with a copy of ``controls`` taken + before it. A written value is kept inside its limits, and counts as a + change only if it then differs from the value before. + + Parameters + ---------- + controls : dict + The flight's control inputs, as the callback left them. + before : dict + A copy of them taken before the callback. + limits : dict + Control input name to its ``(low, high)``, or ``None``. + writer : str, optional + The name of the event or controller that ran the callback, such as + ``"Roll loop"``, for the error messages. + + Returns + ------- + dict + The control inputs whose value changed, with their new value. Empty when + nothing changed. + + Raises + ------ + KeyError + If the callback added or removed a control input, such as by writing a + misspelled name. The inputs are put back as they were. + ValueError + If the callback wrote a value that is not a finite number, such as the + NaN of a division by zero. The inputs are put back as they were. + """ + if controls.keys() != before.keys(): + added = sorted(controls.keys() - before.keys()) + controls.clear() + controls.update(before) + if added: + raise KeyError( + f"There is no control input {added[0]!r}. The control inputs are: " + f"{', '.join(before) or 'none'}." + ) + raise KeyError("Control inputs cannot be removed during a flight.") + changed = {} + for name, value in controls.items(): + if value != before[name]: + # Compared again once inside the limits: a write beyond a limit + # the control already sits at changes nothing + try: + by = None if writer is None else repr(writer) + value = limited_value(value, limits[name], name, by) + except ValueError: + controls.update(before) + raise + controls[name] = value + if value != before[name]: + changed[name] = value + return changed + + +# --------------------------------------------------------------------------- +# Loading a controller or a controllable from a saved file +# --------------------------------------------------------------------------- + + +# What loading a saved function or controllable raises when it was saved without +# pickling (a name instead of the object), or its module, class or code is not +# available here +_LOAD_ERRORS = ( + TypeError, + ValueError, + AttributeError, + ImportError, + EOFError, + KeyError, + pickle.UnpicklingError, +) + + +class UnloadedControllable: + """Stands for a controllable of a saved rocket that could not be loaded: + one saved without pickling, or whose class is not available here. The + rocket leaves it out with a warning. + + Attributes + ---------- + name : str + The name of the controllable, as saved. + """ + + def __init__(self, name): + self.name = name + + def __repr__(self): + return f"UnloadedControllable(name={self.name!r})" + + +def was_loaded(part, kind, needs): + """Return whether ``part`` of a saved rocket was loaded, warning that it + is left out of the rocket when it was not. + + Parameters + ---------- + part : object + What the file gave for the part: the part itself, or what stands for + one that could not be loaded (a dict or an + :class:`UnloadedControllable`). + kind : str + What the part is, for the warning: ``"effector"``. + needs : str + What of the part must be available here to load it, for the warning: + ``"class"``. + + Returns + ------- + bool + """ + if not isinstance(part, (dict, UnloadedControllable)): + return True + # Saved without pickling, or by a class not available here + name = part.get("name") if isinstance(part, dict) else part.name + warnings.warn( + f"The {kind} '{name}' could not be loaded and was left out of the " + f"rocket: it was saved without pickling, or its {needs} is not " + "available here.", + UserWarning, + stacklevel=2, + ) + return False + + +def _missing_controller_function(context): # pylint: disable=unused-argument + """Stands in for a controller function that could not be loaded.""" + return None + + +# --------------------------------------------------------------------------- +# Functions given in place of a method: checked when the owner is built +# --------------------------------------------------------------------------- + + +def check_hook(owner, what, function, default, arguments, needed=True): + """Return ``function`` after checking it takes ``arguments``, or ``None`` + when ``owner``'s class defines the method ``what`` itself. Raise when + neither is given and the method is ``needed``. + + A :class:`ContinuousController` or an effector can be built from functions + (``law=``, ``force_and_moment=``) or subclassed with the same names as + methods. The method as the base class defines it calls the function. + + Parameters + ---------- + owner : Controllable + The controller or effector being built. Its ``name`` names it in errors. + what : str + The name of the method, such as ``"law"``. + function : callable or None + The function given in its place, if any. + default : function + The method as the base class defines it. A subclass that defines its + own replaces it, and then needs no function. + arguments : tuple of str + The names of the arguments the function takes, in order, for the + check and for the error message: ``("states", "controls", + "conditions")``, or ``("firing", "conditions")`` for an effector + with one control. + needed : bool, optional + Whether the method must be given at all. Default ``True``. + + Returns + ------- + callable or None + ``function``, or ``None`` when the owner's class defines the method. + + Raises + ------ + TypeError + If neither a function nor a method is given and one is ``needed``, if + ``function`` is not callable, or if it does not take ``arguments``. + """ + signature = f"{what}({', '.join(arguments)})" + if function is None: + if needed and getattr(type(owner), what) is default: + base = default.__qualname__.partition(".")[0] + raise TypeError( + f"'{owner.name}' needs a {what}: give {base} a function `{signature}`." + ) + return None + if not callable(function): + raise TypeError(f"The {what} must be callable, got {function!r}.") + try: + inspect.signature(function).bind(*[None] * len(arguments)) + except TypeError as error: + raise TypeError( + f"The {what} of '{owner.name}' must take {len(arguments)} arguments, " + f"like `def {signature}: ...`." + ) from error + return function + + +def _check_controller_function(function): + """Raise unless ``function`` takes the context as its one argument.""" + if not callable(function): + raise TypeError(f"The controller function must be callable, got {function!r}.") + try: + inspect.signature(function).bind(None) + except TypeError as error: + raise ValueError( + "The controller function must take the event context as its " + "single argument, like `def controller(context): ...`." + ) from error + return function diff --git a/rocketpy/control/_legacy.py b/rocketpy/control/_legacy.py new file mode 100644 index 000000000..8a4aa2439 --- /dev/null +++ b/rocketpy/control/_legacy.py @@ -0,0 +1,152 @@ +"""The deprecated positional air brakes controller functions of v1.13, +``(time, sampling_rate, state, state_history, observed_variables, +air_brakes[, sensors[, environment]])``, and ``initial_observed_variables``: +run as controller functions that take the event context. + +Remove this module, and its callers, in v1.16. +""" + +import inspect +import warnings + +from rocketpy.control._helpers import limited_value +from rocketpy.tools import snake_case_key + + +def _positional_count(function): + """Return how many positional arguments ``function`` takes, or -1 if it + takes any number.""" + parameters = inspect.signature(function).parameters.values() + if any(p.kind == p.VAR_POSITIONAL for p in parameters): + return -1 + return sum( + p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in parameters + ) + + +def _legacy_controller( + function, sampling_rate, part_name=None, initial_observed_variables=None +): + """Return the function of a :class:`Controller`: ``function`` itself when + it takes the context, or a positional one wrapped in + :class:`_PositionalController`, with ``initial_observed_variables`` as + the start of its ``observed_variables``. Warn about either.""" + if initial_observed_variables is not None: + warnings.warn( + "`initial_observed_variables` is deprecated: record the values you " + "want to see after the flight with `context.record(...)` and read " + "them as `flight.records`. It will be removed in v1.16.", + DeprecationWarning, + stacklevel=3, + ) + try: + # Callable with the context alone, whatever else it accepts + inspect.signature(function).bind(None) + return function + except TypeError: + pass + count = _positional_count(function) + if count not in (-1, 6, 7, 8): + raise ValueError( + "controller_function must take the event context as its single " + "argument, like `def controller(context): ...`. A deprecated " + "positional controller_function must have 6, 7 or 8 arguments, (time, " + "sampling_rate, state, state_history, observed_variables, " + f"air_brakes[, sensors[, environment]]), but {count} were given." + ) + warnings.warn( + "Calling controller_function with positional arguments is deprecated; " + "use controller_function(context) instead. It will be removed in v1.16.", + DeprecationWarning, + stacklevel=3, + ) + return _PositionalController( + function, sampling_rate, part_name, initial_observed_variables + ) + + +class _PositionalController: + """Run a positional controller function as one that takes the context. + ``state_history`` is the flight's rows so far, and ``observed_variables`` + gains each value returned other than ``None``. + + The list is kept here, not in the controller's memory: memory is copied + before every run so a rollback can put it back, and a history that grows + with every sample would make each copy longer than the last. As in + v1.13, a rollback does not shorten it. It starts again at every flight + (:meth:`reset`, called by ``Controller.reset``).""" + + def __init__( + self, function, sampling_rate, part_name=None, initial_observed_variables=None + ): + self.function = function + self.sampling_rate = sampling_rate + # None: the rocket's only controllable with controls + self.part_key = None if part_name is None else snake_case_key(part_name) + self.__name__ = getattr(function, "__name__", "controller_function") + self._count = _positional_count(function) + self._initial_observed = ( + [] if initial_observed_variables is None else [initial_observed_variables] + ) + self.observed_variables = list(self._initial_observed) + + def reset(self): + """Start ``observed_variables`` again, for a new flight.""" + self.observed_variables = list(self._initial_observed) + + def __getstate__(self): + # Saved as built: a loaded controller starts with an empty history + return {**self.__dict__, "observed_variables": list(self._initial_observed)} + + def __call__(self, context): + controllables = [ + controllable + for controllable in context["rocket"].controllables + if self.part_key in (None, snake_case_key(controllable.name)) + ] + if len(controllables) != 1: + raise ValueError( + f"The controller function '{self.__name__}' moves one " + f"controllable, but the rocket has {len(controllables)} that it " + "could be. Write it as `controller_function(context)` and set " + "`context.controls[...]`." + ) + observed = self.observed_variables + arguments = [ + context["time"], + self.sampling_rate, + context["canonical_state"], + context._solution._rows, # pylint: disable=protected-access + observed, + _AirBrakesView(controllables[0], context["controls"]), + [sensor for sensor, _ in context["sensors"].values()], + context["environment"], + ] + result = self.function(*arguments[: self._count if self._count >= 0 else None]) + if result is not None: + observed.append(result) + return result + + +class _AirBrakesView: + """The air brakes as a positional controller sees them: ``deployment_level`` + is the flight's control input, kept inside its limits; anything else is + read from the air brakes.""" + + def __init__(self, air_brakes, controls): + self._air_brakes = air_brakes + self._controls = controls + self._name = f"{snake_case_key(air_brakes.name)}.deployment_level" + + @property + def deployment_level(self): + return self._controls[self._name] + + @deployment_level.setter + def deployment_level(self, value): + self._controls[self._name] = limited_value( + value, self._air_brakes.control_limits["deployment_level"], self._name + ) + + def __getattr__(self, name): + return getattr(self._air_brakes, name) diff --git a/rocketpy/control/continuous_controller.py b/rocketpy/control/continuous_controller.py new file mode 100644 index 000000000..4681f5c51 --- /dev/null +++ b/rocketpy/control/continuous_controller.py @@ -0,0 +1,136 @@ +from rocketpy.control._helpers import check_hook +from rocketpy.control.controllable import Controllable + + +class ContinuousController(Controllable): + """Adds a continuous controller to the rocket: a control law that acts at + every instant of the flight, with no sampling rate. Add it with + :meth:`rocketpy.Rocket.add_controller`. + + It models what responds continuously to the rocket's motion: a passive + damper, an analog loop, or an ideal law studied before a sampling rate + is chosen. A :class:`rocketpy.Controller` is a flight computer that + reads and acts at discrete samples; a continuous controller is part of + the rocket's dynamics, and the flight integrates the closed loop as one. + + The law is given the controller's own states and the flight's + conditions, and sets the control inputs within their limits. A law with + dynamics of its own, such as an integral term or a filter, keeps them as + states that the flight integrates with the rocket's, starting from 0. A + controller with states and no law writes no controls: an observer, whose + estimate the other controllers read as a state. + + Because it acts at every instant, a continuous controller has no memory + between instants, no records, no commands and no outputs: its law must + depend on its arguments alone, and it cannot read the outputs of the + flight's events. After the flight, its states are read from + ``flight.state_history`` and what it set from ``flight.controls``. + + See :ref:`continuous_controller` for examples. + + Attributes + ---------- + law_function : callable or None + The control law, or ``None`` for a controller with states and no law. + derivative_function : callable or None + The derivative of the controller's states with respect to time, or + ``None`` for a controller without states. + states : tuple of str + Names of the controller's own states. + """ + + def __init__( + self, + law=None, + states=None, + state_derivative=None, + name="Continuous Controller", + ): + """Build a continuous controller. + + Parameters + ---------- + law : callable, optional + ``law(states, controls, conditions)``, the control law: it reads + its own states and the flight's conditions (see + :class:`rocketpy.control.FlightConditions`), and writes the + control inputs as ``controls.canards.fin_1``. Required, except + for a controller with ``states``, which may have none. + states : sequence of str, optional + Names of the controller's own states, such as ``("integral",)``. + Each starts the flight at 0. Default: none. + state_derivative : callable, optional + ``state_derivative(states, controls, conditions)``: returns a list + with the derivative with respect to time of each state, one value + per state in the order of ``states``, even for a single state + (``[conditions.state.w3]``, not ``conditions.state.w3``). + Required with ``states``. + name : str, optional + Name of the controller, which names its states in the flight. + Default ``"Continuous Controller"``. + """ + # A controllable with states and no controls of its own + super().__init__(name, ()) + if states is not None: + # One name given alone is one state + self.states = (states,) if isinstance(states, str) else tuple(states) + self._check_state_names() + if state_derivative is not None and not self.states: + raise ValueError( + f"'{name}' has a state_derivative but no states: name them " + 'with `states=`, like `states=("integral",)`.' + ) + arguments = ("states", "controls", "conditions") + # A controller that only has states writes no controls and needs no law + self.law_function = check_hook( + self, "law", law, ContinuousController.law, arguments, not self.states + ) + self.derivative_function = check_hook( + self, + "state_derivative", + state_derivative, + ContinuousController.state_derivative, + arguments, + needed=bool(self.states), + ) + + def law(self, states, controls, conditions): + """Write the control inputs for this instant, by calling the control + law. + + Parameters + ---------- + states : sequence of float + The controller's own states, in the order of ``states``. + controls : ControlsView + The control inputs, to read and write as + ``controls.canards.fin_1``. + conditions : FlightConditions + The flight at this moment. + """ + if self.law_function is not None: + self.law_function(states, controls, conditions) + + def state_derivative(self, states, commands, conditions): + """Return the derivative with respect to time of each state, in the + order of ``states``. + + Parameters + ---------- + states : sequence of float + The controller's own states, in the order of ``states``. + commands : ControlsView + The control inputs, read as ``commands.canards.fin_1``, as the + laws left them, inside their limits: not the values a + controllable with states of its own, such as a servo, acts with. + conditions : FlightConditions + The flight at this moment. + + Returns + ------- + sequence of float + """ + return self.derivative_function(states, commands, conditions) + + def __repr__(self): + return f"ContinuousController(name={self.name!r}, states={self.states!r})" diff --git a/rocketpy/control/controllable.py b/rocketpy/control/controllable.py new file mode 100644 index 000000000..b967ca0be --- /dev/null +++ b/rocketpy/control/controllable.py @@ -0,0 +1,541 @@ +import keyword + +from rocketpy.control._helpers import ( + _LOAD_ERRORS, + UnloadedControllable, + check_hook, + limited_value, +) +from rocketpy.prints.controller_prints import _ControllablePrints +from rocketpy.tools import from_hex_decode, snake_case_key, to_hex_encode + + +class Controllable: + """A part of the rocket with controls, which a controller can move. + + A controllable never holds the live value of a control: during a flight + the values live in the flight's control inputs, and the controllable's + physics receives them as arguments. Its controls are named + ``"."`` in the flight, such as + ``canards.fin_1``. + + A surface with no controls is still a :class:`Controllable`: every + aerodynamic surface is one, with ``controls`` empty. + + Attributes + ---------- + name : str + Name of the controllable. Its control inputs are named after it. + controls : tuple of str + Names of the controls, in the order the physics expects their values. + control_defaults : dict + Value of each control at the start of every flight, and the value used + outside a flight. + control_limits : dict + ``(low, high)`` of each control, or ``None`` for no limits. A value + written outside them is moved to the nearest limit. + states : tuple of str + Names of the controllable's own states, which the flight integrates + along with the rocket's: the position an actuator has reached, the + gas left in a thruster's tank, the integral of a continuous law. + Empty (the default) for a controllable that acts at once with the + values written to its controls. In the flight, a state ``angle`` of + the controllable ``"Canards"`` is named ``canards_angle``. + """ + + states = () + + def __init__( + self, + name, + controls=(), + control_defaults=None, + control_limits=None, + ): + """Set the controllable's name and controls. + + Parameters + ---------- + name : str + Name of the controllable. Its control inputs are named after it in + snake_case, lower case with words joined by underscores: + ``"Air Brakes"`` gives ``air_brakes.``, ``"TVCGimbal"`` + gives ``tvc_gimbal.`` and ``"Fin #2 (left)"`` gives + ``fin_2_left.``. + controls : tuple of str, optional + Names of the controls a controller can set, such as + ``("firing",)``. Each must be made of letters, digits and + underscores and not start with a digit or an underscore. Default + is no controls. + control_defaults : dict, optional + Value of each control at the start of every flight, by name. A + control left out starts at 0. Default ``None``. + control_limits : dict, optional + ``(low, high)`` of each control that has limits, by name: the + range the mechanism can reach. A value written outside it is + moved to the nearest limit. Default ``None``, no limits. + + Raises + ------ + ValueError + If a control name is not a valid name or is repeated, if + ``control_defaults`` or ``control_limits`` name something that is + not a control, or if limits are not ``(low, high)`` with + ``low <= high``. + TypeError + If the default of a control is not a number. + """ + self.name = name + self._set_controls(controls, control_defaults, control_limits) + self.prints = _ControllablePrints(self) + + def info(self): + """Print the controllable's name, the functions it was built from, + its controls and its states. + + Returns + ------- + None + """ + self.prints.all() + + def all_info(self): + """Print all the information about the controllable. + + Returns + ------- + None + """ + self.info() + + def _set_controls(self, controls, defaults, limits): + """Check and store the controls. Needs ``self.name``.""" + # One name given alone is one control + self.controls = (controls,) if isinstance(controls, str) else tuple(controls) + # A control left out of the defaults starts at 0 + self.control_defaults = { + **dict.fromkeys(self.controls, 0.0), + **dict(defaults or {}), + } + self.control_limits = dict(limits or {}) + self._check_controls() + for control in self.controls: + given = self.control_limits.get(control) + self.control_limits[control] = None if given is None else tuple(given) + self.control_defaults[control] = limited_value( + self.control_defaults[control], self.control_limits[control], control + ) + + def _check_controls(self): + """Raise if the controls cannot be flown: a control named twice or not + as a plain name, a control without a number as its default, limits + that are not ``(low, high)`` with ``low <= high``, or defaults or + limits for something that is not a control. + + Called when the controllable is built and again when it is added to a rocket, + since the defaults and limits can be changed in between.""" + name, controls = self.name, tuple(self.controls) + defaults, limits = self.control_defaults, self.control_limits + if len(set(controls)) != len(controls): + raise ValueError(f"'{name}' lists a control more than once: {controls}.") + for control in controls: + if ( + not isinstance(control, str) + or not control.isidentifier() + or keyword.iskeyword(control) + or control.startswith("_") + ): + raise ValueError( + f"'{name}' has a control named {control!r}. A control name " + "must be made of letters, digits and underscores, must not " + "start with a digit or an underscore, and must not be a " + "Python keyword." + ) + if control not in defaults: + raise ValueError(f"The control '{control}' of '{name}' has no default.") + try: + float(defaults[control]) + except (TypeError, ValueError) as error: + raise TypeError( + f"The default of the control '{control}' of '{name}' must be " + f"a number, got {defaults[control]!r}." + ) from error + bounds = limits.get(control) + if bounds is None: + continue + what = f"The limits of the control '{control}' of '{name}'" + try: + low, high = (float(value) for value in bounds) + except (TypeError, ValueError) as error: + raise ValueError( + f"{what} must be (low, high) or None, got {bounds!r}." + ) from error + if low > high: + raise ValueError( + f"{what} are ({low}, {high}): the first must not be larger " + "than the second." + ) + for setting, given in ( + ("control_defaults", defaults), + ("control_limits", limits), + ): + unknown = sorted(set(given) - set(controls)) + if unknown: + raise ValueError( + f"'{name}' has {setting} for {unknown}, which are not among " + f"its controls {controls}." + ) + + def _check_state_names(self): + """Raise if a state is not named as a plain name. The flight names + each state ``_`` and reads it by that name, + which must not look like a control input, ``.``.""" + for state in self.states: + if not isinstance(state, str) or not state.isidentifier(): + raise ValueError( + f"The states of '{self.name}' must be names made of letters, " + f"digits and underscores, got {state!r}." + ) + + def _check_states(self): + """Raise if the states cannot be flown: a state not named as a plain + name, or an ``initial_states`` that does not give one value per state, + since the flight seeds the states from it. Called when the + controllable is added to a rocket.""" + self._check_state_names() + starts = len(list(self.initial_states())) + if starts != len(self.states): + raise ValueError( + f"'{self.name}' has {len(self.states)} states, but its " + f"initial_states gives {starts} values." + ) + + def initial_states(self): + """Return the value of each of the controllable's states at the start of a + flight, in the order of ``states``. Defaults to 0 for every state. + + Returns + ------- + sequence of float + """ + return [0.0] * len(self.states) + + def state_derivative(self, states, commands, conditions): # pylint: disable=unused-argument + """Return the derivative with respect to time of each of the controllable's + states, in the order of ``states``. It must depend on its arguments + alone: no memory, no side effects. + + Parameters + ---------- + states : sequence of float + The values of the controllable's states, in the order of ``states``. + commands : list of float + The values written to the controllable's controls, in the order of + ``controls``. + conditions : FlightConditions + The flight at this moment. See + :class:`rocketpy.control.FlightConditions`. + + Returns + ------- + sequence of float + One value per state. Empty for a controllable without states. + """ + return () + + def actual_controls(self, states, commands, conditions): # pylint: disable=unused-argument + """Return the values the controllable acts with, one per control, from what + was written to its controls and the controllable's states. + + The controllable's physics receives these values, not the ones + written: an actuator returns the position it has reached, one of its + states. Defaults to the values written, unchanged. It must depend on + its arguments alone. + + Parameters + ---------- + states : sequence of float + The values of the controllable's states, in the order of ``states``. + commands : list of float + The values written to the controllable's controls, in the order of + ``controls``. + conditions : FlightConditions + The flight at this moment. See + :class:`rocketpy.control.FlightConditions`. + + Returns + ------- + sequence of float + One value per control, in the order of ``controls``. + """ + return commands + + def _acts_on_its_own(self): + """Whether the controllable has anything to add to the equations of + motion beyond its physics: states of its own, or an ``actual_controls`` + of its own.""" + return bool(self.states) or ( + type(self).actual_controls is not Controllable.actual_controls + ) + + def _state_names(self): + """The names of the controllable's states in the flight: ``_``, such as ``canards_angle``.""" + key = snake_case_key(self.name) + return tuple(f"{key}_{state}" for state in self.states) + + def _default_control_values(self): + """The defaults of the controls, in order: the values used outside a + flight.""" + return tuple(self.control_defaults[name] for name in self.controls) + + def _control_settings(self): + """The controls, defaults and limits, as saved by ``to_dict``.""" + return { + "controls": list(self.controls), + "control_defaults": dict(self.control_defaults), + "control_limits": { + name: None if limits is None else list(limits) + for name, limits in self.control_limits.items() + }, + } + + def to_dict(self, **kwargs): + """Return the controllable as a dictionary, to be saved. + + A controllable written by the user holds its physics in code, so the controllable + itself is saved pickled, next to its control settings for reading. + RocketPy's own controllables save their parameters instead. + + Parameters + ---------- + **kwargs : dict + ``allow_pickle`` (default ``True``): save the controllable itself. With + ``False`` only its name and control settings are saved, and the + controllable is left out of the rocket when the file is loaded. + + Returns + ------- + dict + """ + data = {"name": self.name, **self._control_settings()} + if kwargs.get("allow_pickle", True): + data["controllable"] = to_hex_encode(self) + return data + + @classmethod + def from_dict(cls, data): + """Build the controllable from a dictionary made by :meth:`to_dict`. + + Parameters + ---------- + data : dict + + Returns + ------- + Controllable or UnloadedControllable + The controllable, or an ``UnloadedControllable``, which only + keeps its name, when it was saved without pickling or its class + is not available here. + """ + try: + return from_hex_decode(data["controllable"]) + except _LOAD_ERRORS: + return UnloadedControllable(data.get("name")) + + +class ThrustEffector(Controllable): + """A controllable that turns the motor's thrust, such as a gimbaled nozzle + or jet vanes. Add it with :meth:`rocketpy.Rocket.add_effector`. + + The thrust is the motor's, as the thrust curve of the rocket's + :class:`rocketpy.Motor` gives it at that instant, along the rocket's + axis at the nozzle exit. It is a force along a line: its vector and the + nozzle exit it passes through. The effector receives both and returns + both, and the moment of the thrust on the rocket is taken about the + returned exit. Several thrust effectors act in turn, in the order they + were added. + + Built from a function. See :ref:`controllers` for examples. + + Attributes + ---------- + thrust_function : callable + The function the effector was built from. + """ + + def __init__( + self, + thrust_and_nozzle=None, + controls=(), + control_defaults=None, + control_limits=None, + name="Thrust Effector", + ): + """Build a thrust effector. + + Parameters + ---------- + thrust_and_nozzle : callable + ``thrust_and_nozzle(thrust, nozzle, *controls, conditions)``: the + thrust so far, in N, where the nozzle exit is so far, in m from the + center of dry mass, one value per control in the order of + ``controls``, and the flight at this moment, a + :class:`rocketpy.control.FlightConditions`. Returns ``(thrust, + nozzle)`` after the effector, each three numbers in the body frame. + controls : tuple of str, optional + Names of the controls a controller can set, such as + ``("pitch", "yaw")``. Default: none. + control_defaults : dict, optional + Value of each control at the start of a flight. Controls not + listed start at 0. + control_limits : dict, optional + ``(low, high)`` for each control that has limits. A value written + outside them is moved to the nearest limit. + name : str, optional + Name of the effector. Its controls are named after it, in + snake_case: ``"TVC Gimbal"`` gives ``tvc_gimbal.``. + Default ``"Thrust Effector"``. + """ + super().__init__( + name=name, + controls=controls, + control_defaults=control_defaults, + control_limits=control_limits, + ) + self.thrust_function = check_hook( + self, + "thrust_and_nozzle", + thrust_and_nozzle, + ThrustEffector.thrust_and_nozzle, + ("thrust", "nozzle", *self.controls, "conditions"), + ) + + def thrust_and_nozzle(self, thrust, nozzle, controls, conditions): + """Return the thrust force and the nozzle exit after this effector has + acted on them. + + Parameters + ---------- + thrust : Vector + The thrust force so far, in N, in the rocket's body frame: + ``[0, 0, T]`` for the motor alone, with z along the rocket's axis + toward the nose. + nozzle : Vector + Where the nozzle exit is so far, in m, in the body frame from the + center of dry mass. The thrust acts along a line through it. + controls : list of float + The values the effector acts with, in the order of ``controls``. + conditions : FlightConditions + The flight at this moment. See + :class:`rocketpy.control.FlightConditions`. + + Returns + ------- + tuple + ``(thrust, nozzle)``: the new thrust force, in N, and where the + nozzle exit now is, in m, each three numbers in the body frame. + An effector that does not move the nozzle returns ``nozzle`` as + it was given. + """ + return self.thrust_function(thrust, nozzle, *controls, conditions) + + def __repr__(self): + return f"ThrustEffector(name={self.name!r}, controls={self.controls!r})" + + +class ForceEffector(Controllable): + """A controllable that pushes or turns the rocket directly, other than + through the air or the motor: a cold-gas thruster, a reaction wheel. Add + it with :meth:`rocketpy.Rocket.add_effector`. + + It returns a force and a moment in the rocket's body frame: ``z`` along + the rocket toward the nose, ``x`` and ``y`` the axes the fins are placed + in (see :ref:`rocket_axes`). The moment is about the center of dry mass, + unless the effector was placed with the ``position`` of + :meth:`rocketpy.Rocket.add_effector`: the flight then adds the moment of + the force about that point, and the returned moment is only a pure + couple, such as a reaction wheel's torque. An effector is not + aerodynamic: it takes no part in the static margin or the center of + pressure. + + Built from a function. See :ref:`controllers` for examples and the + frame conventions in full. + + Attributes + ---------- + force_function : callable + The function the effector was built from. + """ + + def __init__( + self, + force_and_moment=None, + controls=(), + control_defaults=None, + control_limits=None, + name="Force Effector", + ): + """Build a force effector. + + Parameters + ---------- + force_and_moment : callable + ``force_and_moment(*controls, conditions)``: one value per control + in the order of ``controls``, and the flight at this moment, a + :class:`rocketpy.control.FlightConditions`. Returns ``(force, + moment)``, each three numbers in the body frame: the force in N + and the moment in N m, about the center of dry mass or, for a + placed effector, the pure couple. + controls : tuple of str, optional + Names of the controls a controller can set, such as ``("firing",)``. + Default: none. + control_defaults : dict, optional + Value of each control at the start of a flight. Controls not + listed start at 0. + control_limits : dict, optional + ``(low, high)`` for each control that has limits. A value written + outside them is moved to the nearest limit. + name : str, optional + Name of the effector. Its controls are named after it, in + snake_case: ``"RCS"`` gives ``rcs.``. Default + ``"Force Effector"``. + """ + super().__init__( + name=name, + controls=controls, + control_defaults=control_defaults, + control_limits=control_limits, + ) + self.force_function = check_hook( + self, + "force_and_moment", + force_and_moment, + ForceEffector.force_and_moment, + (*self.controls, "conditions"), + ) + + def force_and_moment(self, controls, conditions): + """Return the force and moment the effector applies to the rocket, in + the body frame. + + Parameters + ---------- + controls : list of float + The values the effector acts with, in the order of ``controls``. + conditions : FlightConditions + The flight at this moment. See + :class:`rocketpy.control.FlightConditions`. + + Returns + ------- + tuple + ``(force, moment)``, each three numbers in the body frame: the + force in N and the moment in N m, about the rocket's center of dry + mass or, for a placed effector, the pure couple added to the + moment of the force where it acts. + """ + return self.force_function(*controls, conditions) + + def __repr__(self): + return f"ForceEffector(name={self.name!r}, controls={self.controls!r})" diff --git a/rocketpy/control/controlled.py b/rocketpy/control/controlled.py deleted file mode 100644 index 4d655913c..000000000 --- a/rocketpy/control/controlled.py +++ /dev/null @@ -1,46 +0,0 @@ -class Controlled: - """The objects a controller drives, read by name or by position. - - ``context.controlled`` is one of these inside a controller function. An - object given a name is read by that name, ``context.controlled.air_brakes``. - Any object can be read by its position, ``context.controlled[0]``, and - looping over ``context.controlled`` gives every object in the order they - were passed to the controller. - """ - - def __init__(self, objects, names=()): - """Hold the controlled objects. - - Parameters - ---------- - objects : sequence of object - The objects the controller drives. - names : sequence of str, optional - The name of each object, in the same order. Default is no names. - """ - self._objects = tuple(objects) - self._names = tuple(names) - for name, controlled_object in zip(self._names, self._objects): - setattr(self, name, controlled_object) - - def __getattr__(self, name): - # Only reached for a name no object was given. - if name.startswith("_"): - raise AttributeError(name) - available = ", ".join(self._names) or "none; read them by position" - raise AttributeError( - f"This controller has no controlled object named {name!r}. The " - f"names available are: {available}." - ) - - def __getitem__(self, index): - return self._objects[index] - - def __iter__(self): - return iter(self._objects) - - def __len__(self): - return len(self._objects) - - def __repr__(self): - return f"Controlled(names={self._names!r}, objects={self._objects!r})" diff --git a/rocketpy/control/controller.py b/rocketpy/control/controller.py index 71c24342c..fec2b5009 100644 --- a/rocketpy/control/controller.py +++ b/rocketpy/control/controller.py @@ -1,483 +1,275 @@ -import warnings -from inspect import signature -from keyword import iskeyword +"""Controllers: events that set the rocket's control inputs while it flies.""" -from rocketpy.simulation.events.event import Event +import warnings +from copy import deepcopy + +from rocketpy.control._helpers import ( + _LOAD_ERRORS, + _check_controller_function, + _missing_controller_function, +) +from rocketpy.control._legacy import _legacy_controller, _PositionalController +from rocketpy.simulation.events.event import PRESETS, Event from rocketpy.tools import from_hex_decode, to_hex_encode from ..prints.controller_prints import _ControllerPrints -from .controlled import Controlled - - -class _Controller: - """A controller that modifies rocket state during simulation. - - Controllers execute at a fixed sampling rate and can mutate rocket - objects (e.g. air brakes, fins) during flight. Like :class:`Event` - objects, controllers use a callback pattern with a persistent ``memory``, - but they explicitly expect external object state to change. - Internally a controller is a thin wrapper around an :class:`Event`: it - builds an event (see :meth:`to_event`) whose callback invokes the - user-supplied ``controller_function``. The wrapping event is created with - ``changes_dynamics=True``, ``trigger_only_once=False``, and - ``priority=3``, and it mirrors the controller's ``enabled`` flag, - ``memory``, ``sampling_rate``, ``disable_on`` and ``enable_on`` settings. - The controller function is responsible for: - - 1. Reading simulation state and sensor data, - 2. Computing control actions, - 3. Mutating ``controlled_objects`` to apply those actions, - 4. Returning logging information (appended to :attr:`log`). - - The key difference from :class:`Event` is that object mutations are - intentional and expected -- this is the controller's primary purpose. - - Attributes - ---------- - event : Event - The wrapping :class:`Event` consumed by the simulation loop. - log : list - Per-execution return values of ``controller_function`` (alias - :attr:`return_log`). Backed by the wrapped event's ``callback_log``. - enabled : bool - Current enabled state, mirrored from the wrapped event. - context : dict - Persistent state shared across executions. +class Controller(Event): + """Adds a controller to the rocket: a flight computer that runs at a fixed + sampling rate and sets the rocket's controls. Add it with + :meth:`rocketpy.Rocket.add_controller`. + + At every sample the controller reads what the rocket knows, its state + and its sensors, and decides the controls: the deployment level of the + air brakes, the deflection of the canards, the firing of a thruster. A + value it sets stays in force until the next sample, as a real flight + computer holds its outputs between cycles, and the rocket responds to it + through the part it controls. + + The controller can keep values from one sample to the next, such as the + integral of a PID loop, record values to look at after the flight, and + be switched off and on during the flight, at apogee, at burnout or when + a condition it defines is met. After the flight, what it set is read + from ``flight.controls`` and what it recorded from + ``flight.records``. A controller can also share values with other + controllers, such as the setpoint an outer loop gives an inner one, as + outputs. + + See :ref:`controllers` for examples and :ref:`eventusage` for what the + controller is told about the flight. """ - def __init__( + def __init__( # pylint: disable=too-many-arguments self, controller_function, - controlled_objects, sampling_rate, memory=None, + *, + outputs=None, name="Controller", - controlled_objects_name=None, enabled=True, - disable_on=None, enable_on=None, + disable_on=None, + time_overshootable=True, ): - """Initialize the controller. + """Build a controller. Parameters ---------- controller_function : callable - Function that executes the control logic, with signature - ``controller_function(context) -> dict or None``. Invoked once - per sample; its return value is appended to :attr:`log`. Mutate - ``controlled_objects`` directly to apply control actions. - ``context`` holds the values listed in :class:`rocketpy.Event` - (``context.time``, ``context.state``, ``context.height_agl``, - ``context.sensors``, ``context.environment``, ``context.rocket``, - ``context.flight``, ``context.state_dot``, ``context.pressure``, - ``context.previous_state`` and so on) plus ``context.controller`` - (this :class:`_Controller` instance) and ``context.controlled`` - (the objects to mutate). Read a controlled object by the name - given in ``controlled_objects_name``, such as - ``context.controlled.air_brakes``, or by its position, such as - ``context.controlled[0]``. - For the trajectory itself, read ``context.flight.solution``. - controlled_objects : object or list of object - Object(s) the controller is allowed to modify (e.g. an air brakes - instance). May be a single object or a list. They are held by - reference, so mutations persist in the simulation. + The control logic, ``controller_function(context)``, called once + per sample. It writes the controls as + ``context.controls..``, among the names + ``rocket.control_names`` lists, and may keep values for after + the flight with ``context.record``. What it returns is ignored. sampling_rate : float - Rate in hertz at which the controller executes; it runs every - ``1 / sampling_rate`` seconds. + How many times per second the controller runs, in Hz. Must be + positive. For a law that acts at every instant instead of at a + fixed rate, use :class:`rocketpy.ContinuousController`. memory : dict, optional - The controller's own dictionary, kept from one run to the next. - Read and write it as ``context.controller.memory``. It is the - same dict as the wrapped event's ``memory``. Defaults to an empty - dict. + Values the controller keeps from one run to the next, read and + written as ``context.memory``, such as the integral of a PID + controller. It starts again from this dictionary at every flight. + Defaults to an empty dictionary. + outputs : sequence of str or dict, optional + Values this controller computes for other controllers or events + to read. Give the name of each output. It is then written and + read through ``context.outputs``, under the controller's name in + snake_case: a controller with ``name="Guidance"`` and + ``outputs=("setpoint",)`` writes + ``context.outputs.guidance.setpoint = 0.1``, and any other + controller or event reads the same name. An output can hold any + value, keeps it until it is written again, and can be written + only by the controller that declared it. It starts every flight + as ``None``, or at the value given with a dictionary, such as + ``outputs={"setpoint": 0.05}``. After the flight, + ``flight.event_outputs.guidance.setpoint`` is the list of + ``(time, value)`` pairs written. Default ``None``, no outputs. name : str, optional - Human-readable controller name, used for identification and - logging. Defaults to ``"Controller"``. - controlled_objects_name : str or list of str, optional - Name(s) under which the controller function reads the controlled - objects, as ``context.controlled.``. For example, with - ``controlled_objects_name="air_brakes"`` the function reads - ``context.controlled.air_brakes``. Pass a single string for a - single object, or a list/tuple of unique strings, one per object, - when ``controlled_objects`` is a list. Each name must be usable - after a dot in Python: letters, digits and underscores, not - starting with a digit or an underscore. Defaults to ``None``, in - which case the objects are read by position, as - ``context.controlled[0]``. + Name of the controller, which names its records and outputs: + ``"Apogee Controller"`` gives ``flight.records.apogee_controller``. + Defaults to ``"Controller"``. enabled : bool, optional - Initial enabled state of the wrapped event. If ``False``, the - controller does not execute until re-enabled, either via the - ``enable`` command or the ``enable_on`` condition. Defaults to - ``True``. - disable_on : str or int or float or callable, optional - Condition that automatically disables the controller. May be a - string preset (``"apogee"`` or ``"burnout"``), a simulation time in - seconds (int or float), or a callable ``function(context)`` that - returns ``True`` when the controller should be disabled. The - condition is forwarded to the wrapped event. Defaults to ``None`` - (no automatic disabling). - enable_on : str or int or float or callable, optional - Condition that automatically re-enables a disabled controller, - using the same formats as ``disable_on``. When the condition is met - while the controller is disabled, it re-enables before the next - trigger evaluation. Defaults to ``None`` (no automatic enabling). + Whether the controller runs from the start of the flight. It can + be changed after the controller is built, ``controller.enabled = + False``, and every flight from then on starts that way. Defaults + to ``True``. + enable_on : str, float or callable, optional + When a stopped controller starts running: ``"apogee"``, + ``"burnout"``, a time in seconds, or a function ``f(context)`` that + returns ``True`` when the controller should start. Defaults to + ``None``, never. + disable_on : str, float or callable, optional + When to stop running, in the same forms as ``enable_on``. Defaults + to ``None``, never. To stop from inside ``controller_function`` + instead, such as after detecting a fault, call + ``context.commands.disable()``. + time_overshootable : bool, optional + ``True`` (the default) lets the solver step past each sample and + runs the controller on the interpolated state, restarting the + solver at the sample only when a control changes. ``False`` stops + the solver at every sample. The default is faster; the results + differ only by the solver's choice of steps. Ignored when the + flight has ``time_overshoot=False``. See Also -------- - to_event : Builds the :class:`Event` that wraps this controller. - :ref:`eventusage` : Description of the callback ``context``. + rocketpy.Event : What the context offers and how events are gated. + rocketpy.ContinuousController : A controller that runs with the + dynamics instead of at a fixed rate. + rocketpy.Rocket.add_controller : Add the controller to a rocket. + rocketpy.Flight.controls : The control inputs after the flight. + rocketpy.Flight.records : The values recorded with ``context.record``. + rocketpy.Flight.event_outputs : The outputs written during the flight. """ - # TODO: rethink controllers - self.controller_function = self.__evaluate_controller_function( - controller_function - ) - self.controlled_objects = controlled_objects - # Optional name(s) the controller function reads the objects by. - # Accept either a single string name or an iterable of string names - self.controlled_objects_name = controlled_objects_name - self._controlled = self.__build_controlled() - self.sampling_rate = sampling_rate - self.name = name - self.memory = memory if memory is not None else {} - self.prints = _ControllerPrints(self) - self.enabled = enabled - self.disable_on = disable_on - self.enable_on = enable_on - - # Create the event during initialization - self.event = self.to_event() - self.log = self.event.callback_log - - def __evaluate_controller_function(self, controller_function): - """Detect legacy positional-argument signatures and wrap them for compatibility.""" - sig = signature(controller_function) - params = list(sig.parameters.values()) - positional_count = sum( - p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in params - ) - accepts_var_positional = any(p.kind == p.VAR_POSITIONAL for p in params) - - if positional_count == 1 and not accepts_var_positional: - return controller_function - - if positional_count == 0 and not accepts_var_positional: + controller_function = _check_controller_function(controller_function) + # A controller with no rate would run once per solver step, so how + # often it ran would depend on the solver's tolerances + if sampling_rate is None or not sampling_rate > 0: raise ValueError( - "controller_function must take the event context as its single " - "positional argument, like `def controller(context): ...`." + f"The sampling rate of the controller '{name}' must be a " + f"positive number of Hz, got {sampling_rate!r}. For a law that " + "acts at every instant, use rocketpy.ContinuousController." ) - - warnings.warn( - "It is recommended not to use positional arguments when defining " - "a controller function. Instead, define it as " - "`controller_function(context)` and read values such as " - "`context.time`, `context.state`, `context.sensors` and " - "`context.environment`. See the controller documentation for " - "the full list of available values.", - UserWarning, - stacklevel=3, - ) - - def wrapped(context): - args = [ - context["time"], - self.sampling_rate, - context["canonical_state"], - self.log, - self.controlled_objects, - ] - if positional_count >= 6 or accepts_var_positional: - args.append(context["sensors"]) - if positional_count >= 7 or accepts_var_positional: - args.append(context["environment"]) - return controller_function(*args) - - return wrapped - - def to_event(self): - """Create an Event that wraps this controller for simulation execution. - - Returns - ------- - Event - Event configured for controller sampling rate and callback. - - Notes - ----- - The Event callback directly invokes the controller function with - proper parameters. The controller is responsible for mutating - controlled_objects to apply control actions. - """ - - def controller_callback(context): - """Execute controller and handle mutations. - - Parameters - ---------- - context : EventContext - Event context including: - - time: float, simulation time - - state: list, state vector - - sensors: dict, sensor measurements - - environment: Environment, environmental model - - event: Event, the event object itself - - controller: _Controller, this controller instance - - (other standard Event context keys) - - Returns - ------- - dict or None - callback_log dict from controller function, logged to callback_log. - """ - # These belong to this controller alone; the context is shared - # with the other events of the step, so they are owned rather - # than written outright and are removed when the next event binds. - context.own(controller=self, controlled=self._controlled) - return self.controller_function(context) - - return Event( - callback=controller_callback, - name=f"{self.name}", - sampling_rate=self.sampling_rate, - memory=self.memory, - changes_dynamics=True, + # Kept as given, for saving: the event turns them into functions + self._gates = (disable_on, enable_on) + super().__init__( + callback=controller_function, + sampling_rate=sampling_rate, + memory=memory, + disable_on=disable_on, + enable_on=enable_on, trigger_only_once=False, - enabled=self.enabled, - disable_on=self.disable_on, - enable_on=self.enable_on, + time_overshootable=time_overshootable, + name=name, + enabled=enabled, priority=3, + outputs=outputs, ) + self.prints = _ControllerPrints(self) @property - def enabled(self): - """Return the current enabled state mirrored from the wrapped event.""" - if hasattr(self, "event"): - return self.event.enabled - return self._enabled - - @enabled.setter - def enabled(self, value): - self._enabled = bool(value) - if hasattr(self, "event"): - self.event.enabled = self._enabled + def controller_function(self): + """The control logic, ``controller_function(context)``: the event's + callback.""" + return self.callback + + @controller_function.setter + def controller_function(self, function): + self.callback = _check_controller_function(function) + + def reset(self): + """Reset the controller for a new flight: what :class:`rocketpy.Event` + resets, and the ``observed_variables`` of a deprecated positional + controller function.""" + super().reset() + if isinstance(self.callback, _PositionalController): + self.callback.reset() def __str__(self): return f"Controller '{self.name}' with sampling rate {self.sampling_rate} Hz." - @property - def log(self): - """Return the controller callback log.""" - return self._log - - @log.setter - def log(self, value): - self._log = value - if hasattr(self, "event"): - self.event.callback_log = value - - @property - def return_log(self): - """Alias for :attr:`log`.""" - return self.log - - @return_log.setter - def return_log(self, value): - self.log = value - - def __build_controlled(self): - """Validate controlled_objects_name and build ``context.controlled``.""" - objects = self.controlled_objects - names = self.controlled_objects_name - many = isinstance(objects, (list, tuple)) - if names is None: - return Controlled(objects if many else (objects,)) - - if isinstance(names, str): - # A single name stands for whatever was passed, object or list. - names, objects = (names,), (objects,) - elif not isinstance(names, (list, tuple)): - raise TypeError( - "controlled_objects_name must be a string or list/tuple of strings" - ) - elif not many: - raise ValueError( - "controlled_objects_name is a list but controlled_objects is not " - "a list/tuple" - ) - - if not all(isinstance(name, str) for name in names): - raise TypeError( - "All entries in controlled_objects_name list must be strings" - ) - if len(set(names)) != len(names): - raise ValueError("controlled_objects_name entries must be unique") - if len(names) != len(objects): - raise ValueError( - "Length of controlled_objects_name must match number of " - "controlled_objects" - ) - for name in names: - if not name.isidentifier() or iskeyword(name) or name.startswith("_"): - raise ValueError( - f"controlled_objects_name entry '{name}' cannot be read as " - f"`context.controlled.{name}`. Use letters, digits and " - "underscores only, not starting with a digit or an " - "underscore, and not a Python keyword." - ) - return Controlled(objects, names) - def info(self): - """Prints out summarized information about the controller.""" + """Print what the controller is and what it does.""" self.prints.all() def all_info(self): - """Prints out all information about the controller.""" + """Print all the information about the controller.""" self.info() def to_dict(self, **kwargs): - """Serialize controller to dictionary. + """Return the controller as a dictionary, to be saved. Parameters ---------- **kwargs : dict - allow_pickle : bool, optional - If True, serialize controller_function, disable_on, and - enable_on callables using hex encoding. If False, use function - name. Default is True. + ``allow_pickle`` (default ``True``): save the controller function + and the gate functions themselves. With ``False`` only their names + are saved, and a loaded controller cannot run. Returns ------- dict - Serialized controller state. """ allow_pickle = kwargs.get("allow_pickle", True) - if allow_pickle: - controller_function = to_hex_encode(self.controller_function) - else: - controller_function = self.controller_function.__name__ - - # Serialize gate conditions: if callable, use hex encoding; if string or None, keep as-is - disable_on = self.disable_on - if allow_pickle and callable(disable_on): - disable_on = to_hex_encode(disable_on) - - enable_on = self.enable_on - if allow_pickle and callable(enable_on): - enable_on = to_hex_encode(enable_on) + def encode(function): + if not callable(function): + return function + if allow_pickle: + return to_hex_encode(function) + return getattr(function, "__name__", type(function).__name__) + disable_on, enable_on = self._gates return { - "controller_function": controller_function, + "controller_function": encode(self.controller_function), "sampling_rate": self.sampling_rate, + "memory": deepcopy(self._initial_memory), "name": self.name, - "controlled_objects_name": getattr(self, "controlled_objects_name", None), - # Hash(es) identifying the controlled object(s), so Rocket - # deserialization can reconnect the controller to the rocket's own - # reconstructed objects (see Rocket.from_dict). - "controlled_objects_hash": self._controlled_objects_hash(), - "memory": self.memory.copy(), - "enabled": self.enabled, - "disable_on": disable_on, - "enable_on": enable_on, - # Note: controlled_objects are recovered in from_dict via - # object reference matching in Rocket deserialization + "enabled": self._initial_enabled, + "disable_on": encode(disable_on), + "enable_on": encode(enable_on), + "outputs": self.output_defaults, + "time_overshootable": self.time_overshootable, } - def _controlled_objects_hash(self): - """Return the identity hash of the controlled object(s), matching the - shape of ``controlled_objects`` (a single hash for a single object, a - list of hashes for a list). These hashes match the ones the encoder - stores in each object's signature, letting Rocket deserialization find - the reconstructed objects. Returns ``None`` for anything unhashable.""" - - def safe_hash(obj): - try: - return hash(obj) - except TypeError: - return None - - controlled_objects = self.controlled_objects - if isinstance(controlled_objects, (list, tuple)): - return [safe_hash(obj) for obj in controlled_objects] - return safe_hash(controlled_objects) - @classmethod - def from_dict(cls, data, controlled_objects=None): - """Reconstruct controller from dictionary. + def from_dict(cls, data): + """Build a controller from a dictionary made by :meth:`to_dict`. + + A controller whose function cannot be loaded, such as one saved with + ``allow_pickle=False``, is loaded disabled, with a warning. Parameters ---------- data : dict - Serialized controller data from to_dict(). - controlled_objects : list or object, optional - Objects the controller will mutate. If not provided, - must be set manually after reconstruction. Returns ------- - _Controller - Reconstructed controller instance. + Controller """ - controller_function = data.get("controller_function") - sampling_rate = data.get("sampling_rate") name = data.get("name", "Controller") - controlled_objects_name = data.get("controlled_objects_name") - memory = data.get("memory", {}) + sampling_rate = data.get("sampling_rate") enabled = data.get("enabled", True) - disable_on = data.get("disable_on") - enable_on = data.get("enable_on") - - try: - controller_function = from_hex_decode(controller_function) - except (TypeError, ValueError): - pass - - # Deserialize disable_on: try hex decoding for callables, keep strings and None try: - disable_on = from_hex_decode(disable_on) - except (TypeError, ValueError): - # If not hex-encoded, keep as string or None - pass - - try: - enable_on = from_hex_decode(enable_on) - except (TypeError, ValueError): - pass - - if controlled_objects is None: - controlled_objects = [] - - controller = cls( - controller_function=controller_function, - controlled_objects=controlled_objects, + function = from_hex_decode(data["controller_function"]) + except _LOAD_ERRORS as error: + warnings.warn( + f"The function of the controller '{name}' could not be loaded " + f"({type(error).__name__}: {error}), so the controller is " + "loaded disabled. Build it again and add it to the rocket to " + "fly it.", + UserWarning, + ) + function, enabled = _missing_controller_function, False + # Saved before controllers took the context + function = _legacy_controller(function, sampling_rate) + gates = [] + for key in ("disable_on", "enable_on"): + gate = data.get(key) + # A preset name, a time or None is kept as saved + if isinstance(gate, str) and gate not in PRESETS: + try: + gate = from_hex_decode(gate) + except _LOAD_ERRORS as error: + warnings.warn( + f"The `{key}` function of the controller '{name}' could " + f"not be loaded ({type(error).__name__}: {error}), so " + "the controller is loaded disabled. Build it again and " + "add it to the rocket to fly it.", + UserWarning, + ) + gate, enabled = None, False + gates.append(gate) + return cls( + controller_function=function, sampling_rate=sampling_rate, + memory=data.get("memory"), name=name, - memory=memory, - controlled_objects_name=controlled_objects_name, enabled=enabled, - disable_on=disable_on, - enable_on=enable_on, + disable_on=gates[0], + enable_on=gates[1], + outputs=data.get("outputs") or None, + time_overshootable=data.get("time_overshootable", True), ) - # Stash the serialized controlled-object hash(es) so Rocket.from_dict - # can reconnect the controller to the rocket's reconstructed objects. - controller._serialized_controlled_objects_hash = data.get( - "controlled_objects_hash" - ) - return controller - - def rebind_controlled_objects(self, controlled_objects): - """Point the controller at reconstructed controlled object(s) and - rebuild ``context.controlled`` from them. - - Used when a rocket is loaded from a file: the controller is rebuilt - without its controlled objects (they are separate objects in the saved - data), so this reconnects it to the rocket's own objects, ensuring the - controller mutates them rather than orphaned copies. - - Parameters - ---------- - controlled_objects : object or list of object - The reconstructed object(s) the controller should control. - """ - self.controlled_objects = controlled_objects - self._controlled = self.__build_controlled() diff --git a/rocketpy/mathutils/function.py b/rocketpy/mathutils/function.py index 80ad3ca98..46396f392 100644 --- a/rocketpy/mathutils/function.py +++ b/rocketpy/mathutils/function.py @@ -7,7 +7,7 @@ import operator import warnings -from bisect import bisect_left +from bisect import bisect_left, bisect_right from collections.abc import Iterable from copy import deepcopy from enum import Enum @@ -37,6 +37,7 @@ "spline": 3, "shepard": 4, "rbf": 5, + "previous": 6, } EXTRAPOLATION_TYPES = {"zero": 0, "natural": 1, "constant": 2} @@ -99,8 +100,9 @@ def __init__( representation and graphing (axis names). Scalar is default. interpolation : string, optional Interpolation method to be used if source type is ndarray. - For 1-D functions, linear, polynomial, akima and spline are - supported. For N-D functions, linear, shepard and rbf are + For 1-D functions, linear, polynomial, akima, spline and previous + are supported. ``"previous"`` holds each value until the next + point, as a sampled signal does. For N-D functions, linear, shepard and rbf are supported. N-D data on a regular grid is interpolated on the grid, where linear, nearest, slinear, cubic, quintic and pchip are supported, unless shepard or rbf is asked for. @@ -343,8 +345,9 @@ def set_interpolation(self, method="spline"): ---------- method : string, optional Interpolation method to be used if source type is ndarray. - For 1-D functions, linear, polynomial, akima and spline are - supported. For N-D functions, linear, shepard and rbf are + For 1-D functions, linear, polynomial, akima, spline and previous + are supported. ``"previous"`` holds each value until the next + point, as a sampled signal does. For N-D functions, linear, shepard and rbf are supported. N-D data on a regular grid is interpolated on the grid, where linear, nearest, slinear, cubic, quintic and pchip are supported, unless shepard or rbf is asked for. @@ -528,6 +531,13 @@ def rbf_interpolation(x, x_min, x_max, x_data, y_data, coeffs): # pylint: disab self._interpolation_func = rbf_interpolation + case 6: # previous: hold the last value until the next point + + def previous_interpolation(x, x_min, x_max, x_data, y_data, coeffs): # pylint: disable=unused-argument + return y_data[bisect_right(x_data, x) - 1] + + self._interpolation_func = previous_interpolation + case _: raise ValueError( f"Interpolation {interpolation} method not recognized." @@ -637,6 +647,13 @@ def natural_extrapolation( # pylint: disable=function-redefined ): # pylint: disable=unused-argument return interpolator(x) + case 6: # previous: the edge value, as constant does + + def natural_extrapolation( # pylint: disable=function-redefined + x, x_min, x_max, x_data, y_data, coeffs + ): # pylint: disable=unused-argument + return y_data[0] if x < x_min else y_data[-1] + case _: raise ValueError( f"Natural extrapolation not defined for {interpolation}." @@ -888,8 +905,9 @@ def set_discrete( Number of samples to be taken from inside range. Default is 200. interpolation : string Interpolation method to be used if source type is ndarray. - For 1-D functions, linear, polynomial, akima and spline are - supported. For N-D functions, linear, shepard and rbf are + For 1-D functions, linear, polynomial, akima, spline and previous + are supported. ``"previous"`` holds each value until the next + point, as a sampled signal does. For N-D functions, linear, shepard and rbf are supported. N-D data on a regular grid is interpolated on the grid, where linear, nearest, slinear, cubic, quintic and pchip are supported, unless shepard or rbf is asked for. @@ -4003,7 +4021,8 @@ def __validate_outputs(self, outputs): def __validate_interpolation(self, interpolation): if self.__dom_dim__ == 1: - # possible interpolation values: linear, polynomial, akima and spline + # possible interpolation values: linear, polynomial, akima, spline + # and previous if interpolation is None: interpolation = "spline" elif interpolation.lower() not in [ @@ -4011,6 +4030,7 @@ def __validate_interpolation(self, interpolation): "linear", "polynomial", "akima", + "previous", ]: warnings.warn( "Interpolation method set to 'spline' because the " diff --git a/rocketpy/plots/aero_surface_plots.py b/rocketpy/plots/aero_surface_plots.py index de27c3ae0..821ffd119 100644 --- a/rocketpy/plots/aero_surface_plots.py +++ b/rocketpy/plots/aero_surface_plots.py @@ -143,7 +143,6 @@ def coefficients( if "mach" not in index: return machs = np.atleast_1d(np.asarray(mach, dtype=float)) - n_args = len(independent_vars) entries = [] for name, candidates in self._COEFFICIENT_SWEEP.items(): @@ -169,7 +168,7 @@ def coefficients( for curve_mach in curve_machs: values = np.empty_like(x) for i, value in enumerate(x): - args = [0.0] * n_args + args = surface._reference_arguments() # pylint: disable=protected-access args[index["mach"]] = machs[0] if curve_mach is None else curve_mach args[index[var]] = value values[i] = coeff(*args) @@ -1029,24 +1028,172 @@ def draw(self, *, filename=None): pass -class _AirBrakesPlots(_GenericSurfacePlots): - """Class that contains all air brakes plots.""" - - def drag_coefficient_curve(self): - """Plots the drag coefficient curve of the air_brakes.""" - if self.aero_surface.clamp is True: - return self.aero_surface.drag_coefficient.plot(0, 1) - else: - return self.aero_surface.drag_coefficient.plot() +class _ControlFinsPlots(_GenericSurfacePlots): + """Plots of a set of control fins: the fins' effectiveness, then the + generic coefficients.""" def draw(self, *, filename=None): - raise NotImplementedError + """Draw the fin the set is copied from, or its first fin.""" + self.aero_surface.fins[0].plots.draw(filename=filename) + + def effectiveness(self, *, mach=(0.05, 0.95), alpha=0.0, beta=0.0, filename=None): + """Plot the moment the fins produce per radian of each command of + :meth:`rocketpy.ControlFins.deflections`, against Mach: the roll + moment coefficient and, for a set that is on a rocket, the pitch and + yaw moment coefficients about the rocket's center of dry mass. + + Parameters + ---------- + mach : tuple of float, optional + ``(low, high)``: the Mach range plotted. Default ``(0.05, 0.95)``. + alpha, beta : float, optional + The angle of attack and the sideslip angle, in radians, the + effectiveness is taken at. Default 0. + filename : str | None, optional + Where to save the figure. ``None`` (the default) shows it. + """ + effectiveness = self.aero_surface.effectiveness(alpha=alpha, beta=beta) + machs = np.linspace(mach[0], mach[1], 100) + sideways = [command for command in ("pitch", "yaw") if command in effectiveness] + _, axes = plt.subplots(1, 2 if sideways else 1, figsize=(9, 4), squeeze=False) + roll_axis = axes[0][0] + roll_axis.plot(machs, [effectiveness["roll"](m) for m in machs]) + roll_axis.set_title("Roll moment per rad of the roll command") + roll_axis.set_xlabel("Mach Number") + roll_axis.set_ylabel("Roll Moment Coefficient per rad") + roll_axis.grid(True) + if sideways: + moment_axis = axes[0][1] + for command in sideways: + moment_axis.plot( + machs, [effectiveness[command](m) for m in machs], label=command + ) + moment_axis.set_title("Moment per rad of the pitch and yaw commands") + moment_axis.set_xlabel("Mach Number") + moment_axis.set_ylabel("Moment Coefficient per rad") + moment_axis.grid(True) + moment_axis.legend() + plt.suptitle(f"Effectiveness of {self.aero_surface.name}") + plt.tight_layout() + show_or_save_plot(filename) + + def hinge_moments(self, flight, *, filename=None): + """Plot the torque the air put on each fin about its hinge line over a + flight, in N m, one line per fin: the load the mechanism turning the + fin had to hold. Positive pushes the fin toward a larger deflection. + + The fin model's center of pressure is fixed while the real one moves + with speed and angle of attack, so with the hinge close to it trust + the size of the torque, not its sign. + + Parameters + ---------- + flight : Flight + A flight of a rocket carrying this set of fins. + filename : str | None, optional + Where to save the figure. ``None`` (the default) shows it. + """ + torques = self.aero_surface._hinge_moments_in(flight) + _, axis = plt.subplots(figsize=(9, 4)) + for control, torque in torques.items(): + axis.plot(torque.x_array, torque.y_array, label=control) + axis.set_title(f"Hinge moments of {self.aero_surface.name}") + axis.set_xlabel("Time (s)") + axis.set_ylabel("Hinge Moment (N m)") + axis.grid(True) + axis.legend() + plt.tight_layout() + show_or_save_plot(filename) def all(self): - """Plots all available air_brakes plots. + """Plots the first fin, the effectiveness and the coefficients.""" + self.draw() + self.effectiveness() + self.coefficients() - Returns - ------- - None + +class _AirBrakesPlots(_GenericSurfacePlots): + """Plots of air brakes: the drag coefficient curve, and the drag they made + in a flight.""" + + def _data_points(self): + """The ``(level, mach, cd)`` rows the curve was given as, or ``None`` + for a curve given as a number or a function.""" + source = self.aero_surface.drag_coefficient.source + if isinstance(source, np.ndarray) and source.ndim == 2 and source.shape[1] == 3: + return source + return None + + def drag_coefficient(self, *, levels=None, mach=None, filename=None): + """Plot the drag coefficient against Mach, one line per deployment + level. + + Parameters + ---------- + levels : sequence of float, optional + The deployment levels drawn. Default ``None``: the levels of the + curve's data points, or 0.25, 0.5, 0.75 and 1 for a curve given as + a number or a function. + mach : tuple of float, optional + ``(low, high)``: the Mach range drawn. Default ``None``: the range + of the curve's data points, or 0.05 to 0.95. + filename : str | None, optional + Where to save the figure. ``None`` (the default) shows it. + """ + points = self._data_points() + if levels is None: + levels = ( + [level for level in np.unique(points[:, 0]) if level > 0] + if points is not None + else (0.25, 0.5, 0.75, 1.0) + ) + if mach is None: + mach = ( + (points[:, 1].min(), points[:, 1].max()) + if points is not None + else (0.05, 0.95) + ) + machs = np.linspace(mach[0], mach[1], 100) + curve = self.aero_surface.drag_coefficient + _, axis = plt.subplots(figsize=(9, 4)) + for level in levels: + axis.plot(machs, [curve(level, m) for m in machs], label=f"level {level:g}") + axis.set_title(f"Drag coefficient of {self.aero_surface.name}") + axis.set_xlabel("Mach Number") + axis.set_ylabel("Drag Coefficient") + axis.grid(True) + axis.legend() + plt.tight_layout() + show_or_save_plot(filename) + + def drag_coefficient_curve(self): + """The same as :meth:`drag_coefficient`, kept for older scripts.""" + self.drag_coefficient() + + def drag(self, flight, *, filename=None): + """Plot the drag force the air brakes made over a flight, in N, next + to the rocket's total drag. + + Parameters + ---------- + flight : Flight + A flight of a rocket carrying these air brakes. + filename : str | None, optional + Where to save the figure. ``None`` (the default) shows it. """ - self.drag_coefficient_curve() + drag = self.aero_surface._drag_in(flight) + _, axis = plt.subplots(figsize=(9, 4)) + axis.plot(drag.x_array, drag.y_array, label=self.aero_surface.name) + total = flight.aerodynamic_drag + axis.plot(total.x_array, total.y_array, label="Whole rocket", alpha=0.6) + axis.set_title(f"Drag of {self.aero_surface.name}") + axis.set_xlabel("Time (s)") + axis.set_ylabel("Drag (N)") + axis.grid(True) + axis.legend() + plt.tight_layout() + show_or_save_plot(filename) + + def all(self): + """Plot the drag coefficient curve.""" + self.drag_coefficient() diff --git a/rocketpy/plots/flight_plots.py b/rocketpy/plots/flight_plots.py index 2a3deb741..5f5d21659 100644 --- a/rocketpy/plots/flight_plots.py +++ b/rocketpy/plots/flight_plots.py @@ -1,15 +1,17 @@ import warnings from functools import cached_property +from numbers import Real from pathlib import Path import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import MaxNLocator, MultipleLocator +from ..tools import snake_case_key from .plot_helpers import show_or_save_plot -class _FlightPlots: +class _FlightPlots: # pylint: disable=too-many-public-methods """Class that holds plot methods for Flight class. Attributes @@ -656,6 +658,153 @@ def attitude_data(self, *, filename=None): # pylint: disable=too-many-statement plt.subplots_adjust(hspace=0.5) show_or_save_plot(filename) + def controls(self, *, filename=None): + """Plot the control inputs over the flight: one plot per part of the + rocket that has controls, one line per control. Each value is drawn + held until it was written again. + + Parameters + ---------- + filename : str | None, optional + The path the plot should be saved to. By default None, in which case + the plot will be shown instead of saved. Supported file endings are: + eps, jpg, jpeg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff + and webp (these are the formats supported by matplotlib). + + Returns + ------- + None + """ + controls = self.flight.solution.controls + if not controls: + print("This flight has no controls.") + return + names = { + snake_case_key(owner.name): owner.name + for owner in self.flight._control_owners + } + _, axes = plt.subplots( + len(controls), 1, figsize=(9, 3 * len(controls)), squeeze=False + ) + for ax, (owner, histories) in zip(axes[:, 0], controls.items()): + for control, history in histories.items(): + ax.step(history[:, 0], history[:, 1], where="post", label=control) + part_name = names.get(owner, owner) + ax.set_title(part_name) + ax.set_xlabel("Time (s)") + ax.legend() + ax.grid(True) + plt.tight_layout() + show_or_save_plot(filename) + + def state_history(self, *, filename=None): + """Plot the states of the rocket's controllables over the flight: one + plot per controllable that has states, one line per state, such as + the integral of a continuous controller. + + Parameters + ---------- + filename : str | None, optional + The path the plot should be saved to. By default None, in which case + the plot will be shown instead of saved. Supported file endings are: + eps, jpg, jpeg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff + and webp (these are the formats supported by matplotlib). + + Returns + ------- + None + """ + history = self.flight.state_history + if not history: + print("No controllable of this flight has states.") + return + _, axes = plt.subplots( + len(history), 1, figsize=(9, 3 * len(history)), squeeze=False + ) + for ax, (name, states) in zip(axes[:, 0], history.items()): + for state, function in states.items(): + ax.plot(function.x_array, function.y_array, label=state) + ax.set_title(name) + ax.set_xlabel("Time (s)") + ax.legend() + ax.grid(True) + plt.tight_layout() + show_or_save_plot(filename) + + def records(self, *, filename=None): + """Plot what the events of the flight recorded with + ``context.record``, one plot per record, as the recorded points. + Only records whose values are all numbers are plotted; the others + are read in ``flight.records``. + + Parameters + ---------- + filename : str | None, optional + The path the plot should be saved to. By default None, in which case + the plot will be shown instead of saved. Supported file endings are: + eps, jpg, jpeg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff + and webp (these are the formats supported by matplotlib). + + Returns + ------- + None + """ + self._plot_points( + self.flight.records, + "No event of this flight recorded numbers to plot.", + filename, + ) + + def event_outputs(self, *, filename=None): + """Plot what the events of the flight wrote to their outputs, the + values they share through ``context.outputs``, one plot per output, + as the points written. Only outputs whose values are all numbers are + plotted; the others are read in ``flight.event_outputs``. + + Parameters + ---------- + filename : str | None, optional + The path the plot should be saved to. By default None, in which case + the plot will be shown instead of saved. Supported file endings are: + eps, jpg, jpeg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff + and webp (these are the formats supported by matplotlib). + + Returns + ------- + None + """ + self._plot_points( + self.flight.event_outputs, + "No event of this flight wrote numbers to its outputs.", + filename, + ) + + @staticmethod + def _plot_points(by_event, nothing_to_plot, filename): + """Plot each list of ``(time, value)`` points of ``by_event``, event + name to its lists by name, that holds only numbers: one plot per + list, each value held until the next.""" + series = {} + for name in by_event: + for series_name in by_event[name]: + points = by_event[name][series_name] + if all(isinstance(value, Real) for _, value in points): + series[f"{name}: {series_name}"] = points + if not series: + print(nothing_to_plot) + return + _, axes = plt.subplots( + len(series), 1, figsize=(9, 3 * len(series)), squeeze=False + ) + for ax, (name, points) in zip(axes[:, 0], series.items()): + times, values = zip(*points) + ax.step(times, values, where="post", marker=".") + ax.set_title(name) + ax.set_xlabel("Time (s)") + ax.grid(True) + plt.tight_layout() + show_or_save_plot(filename) + def flight_path_angle_data(self, *, filename=None): """Prints out Flight path and Rocket Attitude angle graphs available about the Flight @@ -1582,57 +1731,62 @@ def pressure_signals(self): """Deprecated. Pressure signal plots have been removed. Use a Sensor (e.g. a Barometer) with built-in noise and access its - recorded measurements via ``flight.sensor_data`` instead. + recorded measurements via ``flight.sensor_history`` instead. """ warnings.warn( "pressure_signals() is deprecated and will be removed in v1.16. " "Use a Barometer Sensor with built-in noise and access its data " - "via flight.sensor_data instead.", + "via flight.sensor_history instead.", DeprecationWarning, stacklevel=2, ) - def sensor_data(self, *, filename=None): - """Plots the measured data of every sensor attached to the flight. - - Delegates to each sensor's own ``plots`` object. A sensor added to the - rocket multiple times appears once in the output. + def sensors(self, *, filename=None): + """Plot what the sensors of the flight read: one plot per sensor, one + line per channel, each reading drawn held until the next one. A sensor + whose channels have different units, such as a GNSS receiver, gets one + plot per unit. Parameters ---------- filename : str | None, optional - The path the plots should be saved to. By default None, in which - case the plots will be shown instead of saved. When given, a - per-sensor suffix is appended to keep one file per sensor. - """ - if not self.flight.sensors: - print("No sensors were registered in this flight.") - return - - # A flight loaded from a file without being re-simulated has no recorded - # measurements, so fall back to an empty mapping instead of raising. - sensor_data = getattr(self.flight, "sensor_data", None) or {} + The path the plot should be saved to. By default None, in which case + the plot will be shown instead of saved. Supported file endings are: + eps, jpg, jpeg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff + and webp (these are the formats supported by matplotlib). - seen = [] - for sensor in self.flight.sensors: - if sensor in seen: # a multiply-added sensor is listed more than once - continue - seen.append(sensor) - measured_data = sensor_data.get(sensor) - if not measured_data: - print( - f"\n\n{sensor.name}: no data available (flight was not simulated)." - ) + Returns + ------- + None + """ + history = self.flight.sensor_history + groups = {} + for sensor, event in self.flight._sensors_by_key.values(): + name = event._position_name + if name not in history: continue - print(f"\n\n{sensor.name} Sensor Data\n") - if filename is None: - sensor.plots.all(data=measured_data) - else: - path = Path(filename) - sensor_filename = str( - path.with_name(f"{path.stem}_{sensor.name}{path.suffix}") - ) - sensor.plots.time_series(filename=sensor_filename, data=measured_data) + readings = history[name] + for label, unit in sensor.channels: + if label in readings: + groups.setdefault((name, unit), []).append( + (label, getattr(readings, label)) + ) + if not groups: + print("No sensor readings to plot.") + return + _, axes = plt.subplots( + len(groups), 1, figsize=(9, 3 * len(groups)), squeeze=False + ) + for ax, ((name, unit), channels) in zip(axes[:, 0], groups.items()): + for label, channel in channels: + ax.step(channel.x_array, channel.y_array, where="post", label=label) + ax.set_title(name) + ax.set_xlabel("Time (s)") + ax.set_ylabel(unit) + ax.legend() + ax.grid(True) + plt.tight_layout() + show_or_save_plot(filename) def altitude_data(self, *, filename=None): """Plots altitude AGL vs time with event markers. @@ -1964,5 +2118,21 @@ def all(self): # pylint: disable=too-many-statements self.fluid_mechanics_data() if self.flight.sensors: - print("\n\nSensor Data Plots\n") - self.sensor_data() + print("\n\nSensor Plots\n") + self.sensors() + + if self.flight.solution.control_names: + print("\n\nControl Inputs Plots\n") + self.controls() + + if self.flight.state_history: + print("\n\nControllable States Plots\n") + self.state_history() + + if self.flight.records: + print("\n\nRecords Plots\n") + self.records() + + if self.flight.event_outputs: + print("\n\nEvent Outputs Plots\n") + self.event_outputs() diff --git a/rocketpy/plots/rocket_plots.py b/rocketpy/plots/rocket_plots.py index e6c6c6380..7c9c2e63d 100644 --- a/rocketpy/plots/rocket_plots.py +++ b/rocketpy/plots/rocket_plots.py @@ -5,7 +5,7 @@ from rocketpy.mathutils.vector_matrix import Vector from rocketpy.motors import EmptyMotor, HybridMotor, LiquidMotor, SolidMotor -from rocketpy.rocket.aero_surface import Fin, Fins, NoseCone, Tail +from rocketpy.rocket.aero_surface import ControlFins, Fin, Fins, NoseCone, Tail from rocketpy.rocket.aero_surface.generic_surface import GenericSurface from .plot_helpers import show_or_save_fig, show_or_save_plot @@ -398,6 +398,9 @@ def _draw_aerodynamic_surfaces(self, ax, vis_args, plane, surfaces): ) elif isinstance(surface, Fin): self._draw_fin(ax, surface, position, drawn_surfaces, vis_args, plane) + elif isinstance(surface, ControlFins): + for fin in surface.fins: + self._draw_fin(ax, fin, position, drawn_surfaces, vis_args, plane) elif isinstance(surface, GenericSurface): self._draw_generic_surface( ax, surface, position, drawn_surfaces, vis_args, plane diff --git a/rocketpy/plots/sensors_plots.py b/rocketpy/plots/sensors_plots.py index 130d37e57..b69df55ee 100644 --- a/rocketpy/plots/sensors_plots.py +++ b/rocketpy/plots/sensors_plots.py @@ -17,26 +17,16 @@ class _SensorPlots(ABC): def __init__(self, sensor): self.sensor = sensor - def _iter_runs(self, data=None): - """Yield ``(run_index, run)`` for each recorded measurement run. + def _iter_runs(self): + """Yield ``(run_index, run)`` for each list of measurements. A sensor added a single time to the rocket stores a flat list of tuples; a sensor added multiple times stores one such list per - instance (a nested list). The single-add case yields ``run_index`` - ``None``; the multi-add case yields the instance index. Empty runs + position (a nested list). The single-add case yields ``run_index`` + ``None``; the multi-add case yields the position index. Empty runs are skipped. - - Parameters - ---------- - data : list, optional - Measured data to iterate over. When ``None`` (default) the - sensor's own ``measured_data`` buffer is used. Flight-scoped - callers should pass ``flight.sensor_data[sensor]`` so the plot - reflects that specific flight rather than the sensor's most - recent run. """ - if data is None: - data = self.sensor.measured_data + data = self.sensor.measured_data if not data: return if isinstance(data[0], list): # sensor added multiple times -> nested @@ -46,23 +36,21 @@ def _iter_runs(self, data=None): else: yield None, data - def time_series(self, *, filename=None, data=None): - """Plots each measured channel of the sensor against time. + def time_series(self, *, filename=None): + """Plots each measured channel of the sensor against time, each + measurement held until the next one. One subplot is created per channel. When the sensor was added to the - rocket multiple times, each instance run is overlaid with a legend. + rocket multiple times, each position is overlaid with a legend. To plot + what a sensor read in a given flight, use ``flight.plots.sensors()``. Parameters ---------- filename : str | None, optional The path the plot should be saved to. By default None, in which case the plot will be shown instead of saved. - data : list, optional - Measured data to plot. When ``None`` (default) the sensor's own - ``measured_data`` buffer is used. Flight-scoped callers should - pass ``flight.sensor_data[sensor]``. """ - runs = list(self._iter_runs(data)) + runs = list(self._iter_runs()) if not runs: print(f"No measured data recorded for sensor '{self.sensor.name}'.") return @@ -78,7 +66,7 @@ def time_series(self, *, filename=None, data=None): series_label = ( None if run_index is None else f"Instance {run_index + 1}" ) - ax.plot(arr[:, 0], arr[:, c + 1], label=series_label) + ax.step(arr[:, 0], arr[:, c + 1], where="post", label=series_label) ax.set_title(f"{self.sensor.name} - {label}") ax.set_xlabel("Time (s)") ax.set_ylabel(f"{label} ({unit})") @@ -88,17 +76,9 @@ def time_series(self, *, filename=None, data=None): plt.subplots_adjust(hspace=0.5) show_or_save_plot(filename) - def all(self, *, data=None): - """Plots all the measured data of the sensor. - - Parameters - ---------- - data : list, optional - Measured data to plot. When ``None`` (default) the sensor's own - ``measured_data`` buffer is used. Flight-scoped callers should - pass ``flight.sensor_data[sensor]``. - """ - self.time_series(data=data) + def all(self): + """Plots all the measured data of the sensor.""" + self.time_series() class _AccelerometerPlots(_SensorPlots): diff --git a/rocketpy/prints/aero_surface_prints.py b/rocketpy/prints/aero_surface_prints.py index 478005070..9dedd9313 100644 --- a/rocketpy/prints/aero_surface_prints.py +++ b/rocketpy/prints/aero_surface_prints.py @@ -1,5 +1,7 @@ import numpy as np +from rocketpy.tools import snake_case_key + # TODO: this file could be separated into different, smaller files. class _GenericSurfacePrints: @@ -24,11 +26,10 @@ def coefficients(self): index = {name: i for i, name in enumerate(independent_vars)} if "mach" not in index: return - n_args = len(independent_vars) print("Aerodynamic coefficients (AoA 5°, sideslip 5°, Mach 0.3):") print("---------------------------------------------------------") - args = [0.0] * n_args + args = surface._reference_arguments() # pylint: disable=protected-access args[index["mach"]] = 0.3 if "alpha" in index: args[index["alpha"]] = np.deg2rad(5) @@ -396,10 +397,119 @@ def geometry(self): class _AirBrakesPrints(_GenericSurfacePrints): - """Class that contains all air_brakes prints. Not yet implemented.""" + """Prints of air brakes: their settings and their drag coefficient.""" def geometry(self): - pass + """Print the air brakes' settings: control input, reference area, + limits, starting level and whether the curve replaces the rocket's + drag.""" + brakes = self.aero_surface + print("Air brakes:") + print("-----------") + control = f"{snake_case_key(brakes.name)}.deployment_level" + print(f"Control input: {control} (0 retracted, 1 fully open)") + print(f"Reference area: {brakes.reference_area:.4g} m^2") + print(f"Starts each flight at: {brakes.initial_deployment_level:.4g}") + print(f"Deployment level kept between 0 and 1: {brakes.clamp}") + drag = ( + "the drag of the whole rocket at each deployment level" + if brakes.override_rocket_drag + else "added to the rocket's drag" + ) + print(f"Drag coefficient curve: {drag}") + print(f"Active: {brakes.active_during}, starts switched on: {brakes.active}\n") + + def drag_coefficient(self, levels=(0.25, 0.5, 0.75, 1.0), machs=(0.3, 0.5, 0.7)): + """Print the drag coefficient at a few deployment levels and Mach + numbers, as a table. + + Parameters + ---------- + levels : sequence of float, optional + The deployment levels of the rows. Default 0.25, 0.5, 0.75, 1. + machs : sequence of float, optional + The Mach numbers of the columns. Default 0.3, 0.5, 0.7. + """ + curve = self.aero_surface.drag_coefficient + print("Drag coefficient by deployment level (rows) and Mach (columns):") + print("----------------------------------------------------------------") + print(f"{'Level':>6s} " + " ".join(f"M {mach:<6.2f}" for mach in machs)) + for level in levels: + values = " ".join(f"{curve(level, mach):8.4f}" for mach in machs) + print(f"{level:6.2f} {values}") + print() + + def all(self): + """Print the identity, the settings and the drag coefficient table.""" + self.identity() + self.geometry() + self.drag_coefficient() + + +class _ControlFinsPrints(_GenericSurfacePrints): + """Prints of a set of control fins: which fin is which, then the generic + report.""" + + def fins(self): + """Print each fin's control input, angular position and default + deflection, so a controller knows which fin it turns.""" + surface = self.aero_surface + print("Fins of the set:") + print("----------------") + limits = surface.deflection_limits + if limits is None: + print("Deflection limits: none") + else: + print(f"Deflection limits: {limits[0]:.4g} to {limits[1]:.4g} rad") + print( + f"Hinge line: at {100 * surface.hinge_position:.4g}% of the root chord " + "from the leading edge" + ) + print(f"{'Control':<10s} {'Angular position':>16s} {'Default':>12s}") + for control, angle in zip(surface.controls, surface.angular_positions): + default = surface.control_defaults[control] + print(f"{control:<10s} {angle:>12.2f} deg {default:>8.4g} rad") + print( + "A positive deflection turns a fin the way a positive cant angle does: " + "the same\ndeflection on every fin gives a negative roll moment. " + "The commands of\ndeflections() take care of the signs.\n" + ) + + def effectiveness(self, mach=0.3): + """Print what the fins do per radian of each command of + :meth:`rocketpy.ControlFins.deflections`, at one Mach number.""" + effectiveness = self.aero_surface.effectiveness() + print(f"Effectiveness at Mach {mach:g}, zero angle of attack:") + print("--------------------------------------------") + print( + "Roll moment coefficient per rad of the roll command: " + f"{effectiveness['roll'](mach):+.4f}" + ) + if "pitch" not in effectiveness: + print( + "Pitch and yaw: add the set to a rocket to see them, they depend " + "on where it sits.\n" + ) + return + print( + "Pitch moment coefficient per rad of the pitch command: " + f"{effectiveness['pitch'](mach):+.4f}" + ) + print( + "Yaw moment coefficient per rad of the yaw command: " + f"{effectiveness['yaw'](mach):+.4f}" + ) + print("Pitch and yaw moments are about the rocket's center of dry mass.\n") def all(self): - pass + """Prints all information of the set of control fins. + + Returns + ------- + None + """ + self.identity() + self.fins() + self.effectiveness() + self.geometry() + self.coefficients() diff --git a/rocketpy/prints/controller_prints.py b/rocketpy/prints/controller_prints.py index 1d5c67d83..e40793e34 100644 --- a/rocketpy/prints/controller_prints.py +++ b/rocketpy/prints/controller_prints.py @@ -1,4 +1,63 @@ -from inspect import getsourcelines +def print_controls(controllable): + """Print each control of a controllable with the value it starts every + flight at and its limits, and the controllable's own states.""" + for control in controllable.controls: + limits = controllable.control_limits.get(control) + limits = "no limits" if limits is None else f"from {limits[0]} to {limits[1]}" + print( + f"\tControl {control}: starts at " + f"{controllable.control_defaults[control]}, {limits}" + ) + if controllable.states: + print(f"\tStates: {', '.join(controllable.states)}") + + +class _ControllablePrints: + """Class that holds prints methods for a part with controls or states of + its own that is not an aerodynamic surface: a continuous controller, a + thrust effector or a force effector. + + Attributes + ---------- + _ControllablePrints.controllable : Controllable + The part the prints are of. + """ + + # The functions a part can be built from, by the attribute that holds them + _FUNCTIONS = ( + ("Control law", "law_function"), + ("State derivative", "derivative_function"), + ("Thrust function", "thrust_function"), + ("Force function", "force_function"), + ) + + def __init__(self, controllable): + self.controllable = controllable + + def functions(self): + """Print the functions the part was built from.""" + for label, attribute in self._FUNCTIONS: + function = getattr(self.controllable, attribute, None) + if function is not None: + name = getattr(function, "__name__", type(function).__name__) + print(f"\t{label}: {name}") + + def controls(self): + """Print the part's controls, with where each starts a flight and its + limits, and the part's own states.""" + print_controls(self.controllable) + + def all(self): + """Print all the information about the part. + + Returns + ------- + None + """ + part = self.controllable + print(f"\n{type(part).__name__}: {part.name}\n") + self.functions() + self.controls() class _ControllerPrints: @@ -6,14 +65,11 @@ class _ControllerPrints: Attributes ---------- - _ControllerPrint.controller : controller + _ControllerPrints.controller : Controller Controller object that will be used for the prints. """ - def __init__( - self, - controller, - ): + def __init__(self, controller): """Initializes _ControllerPrints class Parameters @@ -28,44 +84,42 @@ def __init__( self.controller = controller def controller_function(self): - """Prints the controller function information. + """Print the controller function and how often it runs.""" + function = self.controller.controller_function + name = getattr(function, "__name__", type(function).__name__) + print(f"Controller function: {name}") + print(f"Sampling rate: {self.controller.sampling_rate:.3f} Hz") - Returns - ------- - None - """ - if self.controller.controller_function.__name__ == "": - line = getsourcelines(self.controller.controller_function)[0][0] - print("Controller function: " + line.split("=")[0].strip()) - else: - print( - "Controller function: " + self.controller.controller_function.__name__ - ) - if self.controller.sampling_rate is None: - print("Controller refresh rate: continuous") - else: - print(f"Controller refresh rate: {self.controller.sampling_rate:.3f} Hz") - - def interactive_objects(self): - """Prints interactive objects.""" - print("interactive Objects") - # check if is list - if isinstance(self.controller.interactive_objects, list): - for obj in self.controller.interactive_objects: - print(getattr(obj, "name", str(obj))) - else: - obj = self.controller.interactive_objects - print(getattr(obj, "name", str(obj))) + def gates(self): + """Print when the controller runs.""" + disable_on, enable_on = self.controller._gates + print(f"Enabled at the start: {self.controller._initial_enabled}") + if disable_on is not None: + print(f"Disabled on: {getattr(disable_on, '__name__', disable_on)}") + if enable_on is not None: + print(f"Enabled on: {getattr(enable_on, '__name__', enable_on)}") + + def memory_and_records(self): + """Print the outputs, the names kept in memory and the names + recorded.""" + if self.controller.outputs: + print(f"Outputs: {', '.join(self.controller.outputs)}") + memory = self.controller._initial_memory + if memory: + print(f"Memory keys: {', '.join(str(key) for key in memory)}") + records = self.controller._records + if records: + print(f"Records of the last flight: {', '.join(records)}") def all(self): - """Prints all information about the parachute. + """Print all the information about the controller. Returns ------- None """ - print("\nController Details\n") print(self.controller) self.controller_function() - self.interactive_objects() + self.gates() + self.memory_and_records() diff --git a/rocketpy/prints/flight_prints.py b/rocketpy/prints/flight_prints.py index 530cbe1f6..776489cce 100644 --- a/rocketpy/prints/flight_prints.py +++ b/rocketpy/prints/flight_prints.py @@ -254,7 +254,10 @@ def events_registered(self): ) def sensors(self): - """Prints details about sensors registered in the flight. + """Prints the sensors of the flight: the name its readings go by in + ``flight.sensor_history`` (as given, and in snake_case), its type, + sampling rate and number of readings, then the smallest, largest and + final reading of each channel. Returns ------- @@ -262,27 +265,34 @@ def sensors(self): """ print("\nSensors\n") - if len(self.flight.sensors) == 0: + entries = self.flight._sensors_by_key + if not entries: print("No sensors were registered.") return - # A flight loaded from a file without being re-simulated has no recorded - # measurements, so fall back to an empty mapping instead of raising. - sensor_data = getattr(self.flight, "sensor_data", None) or {} - - for sensor in self.flight.sensors: - sensor_name = sensor.name if sensor.name else "Unnamed Sensor" - print(f"Sensor: {sensor_name}") + history = self.flight.sensor_history + series = {} + for key, (sensor, event) in entries.items(): + name = event._position_name + readings = history[name] if name in history else {} + for channel in readings: + series[f"{name}.{channel}"] = getattr(readings, channel).y_array + first = series.get(f"{name}.{sensor.channels[0][0]}") + print(f"Sensor: {name} ({key})") print(f"\tType: {sensor.__class__.__name__}") print(f"\tSampling Rate: {sensor.sampling_rate:.3f} Hz") - measured_data = sensor_data.get(sensor) - if not measured_data: - print("\tNo measurement data available (flight was not simulated).") - print() - continue - print(f"\tMeasurements Recorded: {len(measured_data)}") - sensor.prints.data_summary(data=measured_data) - print() + print(f"\tReadings: {0 if first is None else len(first)}") + print() + if not series: + print("No readings were recorded.") + return + width = max(len(name) for name in series) + print(f"{'Reading':{width}s} {'Min':>10s} {'Max':>10s} {'Final':>10s}") + for name, values in series.items(): + print( + f"{name:{width}s} {min(values):10.4g} " + f"{max(values):10.4g} {values[-1]:10.4g}" + ) def sensor_events(self): """Prints details about sensor-generated events in the flight. @@ -298,17 +308,11 @@ def sensor_events(self): print("No sensor events were registered.") return - for event in sensor_events: + for sensor, event in sensor_events: event_name = event.name if event.name else "Unnamed Sensor Event" print(f"Sensor Event: {event_name}") print(f"\tEnabled at end of simulation: {event.enabled}") - parent_sensor = ( - event.memory.get("sensor") if isinstance(event.memory, dict) else None - ) - parent_name = ( - parent_sensor.name if parent_sensor is not None else event_name - ) - print(f"\tParent Sensor: {parent_name}") + print(f"\tParent Sensor: {sensor.name}") if event.sampling_rate is None: print("\tSampling: Continuous") @@ -328,11 +332,6 @@ def sensor_events(self): print(f"\tFirst Trigger Time: {event.triggered_times[0]:.3f} s") print(f"\tLast Trigger Time: {event.triggered_times[-1]:.3f} s") - if len(event.callback_log) > 0: - print(f"\tCallback Log Entries: {len(event.callback_log)}") - - if isinstance(event.memory, dict): - print(f"\tMemory Keys: {list(event.memory.keys())}") print() def custom_events(self): @@ -375,15 +374,15 @@ def custom_events(self): print(f"\tFirst Trigger Time: {event.triggered_times[0]:.3f} s") print(f"\tLast Trigger Time: {event.triggered_times[-1]:.3f} s") - if len(event.callback_log) > 0: - print(f"\tCallback Log Entries: {len(event.callback_log)}") + if event._records: # pylint: disable=protected-access + print(f"\tRecords: {', '.join(event._records)}") if isinstance(event.memory, dict): print(f"\tMemory Keys: {list(event.memory.keys())}") print() def controllers(self): - """Prints details about controllers registered in the flight. + """Prints details about the controllers that flew with the rocket. Returns ------- @@ -391,48 +390,33 @@ def controllers(self): """ print("\nControllers\n") - if len(self.flight._controllers) == 0: + continuous = self.flight.rocket.continuous_controllers + if len(self.flight.controllers) == 0 and not continuous: print("No controllers were registered.") return - for controller in self.flight._controllers: + for controller in self.flight.controllers: print(f"Controller: {controller.name}") print(f"\tSampling Rate: {controller.sampling_rate:.3f} Hz") print(f"\tEnabled at end of simulation: {controller.enabled}") - print(f"\tController Log Entries: {len(controller.log)}") + print(f"\tRun Count: {len(controller.triggered_times)}") + if controller.triggered_times: + print(f"\tFirst Run Time: {controller.triggered_times[0]:.3f} s") + print(f"\tLast Run Time: {controller.triggered_times[-1]:.3f} s") + records = list(controller._records) + if records: + print(f"\tRecords: {', '.join(records)}") + if controller.outputs: + print(f"\tOutputs: {', '.join(controller.outputs)}") print() - def controller_events(self): - """Prints details about events generated by controllers. - - Returns - ------- - None - """ - print("\nController Events\n") - - if len(self.flight._controllers) == 0: - print("No controller events were registered.") - return - - for controller in self.flight._controllers: - event = controller.event - event_name = event.name if event.name else "Unnamed Controller Event" - - print(f"Controller Event: {event_name}") - print(f"\tParent Controller: {controller.name}") - - if event.sampling_rate is None: - print("\tSampling: Continuous") - else: - print(f"\tSampling Rate: {event.sampling_rate:.3f} Hz") - - print(f"\tTriggered Count: {len(event.triggered_times)}") - if len(event.triggered_times) > 0: - print(f"\tFirst Activation Time: {event.triggered_times[0]:.3f} s") - print(f"\tLast Activation Time: {event.triggered_times[-1]:.3f} s") - - print(f"\tCallback Log Entries: {len(event.callback_log)}") + states = self.flight.state_history + for controller in continuous: + print(f"Continuous Controller: {controller.name}") + print("\tRuns with the equations of motion, at every instant") + for state in controller.states: + final = states[controller.name][state].y_array[-1] + print(f"\tState {state}: {final:.4g} at the end of the flight") print() def impact_conditions(self): @@ -713,6 +697,32 @@ def report(label, time): roll_rate = abs(flight.w3.get_value_opt(burn_out_time)) / two_pi print(f"Roll Rate at Burnout: {roll_rate:.2f} Hz") + def controls(self): + """Prints the smallest, largest and final value of each control input + over the flight. + + Returns + ------- + None + """ + controls = self.flight.controls + print("\nControl Inputs\n") + if not controls: + print("This flight has no controls.") + return + series = { + f"{name}.{control}": getattr(controls[name], control).y_array + for name in controls + for control in controls[name] + } + width = max(len(name) for name in series) + print(f"{'Control':{width}s} {'Min':>10s} {'Max':>10s} {'Final':>10s}") + for name, values in series.items(): + print( + f"{name:{width}s} {min(values):10.4g} " + f"{max(values):10.4g} {values[-1]:10.4g}" + ) + def all(self): """Prints out all data available about the Flight. This method invokes all other print methods in the class. @@ -759,13 +769,10 @@ def all(self): self.rail_button_bending_moments() print() - if self.flight._controllers: + if self.flight.controllers or self.flight.rocket.continuous_controllers: self.controllers() print() - self.controller_events() - print() - if self.flight.sensors: self.sensors() print() @@ -778,5 +785,9 @@ def all(self): self.custom_events() print() + if self.flight.solution.control_names: + self.controls() + print() + self.numerical_integration_settings() print() diff --git a/rocketpy/prints/rocket_prints.py b/rocketpy/prints/rocket_prints.py index 991e75952..f3d4d6c3e 100644 --- a/rocketpy/prints/rocket_prints.py +++ b/rocketpy/prints/rocket_prints.py @@ -1,3 +1,7 @@ +from ..tools import snake_case_key +from .controller_prints import print_controls + + class _RocketPrints: """Class that holds prints methods for Rocket class. @@ -189,6 +193,40 @@ def parachute_data(self): for chute in self.rocket.parachutes: chute.all_info() + def controls(self): + """Print what controls the rocket: its controllers, the parts they + can move with each control input, and its effectors. + + Returns + ------- + None + """ + rocket = self.rocket + print("\nControls\n") + for controller in rocket.controllers: + print(controller) + for controller in rocket.continuous_controllers: + print(f"Continuous controller '{controller.name}'.") + print_controls(controller) + for controllable in rocket.controllables: + print( + f"{type(controllable).__name__} '{controllable.name}', written " + f"as context.controls.{snake_case_key(controllable.name)}." + ) + print_controls(controllable) + for effector in rocket.effectors.get_components(): + point = rocket._effector_points.get(effector) + if effector in rocket._thrust_effectors: + where = "acting on the motor's thrust" + elif point is None: + where = "acting at the center of dry mass" + else: + where = ( + f"at ({point.x:.3f}, {point.y:.3f}, {point.z:.3f}) m from " + "the center of dry mass, in the body frame" + ) + print(f"{type(effector).__name__} '{effector.name}', {where}") + def all(self): """Prints all print methods about the Environment. @@ -200,3 +238,11 @@ def all(self): self.rocket_geometrical_parameters() self.rocket_aerodynamics_quantities() self.parachute_data() + rocket = self.rocket + if ( + rocket.controllers + or rocket.continuous_controllers + or rocket.controllables + or rocket.effectors.get_components() + ): + self.controls() diff --git a/rocketpy/prints/sensors_prints.py b/rocketpy/prints/sensors_prints.py index dd7924fb5..4e65651df 100644 --- a/rocketpy/prints/sensors_prints.py +++ b/rocketpy/prints/sensors_prints.py @@ -1,7 +1,5 @@ from abc import ABC -import numpy as np - class _SensorPrints(ABC): def __init__(self, sensor): @@ -68,45 +66,6 @@ def all(self): self.quantization() self.noise() - def data_summary(self, data=None): - """Prints a per-channel summary (min, max, mean) of the measured data. - - Handles sensors added to the rocket a single time (a flat list of - measurements) and multiple times (one measurement run per instance). - - Parameters - ---------- - data : list, optional - Measured data to summarize. When ``None`` (default) the sensor's - own ``measured_data`` buffer is used. Flight-scoped callers should - pass ``flight.sensor_data[sensor]`` so the summary reflects that - specific flight rather than the sensor's most recent run. - """ - if data is None: - data = self.sensor.measured_data - if not data: - print("\tNo measured data recorded.") - return - - runs = data if isinstance(data[0], list) else [data] - channels = self.sensor.channels - print("\tMeasured Data Summary:") - for run_index, run in enumerate(runs): - if not run: - continue - if len(runs) > 1: - print(f"\t Instance {run_index + 1}:") - indent = "\t " - else: - indent = "\t " - array = np.array(run, dtype=float) - for column, (label, unit) in enumerate(channels): - values = array[:, column + 1] - print( - f"{indent}{label}: min={values.min():.4g}, " - f"max={values.max():.4g}, mean={values.mean():.4g} ({unit})" - ) - class _InertialSensorPrints(_SensorPrints): def orientation(self): diff --git a/rocketpy/rocket/__init__.py b/rocketpy/rocket/__init__.py index 61c03a03d..6c001dc34 100644 --- a/rocketpy/rocket/__init__.py +++ b/rocketpy/rocket/__init__.py @@ -1,8 +1,8 @@ -from rocketpy.control.controller import _Controller +from rocketpy.control.controller import Controller from rocketpy.rocket.aero_surface import ( AeroSurface, AirBrakes, - ControllableGenericSurface, + ControlFins, EllipticalFin, EllipticalFins, Fin, diff --git a/rocketpy/rocket/_helpers.py b/rocketpy/rocket/_helpers.py index 115288901..9cb0c7b2e 100644 --- a/rocketpy/rocket/_helpers.py +++ b/rocketpy/rocket/_helpers.py @@ -226,7 +226,7 @@ def slopes(coefficient, surface, angle_index, mach): """Change of a coefficient per radian between neighboring angles.""" if not _varies_with(coefficient, ("alpha", "beta")[angle_index]): return np.zeros(intervals) - args = [0.0] * len(surface.independent_vars) + args = surface._reference_arguments() args[2] = mach values = [] for angle in _PROBE_ANGLES: @@ -269,7 +269,7 @@ def slopes(coefficient, surface, angle_index, mach): getattr(surface, moment), surface, angle_index, mach ) else: - args = [0.0] * len(surface.independent_vars) + args = surface._reference_arguments() args[2] = mach forces = getattr(surface, force_slope)(*args) moments = getattr(surface, moment_slope)(*args) @@ -1134,7 +1134,7 @@ def _control_axes(rocket, controls): """ owners = {} for surface, _ in rocket.aerodynamic_surfaces: - for control in getattr(surface, "control_variables", ()): + for control in getattr(surface, "controls", ()): owners.setdefault(control, []).append(surface) def slug(text): @@ -1250,9 +1250,11 @@ def condition(index): reynolds_at = fixed_reynolds if sweeps_reynolds: reynolds_at = reynolds[others.pop(0)] + # Outside a flight a surface is evaluated at its control defaults, so + # the sweep moves those, and puts them back below for (_, targets, values), i in zip(control_axes, others): for surface, control in targets: - surface.set_control(control, values[i]) + surface.control_defaults[control] = float(values[i]) return machs[mach_index], reynolds_at # Make sure each surface's center-of-pressure offset is current. @@ -1298,9 +1300,9 @@ def package(values, rate_values): ) return packaged - # The sweep moves the controls of the rocket's surfaces; put them back + # The sweep moves the control of the rocket's surfaces, reset to default moved = { - (surface, control): surface.control_state[control] + (surface, control): surface.control_defaults[control] for _, targets, _ in control_axes for surface, control in targets } @@ -1323,7 +1325,7 @@ def package(values, rate_values): result[phase] = package(values, rate_values) finally: for (surface, control), value in moved.items(): - surface.control_state[control] = value + surface.control_defaults[control] = value return result diff --git a/rocketpy/rocket/aero_surface/__init__.py b/rocketpy/rocket/aero_surface/__init__.py index 7a6e7ac2d..9864c1f5c 100644 --- a/rocketpy/rocket/aero_surface/__init__.py +++ b/rocketpy/rocket/aero_surface/__init__.py @@ -1,9 +1,7 @@ from rocketpy.rocket.aero_surface.aero_surface import AeroSurface from rocketpy.rocket.aero_surface.air_brakes import AirBrakes -from rocketpy.rocket.aero_surface.controllable_generic_surface import ( - ControllableGenericSurface, -) from rocketpy.rocket.aero_surface.fins import ( + ControlFins, EllipticalFin, EllipticalFins, Fin, diff --git a/rocketpy/rocket/aero_surface/_barrowman_surface.py b/rocketpy/rocket/aero_surface/_barrowman_surface.py index c614fc384..e645e5a78 100644 --- a/rocketpy/rocket/aero_surface/_barrowman_surface.py +++ b/rocketpy/rocket/aero_surface/_barrowman_surface.py @@ -187,8 +187,9 @@ def compute_forces_and_moments( # pylint: disable=unused-argument component (``omega[2]``) is used, by fin sets. *args Extra positional arguments accepted for signature compatibility with - the generic surface (``density``, ``dynamic_viscosity``, ``z``); - unused by the Barrowman model. + the generic surface (``density``, ``dynamic_viscosity``, ``z`` and + ``controls``); unused by the Barrowman model, whose only control is + ``active``. Returns ------- @@ -254,6 +255,6 @@ def _mach_coefficient(self, func_of_mach, name="coefficient"): return AeroCoefficient( func_of_mach, depends_on=("mach",), - control_variables=self.control_variables, + control_variables=self._control_axes, name=name, ) diff --git a/rocketpy/rocket/aero_surface/air_brakes.py b/rocketpy/rocket/aero_surface/air_brakes.py index 5d2386220..d6823b89c 100644 --- a/rocketpy/rocket/aero_surface/air_brakes.py +++ b/rocketpy/rocket/aero_surface/air_brakes.py @@ -2,201 +2,310 @@ import numpy as np +from rocketpy.control._helpers import limited_value from rocketpy.mathutils.function import Function from rocketpy.plots.aero_surface_plots import _AirBrakesPlots from rocketpy.prints.aero_surface_prints import _AirBrakesPrints -from .controllable_generic_surface import ControllableGenericSurface +from .generic_surface import GenericSurface -class AirBrakes(ControllableGenericSurface): - """AirBrakes class. Inherits from :class:`ControllableGenericSurface`, using - ``deployment_level`` as its single control variable and a multivariable drag - coefficient. +class AirBrakes(GenericSurface): + """Air brakes: flaps that open to add drag and slow the rocket down, + usually to hit a target apogee. + + The air brakes have one control, ``deployment_level``, from 0 (retracted) + to 1 (fully open), and a drag coefficient that depends on it and on the + Mach number. In a flight the deployment level is a control input named + after the air brakes, ``air_brakes.deployment_level`` for the default + name, which a controller writes as + ``context.controls.air_brakes.deployment_level``. The air brakes object + itself is not changed by a flight: :attr:`initial_deployment_level` is + where every flight starts, and ``flight.controls`` holds what was + flown. + + The drag acts along the rocket's axis, backward, at the point the air + brakes are added at. Retracted air brakes make no force at all: the + rocket then flies with its own drag curves. The + model has no sideways force or moment of its own: a deployed flap at an + angle of attack is treated as pure drag. Attributes ---------- AirBrakes.drag_coefficient : Function - Drag coefficient as a function of deployment level and Mach number. - AirBrakes.drag_coefficient_curve : int, float, callable, array, string, Function - Curve that defines the drag coefficient as a function of deployment level - and Mach number. Used as the source of `AirBrakes.drag_coefficient`. - It is stored as the surface's axial force coefficient ``cA``, read at - the current deployment level in flight; the wind-frame ``cD`` is a view - derived from it. - AirBrakes.deployment_level : float - Current deployment level, ranging from 0 to 1. Deployment level is the - fraction of the total airbrake area that is deployed. - AirBrakes.reference_area : int, float - Reference area used to calculate the drag force of the air brakes - from the drag coefficient curve. Units of m^2. - AirBrakes.clamp : bool, optional - If True, the simulation will clamp the deployment level to 0 or 1 if - the deployment level is out of bounds. If False, the simulation will - not clamp the deployment level and will instead raise a warning if - the deployment level is out of bounds. Default is True. + The drag coefficient as a function of the deployment level and the + Mach number, in that order, as given. + AirBrakes.drag_coefficient_curve : int, float, callable, array, str, Function + The curve as given, the source of :attr:`drag_coefficient`. + AirBrakes.initial_deployment_level : float + The deployment level every flight starts at, from 0 to 1. + AirBrakes.reference_area : float + The area the drag coefficient is multiplied by, in m². + AirBrakes.override_rocket_drag : bool + Whether the curve is the drag of the whole rocket at each deployment + level, and not of the air brakes alone. + AirBrakes.clamp : bool + Whether the deployment level is kept between 0 and 1. AirBrakes.name : str - Name of the air brakes. + The name of the air brakes, which also names their control input. """ - def __init__( + def __init__( # pylint: disable=too-many-arguments self, drag_coefficient_curve, reference_area, clamp=True, override_rocket_drag=False, - deployment_level=0, + initial_deployment_level=0, name="AirBrakes", + active_during="always", + active=True, + deployment_level=None, ): - """Initializes the AirBrakes class. + """Build the air brakes. Parameters ---------- - drag_coefficient_curve : int, float, callable, array, string, Function - This parameter represents the drag coefficient associated with the - air brakes and/or the entire rocket, depending on the value of - ``override_rocket_drag``. - - - If a constant, it should be an integer or a float representing a - fixed drag coefficient value. - - If a function, it must take two parameters: deployment level and - Mach number, and return the drag coefficient. This function allows - for dynamic computation based on deployment and Mach number. - - If an array, it should be a 2D array with three columns: the first - column for deployment level, the second for Mach number, and the - third for the corresponding drag coefficient. - - If a string, it should be the path to a .csv or .txt file. The - file must contain three columns: the first for deployment level, - the second for Mach number, and the third for the drag - coefficient. - - If a Function, it must take two parameters: deployment level and - Mach number, and return the drag coefficient. - - .. note:: For ``override_rocket_drag = False``, at - deployment level 0, the drag coefficient is assumed to be 0, - independent of the input drag coefficient curve. This means that - the simulation always considers that at a deployment level of 0, - the air brakes are completely retracted and do not contribute to - the drag of the rocket. - - reference_area : int, float - Reference area used to calculate the drag force of the air brakes - from the drag coefficient curve. Units of m^2. + drag_coefficient_curve : int, float, callable, array, str, Function + The drag coefficient as a function of the deployment level (0 to + 1) and the Mach number, in that order. A number is a constant + coefficient at every level above 0. A function is called as + ``curve(deployment_level, mach)``. An array has three columns, + deployment level, Mach number and drag coefficient, one row per + point; a string is the path to a ``.csv`` or ``.txt`` file with + the same three columns. Points are interpolated linearly. The + coefficient is of the air brakes alone, unless + ``override_rocket_drag`` is ``True``. Whatever the curve says, + retracted air brakes (deployment level 0) add no drag. + reference_area : float + The area the drag coefficient is multiplied by to get the drag + force, in m²: the one the curve was made with, usually the + rocket's cross section or the flaps' area. clamp : bool, optional - If True, the simulation will clamp the deployment level to 0 or 1 if - the deployment level is out of bounds. If False, the simulation will - not clamp the deployment level and will instead raise a warning if - the deployment level is out of bounds. Default is True. + Whether the deployment level is kept between 0 (retracted) and 1 + (fully open): ``True`` (the default) moves a value outside that + range to the nearest end, ``False`` puts no limit on it and the + drag curve is extrapolated. override_rocket_drag : bool, optional - If False, the air brakes drag coefficient will be added to the - rocket's power off drag coefficient curve. If True, during the - simulation, the rocket's power off drag will be ignored and the air - brakes drag coefficient will be used for the entire rocket instead. - Default is False. - deployment_level : float, optional - Initial deployment level, ranging from 0 to 1. Deployment level is - the fraction of the total airbrake area that is deployed. Default - is 0. + What the curve is the drag coefficient of. + + - ``False`` (the default): the air brakes alone. Their drag is + added to the rocket's. + - ``True``: the whole rocket at each deployment level, as measured + in a wind tunnel or computed for the complete rocket. The air + brakes then add the difference between the curve and its value + at deployment level 0, at the same Mach number, to the rocket's + own drag. The curve is of the rocket with its motor off: while + the motor burns, the same difference is added to the rocket's + ``power_on_drag``. The curve must include deployment level 0, and + the rocket's ``power_off_drag`` should be that retracted drag: the + total drag is then the curve. If they differ, the rocket's drag curves + are the drag with the air brakes retracted and the curve only + gives what opening them adds; a warning is shown when the air + brakes are added to a rocket and the two differ by more than + 5%. A constant curve adds nothing. + initial_deployment_level : float, optional + The deployment level every flight starts at, from 0 (retracted) + to 1 (fully open), the fraction of the flaps' travel. Default 0. name : str, optional - Name of the air brakes. Default is "AirBrakes". + The name of the air brakes. It also names their control input, in + snake_case: the default ``"AirBrakes"`` gives + ``air_brakes.deployment_level``. Two air brakes on one rocket need + different names. + active_during : str, optional + The motor phase the air brakes make force in: ``"always"`` (the + default), ``"power_on"`` or ``"power_off"``. + active : bool, optional + Whether the air brakes start each flight switched on. Default + ``True``. + deployment_level : float, optional + Deprecated name of ``initial_deployment_level``. Support for it + will be removed in v1.16. - Returns - ------- - None + Raises + ------ + ValueError + If ``reference_area`` is not positive, the curve does not depend on + the deployment level and the Mach number, or ``active_during`` is + not one of the three phases. """ - self.clamp = clamp + if deployment_level is not None: + warnings.warn( + "`AirBrakes(deployment_level=...)` is deprecated: it is the " + "deployment level every flight starts at, now named " + "`initial_deployment_level`. Support for `deployment_level` will " + "be removed in v1.16.", + DeprecationWarning, + stacklevel=2, + ) + initial_deployment_level = deployment_level + if not reference_area > 0: + raise ValueError( + f"The reference area must be positive, in m², got {reference_area!r}." + ) self.override_rocket_drag = override_rocket_drag - self.initial_deployment_level = deployment_level + self.clamp = bool(clamp) self.drag_coefficient_curve = drag_coefficient_curve - # Back-compatible 2-input (deployment level, Mach) drag curve, kept for - # display/serialization and as the source of the multivariable drag - # coefficient below. - self.drag_coefficient = Function( - drag_coefficient_curve, - inputs=["Deployment Level", "Mach"], - outputs="Drag Coefficient", - interpolation="linear", - ) + # The curve over (deployment level, Mach), as given: shown, saved and + # the source of the axial coefficient below + source = drag_coefficient_curve + if isinstance(source, (int, float)): + # A number: the same coefficient at every level and Mach number + def constant(deployment_level, mach): # pylint: disable=unused-argument + return drag_coefficient_curve - # The drag force acts along the rocket's centerline (see - # flight_derivatives._compute_drag_area), so the curve is given to - # the surface as its axial coefficient, over only the two variables it - # uses. The deployment-0 => Cd 0 rule applies only when the air brakes - # add to (rather than override) the rocket drag. - def drag_coefficient_function(mach, deployment_level): - if deployment_level == 0 and not self.override_rocket_drag: - return 0.0 - return self.drag_coefficient.get_value_opt(deployment_level, mach) + source = constant + + try: + self.drag_coefficient = Function( + source, + inputs=["Deployment Level", "Mach"], + outputs="Drag Coefficient", + interpolation="linear", + ) + except (ValueError, TypeError) as error: + raise ValueError( + "The drag coefficient curve must depend on the deployment level " + "and the Mach number, in that order: a number, a function of the " + "two, or an array or file with three columns (deployment level, " + f"Mach, drag coefficient), got {drag_coefficient_curve!r}." + ) from error super().__init__( reference_area=reference_area, reference_length=2 * (reference_area / np.pi) ** 0.5, - coefficients={"cA": drag_coefficient_function}, + coefficients={"cA": self._axial_coefficient()}, center_of_pressure=(0, 0, 0), name=name, + active_during=active_during, + active=active, controls=("deployment_level",), + control_defaults={"deployment_level": initial_deployment_level}, + control_limits={"deployment_level": (0, 1) if clamp else None}, ) - self.deployment_level = deployment_level self.prints = _AirBrakesPrints(self) self.plots = _AirBrakesPlots(self) - def _clamp_control(self, name, value): - """Clamp ``deployment_level`` to ``[0, 1]`` (or warn if ``clamp`` is - False), preserving the historical AirBrakes behavior.""" - if name == "deployment_level" and (value < 0 or value > 1): - if self.clamp: - value = float(np.clip(value, 0, 1)) - else: - warnings.warn( - f"Deployment level of {self.name} is smaller than 0 or " - + "larger than 1. Extrapolation for the drag coefficient " - + "curve will be used.", - UserWarning, - ) - return value + def _axial_coefficient(self): + """The surface's axial coefficient, over only the two variables it + uses: the force acts along the rocket's axis. Retracted air brakes + make no force, whatever the curve says. The curve is read from the + attribute at each call, so that replacing it after the air brakes are + built changes the drag flown.""" + if self.override_rocket_drag: + # A curve of the whole rocket: the air brakes are what it adds to + # its retracted column, and the rocket keeps its own drag curves + + def axial_coefficient(mach, deployment_level): + if deployment_level == 0: + return 0.0 + curve = self.drag_coefficient.get_value_opt + return curve(deployment_level, mach) - curve(0, mach) + + else: + + def axial_coefficient(mach, deployment_level): + if deployment_level == 0: + return 0.0 + return self.drag_coefficient.get_value_opt(deployment_level, mach) + + return axial_coefficient + + def _bind_coefficients(self): + """Rebuild the axial coefficient, which reads the drag curve of the + air brakes it was built for, so that a deep copy reads its own.""" + coefficient = self._as_coefficient(self._axial_coefficient(), "cA") + self._input_coefficients["cA"] = self.cA = coefficient + + @property + def initial_deployment_level(self): + """The deployment level the air brakes start every flight at, from 0 + to 1. Setting it outside that range moves it to the nearest end, unless + ``clamp`` is ``False``. During a flight the deployment level is a control input + of the flight, ``flight.controls`` gives it after the flight, + and this attribute does not change.""" + return self.control_defaults["deployment_level"] + + @initial_deployment_level.setter + def initial_deployment_level(self, value): + self.control_defaults["deployment_level"] = limited_value( + value, self.control_limits["deployment_level"], "deployment_level" + ) @property def deployment_level(self): - """Returns the deployment level of the air brakes.""" - return self.control_state["deployment_level"] + """Deprecated: the same as :attr:`initial_deployment_level`. A flight + no longer moves the air brakes object: read the deployment level flown + in ``flight.controls``.""" + _warn_deployment_level() + return self.initial_deployment_level @deployment_level.setter def deployment_level(self, value): - self.set_control("deployment_level", value) - - def _reset(self): - """Resets the air brakes to their initial state. This is ran at the - beginning of each simulation to ensure the air brakes are in the correct - state.""" - self.deployment_level = self.initial_deployment_level + _warn_deployment_level() + self.initial_deployment_level = value def evaluate_geometrical_parameters(self): - """Evaluates the geometrical parameters of the aerodynamic surface. + """Nothing to compute: the air brakes' geometry is their reference + area, given.""" - Returns - ------- - None + def _drag_in(self, flight): + """The drag force of the air brakes over ``flight``, in N, as a + Function of time, from the air at each stored row and the deployment + level then in force. Zero while retracted or switched off. + + Private for now: where post-flight analyses of a part live is still + open, see ``docs/development/post_events_issues/issue_flight_analysis.md``. + ``plots.drag(flight)`` draws it. + + Raises + ------ + ValueError + If the air brakes are not on the flight's rocket. """ + on_rocket = self._on_rocket_of(flight) + level = flight.controls[on_rocket.name]["deployment_level"] + times = flight.time + drag = [] + for t in times: + if not on_rocket.is_active(t, flight): + drag.append(0.0) + continue + speed = flight.free_stream_speed.get_value_opt(t) + mach = flight.mach_number.get_value_opt(t) + rho = flight.density.get_value_opt(t) + coefficient = on_rocket.cA(0.0, 0.0, mach, 0.0, 0.0, 0.0, 0.0, level(t)) + drag.append(0.5 * rho * speed**2 * on_rocket.reference_area * coefficient) + return Function( + np.column_stack((times, drag)), + "Time (s)", + f"Drag of {on_rocket.name} (N)", + "linear", + "zero", + ) def info(self): - """Prints and plots summarized information of the aerodynamic surface. + """Print the air brakes' settings and their drag coefficient at a few + deployment levels and Mach numbers. Returns ------- None """ self.prints.geometry() + self.prints.drag_coefficient() def all_info(self): - """Prints and plots all information of the aerodynamic surface. + """Print everything :meth:`info` prints and plot the drag coefficient + curve. Returns ------- None """ - self.info() - self.plots.drag_coefficient_curve() + self.prints.all() + self.plots.all() def to_dict(self, include_outputs=False, **kwargs): # pylint: disable=unused-argument return { @@ -204,17 +313,35 @@ def to_dict(self, include_outputs=False, **kwargs): # pylint: disable=unused-ar "reference_area": self.reference_area, "clamp": self.clamp, "override_rocket_drag": self.override_rocket_drag, - "deployment_level": self.initial_deployment_level, + "initial_deployment_level": self.initial_deployment_level, "name": self.name, + "active_during": self.active_during, + "active": self.active, } @classmethod def from_dict(cls, data): + # "deployment_level" is the key of files saved before v1.15 + level = data.get("initial_deployment_level", data.get("deployment_level", 0)) return cls( - drag_coefficient_curve=data.get("drag_coefficient_curve"), - reference_area=data.get("reference_area"), - clamp=data.get("clamp"), - override_rocket_drag=data.get("override_rocket_drag"), - deployment_level=data.get("deployment_level"), - name=data.get("name"), + drag_coefficient_curve=data["drag_coefficient_curve"], + reference_area=data["reference_area"], + clamp=data.get("clamp", True), + override_rocket_drag=data.get("override_rocket_drag", False), + initial_deployment_level=level, + name=data.get("name", "AirBrakes"), + active_during=data.get("active_during", "always"), + active=data.get("active", True), ) + + +def _warn_deployment_level(): + warnings.warn( + "`AirBrakes.deployment_level` is deprecated: it is the deployment level " + "the air brakes start every flight at, now named " + "`initial_deployment_level`. A flight no longer moves the air brakes " + "object: read the deployment level flown in `flight.controls`. " + "Support for `deployment_level` will be removed in v1.16.", + DeprecationWarning, + stacklevel=3, + ) diff --git a/rocketpy/rocket/aero_surface/controllable_generic_surface.py b/rocketpy/rocket/aero_surface/controllable_generic_surface.py deleted file mode 100644 index 89fcfbbe1..000000000 --- a/rocketpy/rocket/aero_surface/controllable_generic_surface.py +++ /dev/null @@ -1,319 +0,0 @@ -from rocketpy.rocket.aero_surface.generic_surface import GenericSurface - - -class ControllableGenericSurface(GenericSurface): - """An aerodynamic surface whose coefficients also depend on one or - more control inputs (canards, grid fins, elevons, air-brake deployment, and - so on) set by a controller while the rocket flies. - - On top of the seven standard variables of :class:`GenericSurface` - (``alpha``, ``beta``, ``mach``, ``reynolds``, ``pitch_rate``, ``yaw_rate``, - ``roll_rate``), each coefficient takes one extra input per control, in the - order listed in ``controls``. The current control values are set with - :meth:`set_control` and passed to the coefficients automatically. During a - flight a controller does that: build a ``rocketpy.control._Controller`` - with this surface as its ``controlled_objects`` and a function that calls - ``set_control`` from the flight state, and bind it with - ``rocket._add_controllers(controller)`` (the path - :meth:`rocketpy.Rocket.add_air_brakes` uses); the flight then runs the - controller at its sampling rate. - - Attributes - ---------- - ControllableGenericSurface.control_variables : list of str - Names of the controls, in the order the coefficients expect them. - ControllableGenericSurface.control_state : dict - Current value of each control (starts at 0). - ControllableGenericSurface.cN : AeroCoefficient - Normal force coefficient, the force in the pitch plane. - ControllableGenericSurface.cY : AeroCoefficient - Side force coefficient, the force in the yaw plane. - ControllableGenericSurface.cA : AeroCoefficient - Axial force coefficient, the force along the rocket's axis. - ControllableGenericSurface.cm : AeroCoefficient - Pitching moment coefficient, about ``center_of_pressure``. - ControllableGenericSurface.cn : AeroCoefficient - Yawing moment coefficient, about ``center_of_pressure``. - ControllableGenericSurface.cl : AeroCoefficient - Roll moment coefficient. - ControllableGenericSurface.cL : Function - Lift coefficient, the force perpendicular to the airflow. - ControllableGenericSurface.cD : Function - Drag coefficient, the force along the airflow. - ControllableGenericSurface.cQ : Function - Crosswind coefficient, the side force relative to the airflow. - ControllableGenericSurface.cN_alpha : AeroCoefficient - Slope of ``cN`` with the angle of attack, as a function of Mach. - Has units of 1/rad. - ControllableGenericSurface.cY_beta : AeroCoefficient - Slope of ``cY`` with the sideslip angle, as a function of Mach. - Has units of 1/rad. - ControllableGenericSurface.cm_alpha : AeroCoefficient - Slope of ``cm`` with the angle of attack, as a function of Mach. - Has units of 1/rad. - ControllableGenericSurface.cn_beta : AeroCoefficient - Slope of ``cn`` with the sideslip angle, as a function of Mach. - Has units of 1/rad. - ControllableGenericSurface.aerodynamic_center : Function - Pitch-plane aerodynamic center of the surface along the rocket's axis, - in meters from the surface's position (positive toward the nose), as a - function of Mach. It is the point where the change of the normal force - acts when the angle of attack changes a little from zero. It is the - same point as ``center_of_pressure`` when no moment coefficient is - given. - ControllableGenericSurface.aerodynamic_center_yaw : Function - Yaw-plane aerodynamic center of the surface along the rocket's axis, in - meters from the surface's position (positive toward the nose), as a - function of Mach: the same for the side force and the sideslip angle. - ControllableGenericSurface.reference_area : float - Reference area, in square meters. - ControllableGenericSurface.reference_length : float - Reference length, in meters. - ControllableGenericSurface.reynolds_length : float - Length scale of the Reynolds number, in meters. - ControllableGenericSurface.name : str - Name of the surface. - ControllableGenericSurface.center_of_pressure : tuple - Point where the forces are applied, ``(x, y, z)`` in meters, as given. - ControllableGenericSurface.cp : tuple - The same point as ``(cpx, cpy, cpz)``. ``cpz`` is 0 when the center of - pressure varies with Mach, since the force is then applied at ``z = 0``. - ControllableGenericSurface.cpx : float - x coordinate of ``cp``, in meters. - ControllableGenericSurface.cpy : float - y coordinate of ``cp``, in meters. - ControllableGenericSurface.cpz : float - z coordinate of ``cp``, in meters. - ControllableGenericSurface.active_during : str - The motor phase the surface produces force in, as given. - ControllableGenericSurface.active : bool - Whether the surface starts each flight switched on. - ControllableGenericSurface.force_convention : str - Frame the force coefficients were given in: ``"body"`` or ``"wind"``. - ControllableGenericSurface.independent_vars : list of str - The variables every coefficient is called with, in order. - ControllableGenericSurface.prints : _GenericSurfacePrints - The prints of the surface. Use help(ControllableGenericSurface.prints) to - know more. - ControllableGenericSurface.plots : _GenericSurfacePlots - The plots of the surface. Use help(ControllableGenericSurface.plots) to - know more. - """ - - # TODO: deflection-dependent static-margin diagnostics. - # - # The in-flight dynamics are correct: the deflection feeds the coefficient - # functions live every step (see ``_coefficient_arguments``), and the surface - # never physically moves, so its force-application point / ``cp_to_cdm`` cache - # cannot go stale (unlike an individual fin's cant angle, which IS a physical - # reconfiguration and counts up the fin's ``_version`` so the rocket - # refreshes it). - # - # The gap is diagnostic-only. The surface's ``aerodynamic_center`` and the - # rocket's come from ``cm_alpha = d(cm)/d(alpha)`` evaluated ONCE - # (in ``_set_stability_accessors``) with the control variables frozen at their - # value at construction (0). So if ``cm`` couples alpha and a control axis - # (e.g. an ``alpha * deflection`` term), the reported ``static_margin`` is - # pinned to the zero-deflection configuration and does not track ``set_control``. - # It also is not a single well-defined number: the static margin of a deflected - # control surface is inherently a function of the control input. - # - # To address this properly (not a correctness fix, defer until there is a real - # need), likely some combination of: - # - an ``initial_deflection`` (per-control) argument in ``__init__`` so the - # derived cp accessors are built about a chosen reference deflection rather - # than always 0; - # - re-deriving the cp accessors when the deflection changes -- reuse the - # fin mechanism: bump ``_version`` in ``set_control`` so the rocket's - # stamp-based refresh re-runs the derived-cp step; - # - dedicated stability plots/prints that sweep the static margin (and cp) - # OVER the control-deflection range, since a single scalar margin is the - # wrong abstraction for a controllable surface. - - def __init__( - self, - reference_area, - reference_length, - coefficients, - center_of_pressure=(0, 0, 0), - name="Controllable Generic Surface", - *, - reynolds_length=None, - interpolation=None, - extrapolation=None, - force_convention=None, - active_during="always", - active=True, - controls=("deflection",), - ): - """Create an aerodynamic surface whose coefficients also depend on - controls, such as a canard deflection. - - Parameters - ---------- - reference_area : int, float - Reference area of the surface, in square meters. Commonly the - rocket's cross-sectional area. - reference_length : int, float - Reference length of the surface, in meters. Commonly the rocket's - diameter. Used to non-dimensionalize the moment coefficients and the - reduced rotation rates, and (unless ``reynolds_length`` is given) as - the length scale of the Reynolds number. - coefficients : dict - The force and moment coefficients, by name. Any you leave out are 0: - the body-frame forces ``cN`` (normal), ``cY`` (side) and ``cA`` - (axial), or the wind-frame ones ``cL`` (lift), ``cQ`` (side) and - ``cD`` (drag), and the moments ``cm`` (pitch), ``cn`` (yaw) and - ``cl`` (roll), taken about ``center_of_pressure``. - - Each coefficient can depend on ``alpha`` and ``beta`` (radians, or - ``alpha_deg`` and ``beta_deg`` in degrees), ``alpha_total`` and - ``phi`` (or ``alpha_total_deg`` and ``phi_deg``; a ``cN``, ``cL`` or - ``cm`` against ``alpha_total`` alone is split between the pitch and - yaw planes for you, see :class:`GenericSurface`), ``mach``, ``reynolds``, the reduced rates - ``pitch_rate``, ``yaw_rate`` and ``roll_rate`` (such as - ``q * L_ref / (2 * V)``), and each name in ``controls``, for example - ``lambda alpha, mach, deflection: ...``. It can be given as a - number, a function whose arguments are named after the variables it - uses, the path to a CSV file whose header names the variables - (controls included), a list or numpy array of data points as a pair - with the names of its variables, a :class:`Function`, or a pair - ``(axes, values)`` for values on a regular grid. - center_of_pressure : tuple, list, optional - Point where the aerodynamic forces are applied and about which the - moment coefficients are taken, as ``(x, y, z)`` in meters. It is - measured from the position the surface is added to the rocket at: - ``z`` runs along the rocket's centerline and is positive toward the - nose, whichever coordinate system orientation the rocket uses. The - ``z`` component may instead vary with Mach, as a function of Mach, a - one-input :class:`Function` or a two-column table - ``[[mach, z], ...]``; the moments are then carried to that point by - the moment coefficients. Default ``(0, 0, 0)``. - name : str, optional - Name of the surface. Default ``"Controllable Generic Surface"``. - reynolds_length : int, float, optional - Length scale, in meters, of the Reynolds number passed to the - coefficients. Set it to the length your Reynolds-dependent data was - tabulated against (for example the rocket's body length). ``None`` - (the default) uses ``reference_length`` (the diameter). - interpolation : str or dict, optional - How tabulated coefficients read values between points: a 1-D table - accepts ``"linear"``, ``"akima"``, ``"spline"`` and ``"polynomial"``; - a multi-dimensional scattered table accepts ``"linear"``, - ``"shepard"`` and ``"rbf"``; and a table on a regular grid accepts - ``"linear"``, ``"nearest"``, ``"slinear"``, ``"cubic"``, - ``"quintic"`` and ``"pchip"``. Give one string for all coefficients - or a dict keyed by coefficient name. ``None`` (the default) uses - ``"linear"`` for tables built here and leaves a pre-built - :class:`Function` unchanged. - extrapolation : str or dict, optional - What tabulated coefficients do outside their data range: - ``"constant"`` holds the nearest edge value, ``"natural"`` keeps - following the curve, ``"zero"`` returns 0. Give one string for all - coefficients or a dict keyed by coefficient name. ``None`` (the - default) uses ``"constant"`` for tables built here and leaves a - pre-built :class:`Function` unchanged. - force_convention : str, optional - The frame the force coefficients are given in: ``"body"`` for - ``cN``/``cY``/``cA`` or ``"wind"`` for ``cL``/``cQ``/``cD``. ``None`` - (the default) works it out from the names. - active_during : str, optional - The motor phase this surface produces force in: ``"always"`` - (default), ``"power_on"`` (only while the motor burns, e.g. jet - vanes) or ``"power_off"`` (only after burnout). To switch a surface - on or off at any other moment, use an event: see ``active`` below. - active : bool, optional - Whether the surface starts each flight switched on. Default is - ``True``. Use ``False`` for a surface that only appears later in - the flight, and switch it on from an event with - ``context.event.commands.activate_surface(surface)``. A surface - that is on from the start is switched off the same way, with - ``deactivate_surface``. - controls : iterable of str, optional - Names of the controls, such as a canard deflection angle. Each name - becomes an extra input to every coefficient, after the seven flow - variables and in this order, and a key in :attr:`control_state`. The - values start at 0 and are set with :meth:`set_control`. Default - ``("deflection",)``. - - Raises - ------ - TypeError - If ``coefficients`` is not a dict, or ``center_of_pressure`` is not - an ``(x, y, z)`` triple. - ValueError - If a coefficient name, a variable name, ``force_convention`` or - ``active_during`` is not one of the accepted values, or if - wind-frame and body-frame force coefficients are mixed without a - ``force_convention``. - - See Also - -------- - :ref:`genericsurfaces` - """ - # Set before the base constructor, which reads them to build the - # coefficients - self.control_variables = list(controls) - self.control_state = {name: 0.0 for name in self.control_variables} - - super().__init__( - reference_area=reference_area, - reference_length=reference_length, - coefficients=coefficients, - center_of_pressure=center_of_pressure, - name=name, - reynolds_length=reynolds_length, - extrapolation=extrapolation, - interpolation=interpolation, - force_convention=force_convention, - active_during=active_during, - active=active, - ) - # ``self.prints``/``self.plots`` are the generic ones wired by the base. - - @classmethod - def _input_variable_names(cls, **kwargs): - controls = kwargs.get("controls", ("deflection",)) - return [*super()._input_variable_names(), *controls] - - def _coefficient_arguments(self, *state): - """Add the current value of each control, in ``control_variables`` order.""" - return (*state, *(self.control_state[name] for name in self.control_variables)) - - def _clamp_control(self, name, value): # pylint: disable=unused-argument - """Hook to constrain a control value before it is stored. The base class - applies no clamping; subclasses (e.g. ``AirBrakes``) may override.""" - return value - - def set_control(self, name, value): - """Set the current value of a control variable (applying any clamping). - - Parameters - ---------- - name : str - Name of the control variable; must be one of - :attr:`control_variables`. - value : float - New control value. - """ - if name not in self.control_state: - raise KeyError( - f"Unknown control variable '{name}'. " - f"Valid controls are: {self.control_variables}." - ) - self.control_state[name] = self._clamp_control(name, value) - - def get_control(self, name): - """Return the current value of a control variable.""" - return self.control_state[name] - - def to_dict(self, include_outputs=False, **kwargs): - data = super().to_dict(include_outputs=include_outputs, **kwargs) - data["controls"] = list(self.control_variables) - return data - - @classmethod - def _arguments_from_dict(cls, data): - arguments = super()._arguments_from_dict(data) - arguments["controls"] = data.get("controls", ("deflection",)) - return arguments diff --git a/rocketpy/rocket/aero_surface/fins/__init__.py b/rocketpy/rocket/aero_surface/fins/__init__.py index dd678c625..881fd43cb 100644 --- a/rocketpy/rocket/aero_surface/fins/__init__.py +++ b/rocketpy/rocket/aero_surface/fins/__init__.py @@ -1,3 +1,4 @@ +from rocketpy.rocket.aero_surface.fins.control_fins import ControlFins from rocketpy.rocket.aero_surface.fins.elliptical_fin import EllipticalFin from rocketpy.rocket.aero_surface.fins.elliptical_fins import EllipticalFins from rocketpy.rocket.aero_surface.fins.fin import Fin diff --git a/rocketpy/rocket/aero_surface/fins/control_fins.py b/rocketpy/rocket/aero_surface/fins/control_fins.py new file mode 100644 index 000000000..60aad63f9 --- /dev/null +++ b/rocketpy/rocket/aero_surface/fins/control_fins.py @@ -0,0 +1,804 @@ +import math +from copy import deepcopy + +import numpy as np + +from rocketpy.mathutils.function import Function +from rocketpy.mathutils.vector_matrix import Vector +from rocketpy.plots.aero_surface_plots import _ControlFinsPlots +from rocketpy.prints.aero_surface_prints import _ControlFinsPrints +from rocketpy.rocket.aero_surface.aero_coefficient import AeroCoefficient +from rocketpy.rocket.aero_surface.fins.fin import Fin +from rocketpy.rocket.aero_surface.generic_surface import GenericSurface +from rocketpy.tools import point_around + +# The variables the coefficients of a set of control fins depend on, before +# the deflection of each fin. The Reynolds number plays no part in the fin model. +_FLOW_VARIABLES = ("alpha", "beta", "mach", "pitch_rate", "yaw_rate", "roll_rate") + + +class ControlFins(GenericSurface): + """A set of fins a controller turns one by one, such as canards or movable + tail fins. + + The set is ``n`` copies of one fin, spaced evenly around the rocket, or a + list of fins given one by one. Each fin has one control, its deflection + in radians: the angle it is turned by about its hinge line, exactly as a + cant angle turns a fixed fin. The fins are numbered from the one given, + the way the angular position grows: with 4 fins at 0 degrees, ``fin_1`` + is at 0, ``fin_2`` at 90, ``fin_3`` at 180 and ``fin_4`` at 270. + :meth:`info` prints this table. In a flight each deflection is a control + input named after the set, ``canards.fin_1`` for a set named + ``"Canards"``. :meth:`deflections` turns a roll, a pitch and a yaw command + into one deflection per fin; :meth:`effectiveness` gives the moment + coefficient per radian of each, for the controller's design. + + The same positive deflection on every fin gives a negative roll moment + (``w3`` decreases), as a positive cant angle does. One fin deflected + alone pushes the rocket sideways at that fin: the fin at 0 degrees (on + the ``+y`` axis) toward ``+x``, the fin at 90 degrees toward ``+y``. On + canards the nose follows the push, on tail fins it goes the other way. + + The fin model does not stall, so keep the deflection plus the angle of + attack within a few tenths of a radian; ``deflection_limits`` enforces + it. A set held at a deflection gives the same forces as the same fins + added to the rocket with that cant angle. + + Attributes + ---------- + ControlFins.fin : Fin or None + The fin the set is copied from, or ``None`` when the fins were given + one by one. + ControlFins.n : int + The number of fins. + ControlFins.fins : tuple of Fin + The fins of the set, in order: ``fins[0]`` is ``fin_1``. Each is + uncanted: its deflection turns it during the flight. + ControlFins.angular_positions : tuple of float + The angular position of each fin, in degrees, in order. + ControlFins.hinge_position : float + Where the hinge line crosses the root chord, as a fraction of its + length from the leading edge. + ControlFins.controls : tuple of str + ``("fin_1", ..., "fin_n")``: the deflection of each fin. + ControlFins.control_defaults : dict + Deflection of each fin at the start of every flight, in radians. + ControlFins.control_limits : dict + ``(low, high)`` deflection of each fin, in radians, or ``None``. + """ + + # The fins of the set act at different points around the rocket, and a set + # deflected unevenly pushes harder in one plane than in the other + is_axisymmetric = False + + def __init__( # pylint: disable=too-many-arguments + self, + fin, + n=None, + hinge_position=0.5, + deflection_limits=None, + name="ControlFins", + active_during="always", + active=True, + ): + """Build a set of control fins. + + Parameters + ---------- + fin : TrapezoidalFin, EllipticalFin or FreeFormFin, or a sequence of them + One fin: the fin every fin of the set is a copy of. Its + ``angular_position`` is where ``fin_1`` sits, and its + ``cant_angle`` is the deflection every fin starts each flight at + (0 for an uncanted fin). A sequence of fins: the fins of the set, + one by one, ``fin_1`` first, each at its own ``angular_position`` + and starting each flight at its own ``cant_angle``; they may + differ in shape and size. Angles are in degrees, while the + deflections a controller writes are in radians. The fins given + are not changed or added to the rocket themselves. The set's + reference area and length are the first fin's. + n : int, optional + The number of fins. With one fin, how many copies to space evenly + around the rocket, 4 by default. With a sequence of fins it is + their count, and need not be given. + hinge_position : float, optional + Where the hinge line, the axis the fin turns about, crosses the + root chord: a fraction of the root chord from the leading edge, + from 0 (the leading edge) to 1 (the trailing edge). It sets where + the fin moves to when it turns. Default 0.5, the middle of the + root chord, which is also where a cant angle turns a fixed fin. + deflection_limits : tuple of float, optional + ``(low, high)``: the smallest and largest deflection of each fin, + in radians, for example ``(-0.2, 0.2)``: how far the fins can + turn, and the way to keep them where the fin model holds, within + a few tenths of a radian. A deflection asked for outside them is + moved to the nearest limit. Default ``None``, no limits. + name : str, optional + Name of the set. It also names the control inputs, in snake_case: + ``"Canards"`` gives ``canards.fin_1``, ``canards.fin_2`` and so on. + Default ``"ControlFins"``, which gives ``control_fins.fin_1``. + active_during : str, optional + The motor phase the fins produce force in: ``"always"`` (the + default), ``"power_on"`` or ``"power_off"``. + active : bool, optional + Whether the fins start each flight switched on. Default ``True``. + + Raises + ------ + TypeError + If ``fin`` is neither an individual fin nor a sequence of them, or + ``n`` is not a whole number. + ValueError + If ``n`` is smaller than 1 or differs from the number of fins + given, ``deflection_limits`` is not ``(low, high)`` with + ``low <= high``, or ``hinge_position`` is not between 0 and 1. + """ + given = self.__check_fins(fin, n) + n = len(given) + if not 0 <= hinge_position <= 1: + raise ValueError( + "The hinge position is a fraction of the root chord from the " + f"leading edge, between 0 and 1, got {hinge_position!r}." + ) + + self.fin = deepcopy(fin) if isinstance(fin, Fin) else None + self.n = n + self._hinge_position = hinge_position + self.deflection_limits = ( + None if deflection_limits is None else tuple(deflection_limits) + ) + self.angular_positions = tuple(each.angular_position for each in given) + self.fins = tuple( + self._copy_fin(each, each.angular_position, f"{name} fin {i + 1}") + for i, each in enumerate(given) + ) + # The fins as given, canted, to save the set + self._given = tuple(deepcopy(each) for each in given) + # Where each fin's root leading edge sits without a deflection, from + # the point the set is added at, in the body frame + self._roots = tuple( + Vector(point_around(0, each.angular_position, each.rocket_radius)) + for each in self.fins + ) + # The frame of each fin at the deflection it was last flown with, so a + # deflection held for many steps is not turned again at each one + self._frames = [None] * n + # Where the set sits on the rocket it was last added to, from the + # center of dry mass, in the body frame. The rocket sets it. + self._position = None + + controls = tuple(f"fin_{i + 1}" for i in range(n)) + defaults = { + control: math.radians(each.cant_angle) + for control, each in zip(controls, given) + } + super().__init__( + reference_area=given[0].reference_area, + reference_length=given[0].reference_length, + coefficients={}, + center_of_pressure=(0, 0, 0), + name=name, + active_during=active_during, + active=active, + controls=controls, + control_defaults=defaults, + control_limits=( + None + if deflection_limits is None + else dict.fromkeys(controls, deflection_limits) + ), + ) + self.prints = _ControlFinsPrints(self) + self.plots = _ControlFinsPlots(self) + + @property + def hinge_position(self): + """Where the hinge line crosses the root chord, as a fraction of its + length from the leading edge, from 0 to 1.""" + return self._hinge_position + + @hinge_position.setter + def hinge_position(self, value): + self._hinge_position = value + # The frames kept were turned about the old hinge line, and so were + # the forces the coefficients kept for the point they were last read at + self._frames = [None] * self.n + self._bind_coefficients() + self._version += 1 + + @staticmethod + def __check_fins(fin, n): + """The fins of the set as given: ``n`` evenly spaced copies of one fin, + or the sequence given, with ``n`` checked against it.""" + if isinstance(fin, Fin): + n = 4 if n is None else n + if isinstance(n, bool) or not isinstance(n, int): + raise TypeError( + f"The number of fins must be a whole number, got {n!r}." + ) + if n < 1: + raise ValueError(f"The number of fins must be at least 1, got {n}.") + copies = [] + for i in range(n): + copy = deepcopy(fin) + copy.angular_position = (fin.angular_position + 360 * i / n) % 360 + copies.append(copy) + return tuple(copies) + if ( + isinstance(fin, (list, tuple)) + and fin + and all(isinstance(each, Fin) for each in fin) + ): + if n is not None and n != len(fin): + raise ValueError( + f"{len(fin)} fins were given, but n={n!r}. Leave n out when " + "giving the fins one by one." + ) + return tuple(fin) + raise TypeError( + "ControlFins is built from one individual fin, such as " + f"TrapezoidalFin(...), or a sequence of them, got {fin!r}." + ) + + @staticmethod + def _copy_fin(fin, angular_position, name): + """A copy of ``fin`` at ``angular_position``, uncanted: the deflection + turns it during the flight.""" + copy = deepcopy(fin) + copy.name = name + if copy.cant_angle != 0: + copy.cant_angle = 0 + if copy.angular_position != angular_position: + copy.angular_position = angular_position + return copy + + def _frame(self, index, deflection): + """The rotations of fin ``index`` turned by ``deflection`` and where its + center of pressure is, from the point the set is added at, in the body + frame.""" + frame = self._frames[index] + if frame is not None and frame[0] == deflection: + return frame[1:] + fin = self.fins[index] + uncanted, body_to_fin = fin._rotations(deflection) + fin_to_body = body_to_fin.transpose + offset = ( + self._roots[index] + + fin._cant_shift(deflection, uncanted.transpose, self.hinge_position) + + fin_to_body @ fin.force_application_point + ) + self._frames[index] = (deflection, body_to_fin, fin_to_body, offset) + return body_to_fin, fin_to_body, offset + + def _fins_in_air( + self, stream_velocity, stream_speed, stream_mach, omega, deflections + ): + """Each fin turned by its deflection, with its frame and the air it + meets where it sits: ``(fin, deflection, body_to_fin, fin_to_body, + offset, stream, speed, mach)``. The rotation of the rocket moves each + fin through the air on its own, as it would an individual fin added to + the rocket.""" + stream_velocity = Vector(stream_velocity) + omega = Vector(omega) + for index, (fin, deflection) in enumerate(zip(self.fins, deflections)): + body_to_fin, fin_to_body, offset = self._frame(index, deflection) + stream = stream_velocity - (omega ^ offset) + speed = abs(stream) + mach = stream_mach * speed / stream_speed if stream_speed > 0 else 0.0 + yield fin, deflection, body_to_fin, fin_to_body, offset, stream, speed, mach + + def _fin_forces( # pylint: disable=too-many-arguments + self, stream_velocity, stream_speed, stream_mach, rho, cp, omega, deflections + ): + """Sum the forces and moments of the fins, each turned by its + deflection and fed the air it meets where it sits.""" + totals = [0.0] * 6 + for ( + fin, + deflection, + body_to_fin, + fin_to_body, + offset, + *air, + ) in self._fins_in_air( + stream_velocity, stream_speed, stream_mach, omega, deflections + ): + forces = fin._forces_in_frame( + *air, rho, cp + offset, omega, body_to_fin, fin_to_body, deflection + ) + for k in range(6): + totals[k] += forces[k] + return tuple(totals) + + @staticmethod + def _stream(alpha, beta): + """The unit air velocity in the body frame for the angles given, in + radians: from the nose toward the tail (``-z``), turned by ``alpha`` + toward ``-y`` and by ``beta`` toward ``-x``, as + :meth:`GenericSurface.compute_forces_and_moments` defines the angles.""" + stream = Vector([-math.tan(beta), -math.tan(alpha), -1.0]) + return stream / abs(stream) + + def compute_forces_and_moments( # pylint: disable=arguments-differ + self, + stream_velocity, + stream_speed, + stream_mach, + rho, + cp, + omega, + density=None, + dynamic_viscosity=None, + z=None, + controls=None, + ): + """Compute the forces and moments of the fins, each turned by its + deflection. Called at each step of the simulation. + + Parameters + ---------- + stream_velocity : Vector + Velocity of the air relative to the point the set is added at, in + the body frame, in m/s. Flying nose first it points toward ``-z``, + from the nose to the tail. + stream_speed : float + Its magnitude, in m/s. + stream_mach : float + Its Mach number. + rho : float + Air density, in kg/m³. + cp : Vector + The point the set is added at, relative to the rocket's center of + dry mass, in the body frame, in meters. + omega : tuple of float + Angular velocity of the rocket about the body axes, in rad/s. + density, dynamic_viscosity, z : optional + Accepted for the same call as the other surfaces. Unused: the fin + model does not depend on the Reynolds number. + controls : sequence of float, optional + The deflection of each fin, in radians, in the order of + :attr:`controls`. ``None`` (the default) uses the default + deflections, as outside a flight. + + Returns + ------- + tuple of float + The forces ``(R1, R2, R3)`` along the body axes and the moments + ``(M1, M2, M3)`` about them, taken about the rocket's center of dry + mass. + """ + deflections = self._default_control_values() if controls is None else controls + return self._fin_forces( + stream_velocity, stream_speed, stream_mach, rho, cp, omega, deflections + ) + + def evaluate_coefficients(self): + """Write the forces of the fins as the six body-frame coefficients, + taken about the point the set is added at, as functions of the angles, + Mach, the reduced rates and the deflection of each fin. They are what + the static margin, the plots and :meth:`rocketpy.Rocket.to_surface` + read; the flight computes the same forces directly.""" + variables = (*_FLOW_VARIABLES, *self.controls) + last = {} + + def coefficients(*args): + # The six coefficients come from one sum over the fins, so the sum + # is kept for the next coefficient read at the same point + if last.get("args") != args: + last["args"], last["values"] = args, self._coefficients_at(*args) + return last["values"] + + for index, name in enumerate(("cN", "cY", "cA", "cm", "cn", "cl")): + setattr( + self, + name, + AeroCoefficient( + lambda *args, index=index: coefficients(*args)[index], + depends_on=variables, + control_variables=self.controls, + name=name, + ), + ) + + def _bind_coefficients(self): + """Rebuild the coefficients, computed from the fins of the set they + were built for, so that a deep copy reads its own fins.""" + self.evaluate_coefficients() + self._evaluate_stability_derivatives() + + def _coefficients_at( # pylint: disable=too-many-arguments + self, alpha, beta, mach, pitch_rate, yaw_rate, roll_rate, *deflections + ): + """``(cN, cY, cA, cm, cn, cl)`` of the set at unit speed and density, + about the point the set is added at, in the air :meth:`_stream` gives + for the angles.""" + # The reduced rates are omega * L / (2 * V), at a speed of 1 + rate_factor = 2 / self.reference_length + omega = Vector([pitch_rate, yaw_rate, roll_rate]) * rate_factor + R1, R2, R3, M1, M2, M3 = self._fin_forces( + self._stream(alpha, beta), + 1.0, + mach, + 1.0, + Vector([0, 0, 0]), + omega, + deflections, + ) + force = 0.5 * self.reference_area + moment = force * self.reference_length + return ( + -R2 / force, + R1 / force, + -R3 / force, + M1 / moment, + M2 / moment, + M3 / moment, + ) + + def _placed_at(self, position): + """Called by the rocket with where the set sits, from the center of dry + mass, in the body frame. The pitch and yaw commands depend on it.""" + self._position = position + + def _side(self): + """``1`` for a set ahead of the rocket's center of dry mass, ``-1`` + for one behind it. A pitch or yaw command turns the fins one way on + canards and the other way on tail fins.""" + if self._position is None: + raise ValueError( + f"'{self.name}' is not on a rocket yet. A pitch or yaw command " + "turns the fins one way ahead of the center of mass and the other " + "way behind it, so add the set to the rocket first, with " + "rocket.add_surfaces." + ) + if self._position.z == 0: + raise ValueError( + f"'{self.name}' sits at the rocket's center of dry mass, where " + "its fins cannot pitch or yaw the rocket." + ) + return 1 if self._position.z > 0 else -1 + + def deflections(self, roll=0.0, pitch=0.0, yaw=0.0): + """Turn a roll, a pitch and a yaw command into the deflection of + every fin. + + A positive command turns the rocket toward the positive angular + velocity of that name: ``roll`` raises ``w3`` (about the rocket's + axis), ``pitch`` raises ``w1`` (about the body ``x`` axis) and ``yaw`` + raises ``w2`` (about the body ``y`` axis). This holds for canards and + for tail fins alike, so a controller that opposes the three angular + velocities uses ``roll=-K * w3``, ``pitch=-K * w1`` and + ``yaw=-K * w2``. + + Each fin gets ``-roll + side * (yaw * cos(phi) - pitch * sin(phi))``, + with ``phi`` its angular position and ``side`` equal to 1 for a set + ahead of the rocket's center of dry mass and -1 for one behind it. The + pitch and yaw commands therefore need the set to be on a rocket. + + Parameters + ---------- + roll : float, optional + Roll command, in radians: every fin is turned by this angle, the + way that raises ``w3``. Default 0. + pitch : float, optional + Pitch command, in radians: the angle the fins on the body ``x`` + axis are turned by, the way that raises ``w1``; the other fins + follow with the sine of their angular position. Default 0. + yaw : float, optional + Yaw command, in radians: the angle the fins on the body ``y`` + axis are turned by, the way that raises ``w2``; the other fins + follow with the cosine of their angular position. Default 0. + + Returns + ------- + dict + The deflection of each fin, in radians, by control name: + ``{"fin_1": ..., "fin_2": ..., ...}``. Write them all at once + with ``context.controls..update(...)``. + + Raises + ------ + ValueError + If a pitch or yaw command is given before the set is added to a + rocket, or for a set placed at the rocket's center of dry mass. + + Examples + -------- + >>> from rocketpy import ControlFins, TrapezoidalFin + >>> fin = TrapezoidalFin(root_chord=0.1, tip_chord=0.05, span=0.08, + ... rocket_radius=0.06, angular_position=0) + >>> canards = ControlFins(fin, n=4, name="Canards") + >>> canards.deflections(roll=0.1) + {'fin_1': -0.1, 'fin_2': -0.1, 'fin_3': -0.1, 'fin_4': -0.1} + """ + side = self._side() if pitch != 0 or yaw != 0 else 0 + # Rounded so cos(90 deg) gives 0 rather than 6e-17; + 0.0 turns -0.0 to 0.0 + return { + control: round( + -roll + + side + * ( + yaw * math.cos(math.radians(phi)) + - pitch * math.sin(math.radians(phi)) + ), + 12, + ) + + 0.0 + for control, phi in zip(self.controls, self.angular_positions) + } + + def effectiveness(self, alpha=0.0, beta=0.0): + """Give the moment the fins produce per radian of each command of + :meth:`deflections`, as functions of Mach. + + The numbers are moment coefficients: multiply by the dynamic pressure, + the set's reference area and its reference length to get a moment in + N m per radian of command. They are what sets the gain of a roll or + attitude controller. The pitch and yaw moments are taken about the + rocket's center of dry mass, where the center of mass is once the + propellant has burned. While the motor burns the center of mass is + further aft, so canards turn the rocket a little more and tail fins a + little less. + + The air comes head on, from the nose toward the tail (along ``-z`` in + the body frame), turned by the two angles below. The rocket is not + rotating. :meth:`rocketpy.ControlFins.info` prints these numbers at + one Mach number and ``plots.effectiveness()`` draws them. + + Parameters + ---------- + alpha, beta : float, optional + The angle of attack and the sideslip angle, in radians, the + effectiveness is taken at. A positive ``alpha`` means the rocket + moves toward ``+y`` through the air, so the air flows across it + toward ``-y``; a positive ``beta`` the same toward ``+x`` and + ``-x``. Default 0, head on. + + Returns + ------- + dict of Function + ``"roll"``: the roll moment coefficient per radian of the roll + command. ``"pitch"`` and ``"yaw"``: the moment coefficients about + the body ``x`` and ``y`` axes per radian of the pitch and yaw + commands; they are only given for a set that is on a rocket. All + are positive, and each is a :class:`rocketpy.Function` of the + Mach number. + + Examples + -------- + >>> from rocketpy import ControlFins, TrapezoidalFin + >>> fin = TrapezoidalFin(root_chord=0.1, tip_chord=0.05, span=0.08, + ... rocket_radius=0.06, angular_position=0) + >>> canards = ControlFins(fin, n=4, name="Canards") + >>> roll_per_rad = canards.effectiveness()["roll"] + >>> bool(roll_per_rad(0.3) > 0) + True + """ + stream = self._stream(alpha, beta) + still = Vector([0, 0, 0]) + on_a_rocket = self._position is not None and self._position.z != 0 + position = self._position if on_a_rocket else still + moment = 0.5 * self.reference_area * self.reference_length + step = 0.01 # rad, small enough for the slope, large enough for the sum + + def forces(mach, deflections): + # At unit speed and density, about the rocket's center of dry mass + return self._fin_forces( + stream, 1.0, mach, 1.0, position, still, deflections + ) + + def slope(command, index): + up = list(self.deflections(**{command: step}).values()) + down = list(self.deflections(**{command: -step}).values()) + return Function( + lambda mach: ( + (forces(mach, up)[index] - forces(mach, down)[index]) + / (2 * step) + / moment + ), + "Mach Number", + f"{command.capitalize()} Moment Coefficient per rad", + ) + + effectiveness = {"roll": slope("roll", 5)} + if on_a_rocket: + effectiveness["pitch"] = slope("pitch", 3) + effectiveness["yaw"] = slope("yaw", 4) + return effectiveness + + def hinge_moments(self, dynamic_pressure, deflections=None, alpha=0.0, beta=0.0): + """Give the torque the air puts on each fin about its hinge line, in + N m, as a function of Mach: the load the mechanism turning the fin + has to hold. + + Each fin's torque is its normal force times the distance along the + chord from the hinge line to the fin's center of pressure. The center + of pressure is the one point the fin model gives, the quarter chord of + the mean chord at low speed. The real one moves back at transonic and + supersonic speeds and with the angle of attack, so when the hinge is + placed close to it, as it usually is to keep this torque small, the + size is right but the sign is not to be trusted. Size the mechanism + for the largest torque over the deflections and speeds it will see. + + ``alpha`` and ``beta`` set the direction the air comes from: both zero + means straight along the rocket, from the nose toward the tail + (``-z``). The rocket is not rotating. + + Parameters + ---------- + dynamic_pressure : float + Half the air density times the airspeed squared, in Pa, the + torques are given at. + deflections : float or dict, optional + The deflection of the fins, in radians: one number for every fin, + or one per control input as :meth:`deflections` returns. A fin + left out keeps its default deflection. Default ``None``, every fin + at its default. + alpha, beta : float, optional + The angle of attack and the sideslip angle, in radians. A + positive ``alpha`` means the rocket moves toward ``+y`` through + the air, so the air flows across it toward ``-y``; a positive + ``beta`` the same toward ``+x`` and ``-x``. Default 0, head on. + + Returns + ------- + dict of Function + One :class:`rocketpy.Function` of the Mach number per control + input, keyed by its name, giving the torque in N m. Positive + pushes the fin toward a larger deflection, negative toward a + smaller one, so a fin with its hinge ahead of the center of + pressure gets a negative torque at a positive deflection. + + Examples + -------- + >>> from rocketpy import ControlFins, TrapezoidalFin + >>> fin = TrapezoidalFin(root_chord=0.1, tip_chord=0.05, span=0.08, + ... rocket_radius=0.06, angular_position=0) + >>> canards = ControlFins(fin, n=4, hinge_position=0.25, name="Canards") + >>> torque = canards.hinge_moments(20e3, deflections=0.1)["fin_1"] + >>> bool(torque(0.3) < 0) + True + """ + stream = self._stream(alpha, beta) + still = Vector([0, 0, 0]) + if deflections is None: + deflections = {} + elif not isinstance(deflections, dict): + deflections = dict.fromkeys(self.controls, float(deflections)) + values = [ + deflections.get(control, self.control_defaults[control]) + for control in self.controls + ] + # Unit speed and a density of twice the dynamic pressure give + # 0.5 * rho * speed**2 = dynamic_pressure + rho = 2 * dynamic_pressure + + def torque(index): + # Function reads the number of inputs off the callable, so the + # index is bound here rather than as a default argument + return lambda mach: self._hinge_moments_at( + stream, 1.0, mach, rho, still, values + )[index] + + return { + control: Function( + torque(index), "Mach Number", f"Hinge Moment of {control} (N m)" + ) + for index, control in enumerate(self.controls) + } + + def _hinge_moments_at( + self, stream_velocity, stream_speed, stream_mach, rho, omega, deflections + ): + """The torque on each fin about its hinge line, in N m, in the air + given, fed to each fin as :meth:`_fin_forces` feeds it: the fin's + normal force times the chordwise arm from the hinge line to its + center of pressure, positive toward a larger deflection.""" + return [ + fin._normal_force(*air, rho, body_to_fin) + * (fin.cpz - self.hinge_position * fin.root_chord) + for fin, _, body_to_fin, _, _, *air in self._fins_in_air( + stream_velocity, stream_speed, stream_mach, omega, deflections + ) + ] + + def _hinge_moments_in(self, flight): + """The torque on each fin about its hinge line over ``flight``, in + N m: one Function of time per control input, from the air the set met + at each stored row of the flight and the deflections then in force. + + Private for now: where post-flight analyses of a part live is still + open, see ``docs/development/post_events_issues/issue_flight_analysis.md``. + ``plots.hinge_moments(flight)`` draws it. + + Raises + ------ + ValueError + If the set is not on the flight's rocket. + """ + on_rocket = self._on_rocket_of(flight) + cp = flight.rocket.surfaces_cp_to_cdm[on_rocket] + history = flight.controls[on_rocket.name] + times = flight.time + # The air at the rocket's center of dry mass, moved to the set by the + # rotation; the wind at the set's own altitude is not told apart + streams = np.atleast_2d(flight.stream_velocity_body_frame) + rows = [] + for t, stream in zip(times, streams): + if not on_rocket.is_active(t, flight): + rows.append([0.0] * on_rocket.n) + continue + omega = Vector( + [ + flight.w1.get_value_opt(t), + flight.w2.get_value_opt(t), + flight.w3.get_value_opt(t), + ] + ) + stream = Vector(stream) - (omega ^ cp) + speed = abs(stream) + mach = speed / flight.speed_of_sound.get_value_opt(t) + rho = flight.density.get_value_opt(t) + deflections = [ + history[control].get_value_opt(t) for control in on_rocket.controls + ] + rows.append( + on_rocket._hinge_moments_at( + stream, speed, mach, rho, omega, deflections + ) + ) + rows = np.array(rows) + return { + control: Function( + np.column_stack((times, rows[:, index])), + "Time (s)", + f"Hinge Moment of {on_rocket.name} {control} (N m)", + "linear", + "zero", + ) + for index, control in enumerate(on_rocket.controls) + } + + def info(self): + """Print which fin is which (its control input, angular position and + default deflection), the effectiveness, then the geometry and the + coefficients. + + Returns + ------- + None + """ + self.prints.fins() + self.prints.effectiveness() + self.prints.geometry() + self.prints.coefficients() + + def to_dict(self, include_outputs=False, **kwargs): # pylint: disable=unused-argument + return { + "fin": self.fin if self.fin is not None else list(self._given), + "n": self.n, + "name": self.name, + "deflection_limits": self.deflection_limits, + "hinge_position": self.hinge_position, + "active_during": self.active_during, + "active": self.active, + # As they are now, if changed since the set was built + **self._control_settings(), + } + + @classmethod + def from_dict(cls, data): + limits = data.get("deflection_limits") + fins = cls( + data["fin"], + n=data.get("n"), + name=data.get("name", "ControlFins"), + deflection_limits=None if limits is None else tuple(limits), + hinge_position=data.get("hinge_position", 0.5), + active_during=data.get("active_during", "always"), + active=data.get("active", True), + ) + if "control_defaults" in data: + fins._set_controls( + fins.controls, data["control_defaults"], data["control_limits"] + ) + return fins diff --git a/rocketpy/rocket/aero_surface/fins/fin.py b/rocketpy/rocket/aero_surface/fins/fin.py index f136b8c06..a9859cb60 100644 --- a/rocketpy/rocket/aero_surface/fins/fin.py +++ b/rocketpy/rocket/aero_surface/fins/fin.py @@ -5,6 +5,7 @@ from rocketpy.mathutils.vector_matrix import Matrix, Vector from rocketpy.rocket.aero_surface._helpers import _wind_axes from rocketpy.rocket.aero_surface.fins._base_fin import _BaseFin +from rocketpy.tools import point_around # Still abstract: each fin shape class provides the center of pressure @@ -308,8 +309,19 @@ def evaluate_rotation_matrix(self): ---------- :ref:`Individual Fin Model ` """ + R_uncanted, R_body_to_fin = self._rotations(self.cant_angle_rad) + + # Store for downstream transforms + self._rotation_fin_to_body_uncanted = R_uncanted.transpose + self._rotation_body_to_fin = R_body_to_fin + self._rotation_fin_to_body = R_body_to_fin.transpose + self._rotation_surface_to_body = self._rotation_fin_to_body + + def _rotations(self, delta): + """Return the rotations from the body frame to the fin frame for the + fin turned by the cant angle ``delta``, in radians: without the cant, + then with it. ``ControlFins`` calls it with each fin's deflection.""" phi = self.angular_position_rad - delta = self.cant_angle_rad sin_phi = math.sin(phi) cos_phi = math.cos(phi) sin_delta = math.sin(delta) @@ -344,13 +356,7 @@ def evaluate_rotation_matrix(self): # Uncanted body to fin, then apply cant R_uncanted = R_phi @ R_pi - R_body_to_fin = R_delta @ R_uncanted - - # Store for downstream transforms - self._rotation_fin_to_body_uncanted = R_uncanted.transpose - self._rotation_body_to_fin = R_body_to_fin - self._rotation_fin_to_body = R_body_to_fin.transpose - self._rotation_surface_to_body = self._rotation_fin_to_body + return R_uncanted, R_delta @ R_uncanted @property def force_application_point(self): @@ -457,8 +463,9 @@ def compute_forces_and_moments( Tuple containing angular velocities around the x, y, z axes. *args Extra positional arguments accepted for signature compatibility with - the generic surface (e.g. ``density``, ``dynamic_viscosity``, - ``z``). Unused by the fin's Barrowman model. + the generic surface (``density``, ``dynamic_viscosity``, ``z`` and + ``controls``). Unused by the fin's Barrowman model, whose only + control is ``active``. Returns ------- @@ -467,14 +474,26 @@ def compute_forces_and_moments( x, y and z axes and the moments ``(M1, M2, M3)`` about them, taken about the rocket's center of dry mass. """ - R1, R2, R3, M1, M2, M3 = 0, 0, 0, 0, 0, 0 - - # stream velocity in fin frame - stream_velocity_f = self._rotation_body_to_fin @ stream_velocity + return self._forces_in_frame( + stream_velocity, + stream_speed, + stream_mach, + rho, + cp, + omega, + self._rotation_body_to_fin, + self._rotation_fin_to_body, + self.cant_angle_rad, + ) + def _normal_force( + self, stream_velocity, stream_speed, stream_mach, rho, rotation_body_to_fin + ): + """The force on the fin along its own ``x`` axis, in N, from the air it + meets: lift slope times the angle the air makes with the fin.""" + stream_velocity_f = rotation_body_to_fin @ stream_velocity attack_angle = np.arctan2(stream_velocity_f[0], stream_velocity_f[2]) - # Force in the X direction of the fin - X = ( + return ( 0.5 * rho * stream_speed**2 @@ -482,8 +501,27 @@ def compute_forces_and_moments( * self.clalpha.get_value_opt(stream_mach) * attack_angle ) + + def _forces_in_frame( + self, + stream_velocity, + stream_speed, + stream_mach, + rho, + cp, + omega, + rotation_body_to_fin, + rotation_fin_to_body, + cant_angle_rad, + ): + """The fin's forces and moments, as in :meth:`compute_forces_and_moments`, + with the fin turned by ``cant_angle_rad`` through the given rotations. + ``ControlFins`` calls it with each fin's deflection.""" + X = self._normal_force( + stream_velocity, stream_speed, stream_mach, rho, rotation_body_to_fin + ) # Force in body frame - R1, R2, R3 = self._rotation_fin_to_body @ Vector([X, 0, 0]) + R1, R2, R3 = rotation_fin_to_body @ Vector([X, 0, 0]) # Moments M1, M2, M3 = cp ^ Vector([R1, R2, R3]) # Apply roll interference factor, disregarding lift interference factor @@ -495,27 +533,36 @@ def compute_forces_and_moments( * self.reference_area * (self.reference_length) ** 2 * self._cld_omega.get_value_opt(stream_mach) - * math.cos(self.cant_angle_rad) + * math.cos(cant_angle_rad) * omega[2] # omega3 / 2 ) M3 += M3_damping return R1, R2, R3, M1, M2, M3 - def _compute_leading_edge_position(self, position, _csys): - """Computes the position of the fin leading edge in a rocket's user, - given its position in a rocket.""" + def _cant_shift( + self, cant_angle_rad, rotation_fin_to_body_uncanted, hinge_position=0.5 + ): + """How far turning the fin by ``cant_angle_rad`` about its hinge line, at + ``hinge_position`` of the root chord from the leading edge, moves its + leading edge, in the body frame.""" # Point from deflection from cant angle in the plane perpendicular to # the fuselage where the fin is located in the fin frame + hinge = hinge_position * self.root_chord p = Vector( [ - -self.root_chord / 2 * np.sin(self.cant_angle_rad), + -hinge * np.sin(cant_angle_rad), 0, - self.root_chord / 2 * (1 - np.cos(self.cant_angle_rad)), + hinge * (1 - np.cos(cant_angle_rad)), ] ) # Rotate the point to the body frame orientation - p = self._rotation_fin_to_body_uncanted @ p + return rotation_fin_to_body_uncanted @ p + + def _compute_leading_edge_position(self, position, _csys): + """Computes the position of the fin leading edge in a rocket's user, + given its position in a rocket.""" + p = self._cant_shift(self.cant_angle_rad, self._rotation_fin_to_body_uncanted) # Rotate the point to the user-defined coordinate system p = Vector([p.x * _csys, p.y, p.z * _csys]) @@ -528,11 +575,7 @@ def _compute_leading_edge_position(self, position, _csys): position = Vector(position) else: position = Vector( - [ - -self.rocket_radius * math.sin(self.angular_position_rad) * _csys, - self.rocket_radius * math.cos(self.angular_position_rad), - position, - ] + point_around(position, self.angular_position, self.rocket_radius, _csys) ) # Translate the position of the fin leading edge to the position of the diff --git a/rocketpy/rocket/aero_surface/generic_surface.py b/rocketpy/rocket/aero_surface/generic_surface.py index 9b24cf111..c8066e5ba 100644 --- a/rocketpy/rocket/aero_surface/generic_surface.py +++ b/rocketpy/rocket/aero_surface/generic_surface.py @@ -1,7 +1,9 @@ import csv +from copy import deepcopy import numpy as np +from rocketpy.control.controllable import Controllable from rocketpy.mathutils import Function from rocketpy.mathutils.vector_matrix import Matrix, Vector from rocketpy.plots.aero_surface_plots import _GenericSurfacePlots @@ -14,13 +16,14 @@ _wind_to_body_coefficients, ) from rocketpy.rocket.aero_surface.aero_coefficient import ( + BASE_INDEPENDENT_VARS, SOURCE_ONLY_NAMES, AeroCoefficient, build_independent_vars, ) -class GenericSurface: +class GenericSurface(Controllable): """An aerodynamic surface of the rocket, defined by its force and moment coefficients. @@ -56,6 +59,15 @@ class GenericSurface: The motor phase the surface produces force in, as given. GenericSurface.active : bool Whether the surface starts each flight switched on. + GenericSurface.controls : tuple of str + Names of the controls the coefficients read, such as + ``("deflection",)``. Empty for a surface without controls. + GenericSurface.control_defaults : dict + Value of each control at the start of every flight, and the value + used outside a flight (for the stability margin, for instance). + GenericSurface.control_limits : dict + ``(low, high)`` of each control, or ``None`` for no limits. A value + written outside them is moved to the nearest limit. GenericSurface.force_convention : str Frame the force coefficients were given in: ``"body"`` or ``"wind"``. GenericSurface.independent_vars : list of str @@ -124,9 +136,13 @@ class GenericSurface: # Body-frame coefficients that were given in the plane of the wind (against # the total angle of attack) and split between the pitch and yaw planes _wind_plane_names = frozenset() - # Mach numbers at which a coefficient in the plane of the wind is checked to vanish at + # Mach numbers at which a coefficient in the plane of the wind is checked + # to vanish at # zero total angle of attack _ZERO_ANGLE_MACHS = (0.0, 0.3, 0.9, 2.0) + # The most a coefficient in the plane of the wind may be at zero total angle + # of attack: CFD and wind tunnel tables carry small residuals there + _ZERO_ANGLE_TOLERANCE = 1e-3 # Step of the numerical stability slopes, in radians _SLOPE_STEP = 1e-6 # Coefficients that have a direction across the rocket's axis. Given against @@ -139,7 +155,7 @@ class GenericSurface: # Rate derivatives, such as ``cm_q``: the reduced rate each suffix multiplies _RATE_DERIVATIVES = {"p": "roll_rate", "q": "pitch_rate", "r": "yaw_rate"} - def __init__( + def __init__( # pylint: disable=too-many-arguments self, reference_area, reference_length, @@ -153,6 +169,9 @@ def __init__( force_convention=None, active_during="always", active=True, + controls=(), + control_defaults=None, + control_limits=None, ): """Create an aerodynamic surface from its aerodynamic coefficients. @@ -181,8 +200,12 @@ def __init__( - A rate derivative, to add damping: a body-frame coefficient's name followed by ``_p``, ``_q`` or ``_r`` (roll, pitch or yaw rate), such as ``cm_q``. It is multiplied by the reduced rate and added - to the coefficient, so damping is a negative number (see - :ref:`generic_surface_damping`). + to the coefficient, so damping is a negative number. The flight + already moves a surface through the air as the rocket rotates, + so a surface away from the center of dry mass damps through its + own slope and lever arm. A whole-vehicle dataset, whose + derivatives include the lever arms, belongs at the center of + dry mass (see :ref:`generic_surface_damping`). Each coefficient can depend on these variables: @@ -295,9 +318,28 @@ def __init__( Whether the surface starts each flight switched on. Default is ``True``. Use ``False`` for a surface that only appears later in the flight, and switch it on from an event with - ``context.event.commands.activate_surface(surface)``. A surface + ``context.commands.activate_surface(surface)``. A surface that is on from the start is switched off the same way, with ``deactivate_surface``. + controls : iterable of str, optional + Names of controls the coefficients depend on, such as a canard + deflection, set by a controller during the flight. Each name + becomes one more variable the coefficients can use, after the + variables above and in this order, for example + ``controls=("deflection",)`` with + ``{"cl": lambda mach, deflection: 0.5 * deflection}``. Default is + no controls. + control_defaults : dict, optional + The value of each control at the start of every flight, by name, + for example ``{"deflection": 0.0}``. It is also the value used + outside a flight, such as for the stability margin. A control left + out starts at 0. Default is ``None``, every control at 0. + control_limits : dict, optional + The range each control can take, as ``(low, high)`` by name, for + example ``{"deflection": (-0.3, 0.3)}``: the range the mechanism + can reach. A value written outside it is moved to the nearest + limit. A control left out has no limits. Default is ``None``, no + limits. Raises ------ @@ -308,20 +350,17 @@ def __init__( If a coefficient name, a variable name, ``force_convention`` or ``active_during`` is not one of the accepted values, if wind-frame and body-frame force coefficients are mixed without a - ``force_convention``, or if a coefficient given against the total - angle of attack breaks the rules above. + ``force_convention``, if a coefficient given against the total + angle of attack breaks the rules above, or if a control name is + not a valid name, is repeated or is one of the variables above. See Also -------- :ref:`genericsurfaces` """ - # Externally-supplied axes (e.g. control deflections). Subclasses set - # this before ``super().__init__``. Defaults to none for plain surfaces. - self.control_variables = getattr(self, "control_variables", ()) - # Ordered independent variables accepted by every coefficient: the seven - # base axes, plus any ``control_variables`` - self.independent_vars = build_independent_vars(self.control_variables) + super().__init__(name, controls, control_defaults, control_limits) + self.independent_vars = build_independent_vars(self._control_axes) self.reference_area = reference_area self.reference_length = reference_length @@ -329,7 +368,6 @@ def __init__( reference_length if reynolds_length is None else reynolds_length ) self._set_center_of_pressure(center_of_pressure) - self.name = name self.active_during = self._validate_active_during(active_during) self.active = bool(active) @@ -347,6 +385,44 @@ def __init__( self.prints = _GenericSurfacePrints(self) self.plots = _GenericSurfacePlots(self) + def __deepcopy__(self, memo): + """Return a deep copy of the surface whose coefficients read the copy. + + A function is not copied by ``deepcopy``, so a coefficient computed + from the surface it belongs to would go on reading this surface from + the copy. The copy rebuilds those (see :meth:`_bind_coefficients`). + """ + copied = type(self).__new__(type(self)) + memo[id(self)] = copied + for key, value in self.__dict__.items(): + copied.__dict__[key] = deepcopy(value, memo) + copied._bind_coefficients() + return copied + + def _bind_coefficients(self): + """Rebuild the coefficients computed from the surface itself, so that + they read this surface. Called on a deep copy. Nothing to do here: the + coefficients of a generic surface are the data it was given.""" + + def _on_rocket_of(self, flight): + """Return this surface as the rocket of ``flight`` holds it: the same + object, or the surface of the same kind and name when the rocket was + copied. + + Raises + ------ + ValueError + If the surface is not on the flight's rocket. + """ + surfaces = [surface for surface, _ in flight.rocket.aerodynamic_surfaces] + same = [s for s in surfaces if s is self] + named = [ + s for s in surfaces if isinstance(s, type(self)) and s.name == self.name + ] + if not same and not named: + raise ValueError(f"{self.name} is not on the rocket of this flight.") + return (same or named)[0] + def _default_surface_rotation(self): """Rotation from the surface-local frame to the body frame. It is applied to the :attr:`force_application_point` when the rocket locates each @@ -382,7 +458,9 @@ def _set_center_of_pressure(self, value): f"{value!r}." ) from exc numeric = isinstance(z, (int, float, np.number)) - if hasattr(self, "cm") and (not numeric or getattr(self, "_xcp", None)): + built = hasattr(self, "cm") + varies_with_mach = not numeric or getattr(self, "_xcp", None) is not None + if built and varies_with_mach: raise ValueError( "A center of pressure that varies with Mach is folded into the " "moment coefficients when the surface is built: create a new " @@ -393,7 +471,7 @@ def _set_center_of_pressure(self, value): if numeric else AeroCoefficient( z, - control_variables=getattr(self, "control_variables", ()), + control_variables=self._control_axes, name="center_of_pressure", single_var="mach", ) @@ -402,6 +480,33 @@ def _set_center_of_pressure(self, value): self.cpx, self.cpy, self.cpz = x, y, 0.0 if xcp else z self.cp = (self.cpx, self.cpy, self.cpz) + def _set_controls(self, controls, defaults, limits): + """Check and store the controls the coefficients read. A control + cannot share its name with a flow variable.""" + # One name given alone is one control + controls = (controls,) if isinstance(controls, str) else tuple(controls) + flow_variables = {*BASE_INDEPENDENT_VARS, *SOURCE_ONLY_NAMES} + for control in controls: + if isinstance(control, str) and control in flow_variables: + raise ValueError( + f"'{self.name}' cannot have a control named '{control}': it " + "is one of the flow variables." + ) + super()._set_controls(controls, defaults, limits) + + @property + def _control_axes(self): + """The controls the coefficients read, in order. Empty while the + surface is being built and has none yet.""" + return getattr(self, "controls", ()) + + def _reference_arguments(self): + """The arguments of every coefficient at zero angles, Mach number, + Reynolds number and rates, with the controls at their defaults, as a + list to set the variables of interest in. What a surface is evaluated + at outside a flight.""" + return [0.0] * len(BASE_INDEPENDENT_VARS) + list(self._default_control_values()) + def is_active(self, t, flight): """Return whether the surface produces force at time ``t`` of a flight. @@ -491,7 +596,7 @@ def _evaluate_stability_derivatives(self): A plain generic surface recovers each derivative from its body-frame force and moment coefficients by numerical differentiation about one point: ``alpha = beta = 0``, Reynolds number 0, every rotation rate 0 - and every control at 0, as a function of Mach. A coefficient that + and every control at its default, as a function of Mach. A coefficient that changes with the Reynolds number is therefore linearized at Reynolds 0 (the edge of its table, when tabulated). The Barrowman surfaces instead set these four attributes directly from geometry and only reuse @@ -509,9 +614,13 @@ def _evaluate_stability_derivatives(self): # whole surface is read that way. step = self._SLOPE_STEP one_sided = bool(self._wind_plane_names) + # The slopes are taken once, with the controls at their defaults, so + # the margin of a surface whose slope depends on a control is the one + # at the default (issue_stability_margin_vs_controls.md). + defaults = dict(zip(self._control_axes, self._default_control_values())) def slope(coefficient, angle): - at = {angle: step} if one_sided else None + at = {**defaults, angle: step} if one_sided else (defaults or None) return coefficient.slope(angle, "mach", at=at, dx=step) for name, angle in ( @@ -527,7 +636,7 @@ def slope(coefficient, angle): AeroCoefficient( slope(getattr(self, name), angle), depends_on=("mach",), - control_variables=self.control_variables, + control_variables=self._control_axes, name=slope_name, ), ) @@ -562,10 +671,13 @@ def center_z(mach): application_z = ( self._rotation_surface_to_body @ self.force_application_point )[2] - slope = force_coeff.get_value_opt(0.0, 0.0, mach, 0.0, 0.0, 0.0, 0.0) + # At zero angles and rates, the controls at their defaults + args = (0.0, 0.0, mach, 0.0, 0.0, 0.0, 0.0) + args += self._default_control_values() + slope = force_coeff.get_value_opt(*args) if slope == 0: return application_z - moment = moment_coeff.get_value_opt(0.0, 0.0, mach, 0.0, 0.0, 0.0, 0.0) + moment = moment_coeff.get_value_opt(*args) return application_z + moment / slope * self.reference_length return Function( @@ -617,20 +729,19 @@ def _as_coefficient(self, source, name, single_var=None): asked for under that coefficient's name. ``single_var`` names the variable of a one-column table or headerless file that carries no name. """ + # A setting is either one value for every coefficient or a dict by name - extrapolation, interpolation = ( - option.get(name) if isinstance(option, dict) else option - for option in (self._extrapolation, self._interpolation) - ) - coefficient = AeroCoefficient( + def setting(option): + return option.get(name) if isinstance(option, dict) else option + + return AeroCoefficient( source, - control_variables=self.control_variables, + control_variables=self._control_axes, name=name, - extrapolation=extrapolation, - interpolation=interpolation, + extrapolation=setting(self._extrapolation), + interpolation=setting(self._interpolation), single_var=single_var, ) - return coefficient @staticmethod def _is_in_wind_plane(coefficient): @@ -763,17 +874,20 @@ def _check_zero_at_zero_total_angle(self, coefficient, name): the way down to zero. Left in, the body-frame force would flip sign every time the angle crosses zero, and the stability slope, taken over a tiny step from zero, would come out as that jump divided by the step - (1e5 for a table starting at 2 degrees). + (1e5 for a table starting at 2 degrees). A residual within + ``_ZERO_ANGLE_TOLERANCE``, as measured and computed data carry, is let + through: its flip is a force too small to matter. """ args = [0.0] * len(self.independent_vars) machs = self._ZERO_ANGLE_MACHS if "mach" in coefficient.depends_on else (0.0,) for mach in machs: args[2] = mach value = coefficient(*args) - if abs(value) > 1e-9: + if abs(value) > self._ZERO_ANGLE_TOLERANCE: raise ValueError( f"{name} is {value:.4g} at zero total angle of attack (Mach " - f"{mach:g}) but must be zero there: with no crossflow the " + f"{mach:g}) but must be zero there (within " + f"{self._ZERO_ANGLE_TOLERANCE:g}): with no crossflow the " "force has no direction to point in. Give 0 at " "alpha_total = 0; a table must start at 0 degrees, since its " "first value is held down to zero otherwise." @@ -837,7 +951,6 @@ def _build_coefficients( f"{type(coefficients).__name__}. For one file holding several " f"coefficients use {type(self).__name__}.from_csv." ) - default_coefficients = self._get_default_coefficients() self.force_convention = self._resolve_force_convention( coefficients, force_convention ) @@ -855,8 +968,8 @@ def _build_coefficients( if self.force_convention == "wind": coefficients = self._wind_input_to_body(coefficients) coefficients = self._complete_body_coefficients(coefficients) - self._check_coefficients(coefficients, default_coefficients) - coefficients = {**default_coefficients, **coefficients} + self._check_coefficients(coefficients) + coefficients = {**self._get_default_coefficients(), **coefficients} # Lets the flight skip the Reynolds number when no coefficient uses it self._needs_reynolds = False @@ -881,8 +994,11 @@ def _complete_body_coefficients(self, coefficients): rate derivative to its coefficient, ``cm + cm_q * pitch_rate``. (The linear surface keeps its derivatives and fills in its yaw plane.)""" coefficients = dict(coefficients) - for name in [name for name in coefficients if self._rate_of(name)]: - target, rate = name.partition("_")[0], self._rate_of(name) + derivatives = [ + (name, rate) for name in coefficients if (rate := self._rate_of(name)) + ] + for name, rate in derivatives: + target = name.partition("_")[0] derivative = coefficients.pop(name) base = self._as_coefficient(coefficients.get(target, 0), target) if rate in base.depends_on: @@ -935,32 +1051,44 @@ def total(*args): _as_function(total, used, moment.name), moment.name ) + # Each moment with the force in its plane. The linear surface holds + # derivatives too, "cm_alpha" with "cN_alpha": the suffix is kept + moment_to_force = {"cm": "cN", "cn": "cY"} for name in self._get_default_coefficients(): - force_name = {"cm": "cN", "cn": "cY"}.get(name[:2]) - if force_name is not None: - force = getattr(self, force_name + name[2:]) - if not force.is_zero: - setattr(self, name, carried(getattr(self, name), force)) + prefix, _, suffix = name.partition("_") + if prefix not in moment_to_force: + continue + force_name = moment_to_force[prefix] + (f"_{suffix}" if suffix else "") + force = getattr(self, force_name) + if not force.is_zero: + setattr(self, name, carried(getattr(self, name), force)) @classmethod def _get_default_coefficients(cls): """The coefficients the surface holds, each with its default value.""" return {"cN": 0, "cY": 0, "cA": 0, "cm": 0, "cn": 0, "cl": 0} - def _check_coefficients(self, input_coefficients, default_coefficients): + def _check_coefficients(self, input_coefficients, allowed=None): """Raise a ``ValueError`` for a coefficient name the surface does not - have.""" - invalid_keys = set(input_coefficients) - set(default_coefficients) + have. ``allowed`` is the set of names accepted; ``None`` (the default) + means the coefficients the surface holds.""" + if allowed is None: + allowed = self._get_default_coefficients() + invalid_keys = set(input_coefficients) - set(allowed) if invalid_keys: raise ValueError( f"Invalid coefficient name(s) used in key(s): {', '.join(invalid_keys)}. " "Check the documentation for valid names." ) - def _coefficient_arguments(self, *state): + def _coefficient_arguments(self, *state, controls=None): """The arguments every coefficient is called with: the seven flow - variables in ``state``, plus any a subclass adds.""" - return state + variables in ``state``, then the value of each control. ``controls`` + holds those values, from the flight's control inputs; ``None`` uses + the defaults, as outside a flight.""" + if controls is None: + controls = self._default_control_values() + return (*state, *controls) def compute_forces_and_moments( self, @@ -973,6 +1101,7 @@ def compute_forces_and_moments( density, dynamic_viscosity, z, + controls=None, ): """Computes the forces and moments acting on the aerodynamic surface. Used in each time step of the simulation. This method is valid for @@ -1001,6 +1130,10 @@ def compute_forces_and_moments( z : float Altitude of the surface's center of pressure above sea level, in m, used to evaluate ``density`` and ``dynamic_viscosity``. + controls : sequence of float, optional + The value of each of the surface's controls, in the order of + :attr:`controls`, as the flight holds them. ``None`` (the default) + uses :attr:`control_defaults`, the values outside a flight. Returns ------- @@ -1046,6 +1179,7 @@ def compute_forces_and_moments( omega[0] * reduced_rate_factor, omega[1] * reduced_rate_factor, omega[2] * reduced_rate_factor, + controls=controls, ) force = 0.5 * rho * stream_speed**2 * self.reference_area moment = force * self.reference_length @@ -1068,10 +1202,14 @@ def _input_coefficient_names(cls): return set(cls._get_default_coefficients()) | set(cls._WIND_FORCE_NAMES) @classmethod - def _input_variable_names(cls, **kwargs): # pylint: disable=unused-argument + def _input_variable_names(cls, **kwargs): """Every name a variable can be given under, for a surface built with - the constructor arguments ``kwargs``.""" - return [*build_independent_vars(), *SOURCE_ONLY_NAMES] + the constructor arguments ``kwargs``: the flow variables and the + surface's controls.""" + return [ + *build_independent_vars(kwargs.get("controls", ())), + *SOURCE_ONLY_NAMES, + ] @classmethod def from_csv( @@ -1111,8 +1249,8 @@ def from_csv( ``alpha_deg`` and ``beta_deg`` (degrees), ``alpha_total`` and ``phi`` (total angle of attack and roll angle of the wind, also with ``_deg``), ``mach``, ``reynolds``, - ``pitch_rate``, ``yaw_rate`` and ``roll_rate``, plus the control - names of a controllable surface. The coefficient names are those of + ``pitch_rate``, ``yaw_rate`` and ``roll_rate``, plus the names in + ``controls`` when it is given. The coefficient names are those of the class, such as ``cN``, ``cY``, ``cA`` (or ``cL``, ``cQ``, ``cD``), ``cm``, ``cn`` and ``cl`` for a :class:`GenericSurface`. Names are case sensitive: ``cN`` is the normal force and ``cn`` the @@ -1196,6 +1334,9 @@ def _arguments_from_dict(cls, data): "force_convention": data.get("force_convention", "body"), "active_during": data.get("active_during", "always"), "active": data.get("active", True), + "controls": tuple(data.get("controls", ())), + "control_defaults": data.get("control_defaults"), + "control_limits": data.get("control_limits"), } return arguments @@ -1221,7 +1362,7 @@ def to_dict(self, include_outputs=False, **kwargs): # pylint: disable=unused-ar The arguments needed to rebuild the surface with :meth:`from_dict`. """ x, y, z = self.center_of_pressure - return { + data = { "reference_area": self.reference_area, "reference_length": self.reference_length, "reynolds_length": self.reynolds_length, @@ -1233,6 +1374,9 @@ def to_dict(self, include_outputs=False, **kwargs): # pylint: disable=unused-ar "active_during": self.active_during, "active": self.active, } + if self._control_axes: + data.update(self._control_settings()) + return data @classmethod def from_dict(cls, data): diff --git a/rocketpy/rocket/aero_surface/linear_generic_surface.py b/rocketpy/rocket/aero_surface/linear_generic_surface.py index 4e2592c67..4990a8e66 100644 --- a/rocketpy/rocket/aero_surface/linear_generic_surface.py +++ b/rocketpy/rocket/aero_surface/linear_generic_surface.py @@ -115,7 +115,7 @@ class LinearGenericSurface(GenericSurface): # Force prefix in the body frame -> in the wind frame _BODY_TO_WIND_PREFIX = {"cN": "cL", "cY": "cQ", "cA": "cD"} - def __init__( + def __init__( # pylint: disable=too-many-arguments self, reference_area, reference_length, @@ -130,6 +130,9 @@ def __init__( active_during="always", active=True, axisymmetric=False, + controls=(), + control_defaults=None, + control_limits=None, ): """Create a linear aerodynamic surface from its coefficient derivatives. @@ -271,7 +274,7 @@ def __init__( Whether the surface starts each flight switched on. Default is ``True``. Use ``False`` for a surface that only appears later in the flight, and switch it on from an event with - ``context.event.commands.activate_surface(surface)``. A surface + ``context.commands.activate_surface(surface)``. A surface that is on from the start is switched off the same way, with ``deactivate_surface``. axisymmetric : bool, optional @@ -292,6 +295,20 @@ def __init__( Default is ``False``: the two planes are used as given, and a plane without derivatives produces no force. + controls : iterable of str, optional + Names of controls the derivatives depend on, such as a canard + deflection, set by a controller during the flight. Each name becomes + one more variable the derivatives can use, for example + ``controls=("deflection",)`` with + ``{"cl_0": lambda mach, deflection: 0.5 * deflection}``. Default is + no controls. + control_defaults : dict, optional + The value of each control at the start of every flight, and outside + a flight, by name. A control left out starts at 0. Default ``None``. + control_limits : dict, optional + The range of each control, as ``(low, high)`` by name. A control + left out has no limits. A value written outside them is moved to + the nearest limit. Default ``None``. Raises ------ @@ -324,6 +341,9 @@ def __init__( force_convention=force_convention, active_during=active_during, active=active, + controls=controls, + control_defaults=control_defaults, + control_limits=control_limits, ) self.compute_all_coefficients() @@ -370,7 +390,7 @@ def _force_frames_present(self, coefficients): has_body = bool(prefixes & set(self._BODY_FORCE_NAMES)) return has_wind, has_body - def _check_coefficients(self, input_coefficients, default_coefficients): + def _check_coefficients(self, input_coefficients, allowed=None): """Raise a ``ValueError`` for a name that is not one of the derivatives. On top of the generic check, a coefficient value such as ``cN`` gets a hint @@ -386,7 +406,7 @@ def _check_coefficients(self, input_coefficients, default_coefficients): "values. For a coefficient given against the angle, use " "GenericSurface." ) - super()._check_coefficients(input_coefficients, default_coefficients) + super()._check_coefficients(input_coefficients, allowed) def _as_coefficient(self, source, name, single_var=None): """Wrap a derivative as an :class:`AeroCoefficient`. diff --git a/rocketpy/rocket/parachute.py b/rocketpy/rocket/parachute.py index 02ab09677..73c70895e 100644 --- a/rocketpy/rocket/parachute.py +++ b/rocketpy/rocket/parachute.py @@ -33,7 +33,7 @@ class Parachute: so ``context`` holds the same values as any event trigger receives, including ``context.state``, ``context.pressure``, ``context.height_agl``, ``context.sensors``, ``context.time``, - ``context.flight``, ``context.rocket`` and ``context.environment``. + ``context.rocket`` and ``context.environment``. See :ref:`triggerdetails` for how to write a trigger and the values it can read. The function is called according to the specified sampling rate. @@ -150,9 +150,9 @@ def __init__( - A callable function ``trigger(context)`` that returns ``True`` when the parachute ejection system should be triggered and ``False`` otherwise. ``context`` holds the simulation values - at the moment of the check, read as ``context.pressure`` (Pa), - ``context.height_agl`` (m), ``context.state.vz`` (m/s), - ``context.previous_state`` and so on. + at the moment of the check, read as + ``context.pressure`` (Pa), ``context.height_agl`` (m), + ``context.state.vz`` (m/s), ``context.previous_state`` and so on. See :ref:`triggerdetails` for how to write a trigger and the values it can read. The legacy form ``trigger(p, h, y[, sensors])``, taking the @@ -254,7 +254,7 @@ def __init_noise(self, noise): "The `noise` parameter on Parachute is deprecated and will be " "removed in v1.16. Use a Sensor (e.g. a Barometer) with " "built-in noise instead, and read the noisy measurement via " - "`context.sensors_by_name` in your trigger function.", + "`context.sensors` in your trigger function.", # FutureWarning, not DeprecationWarning: Python hides the # latter unless it points at the user's own script, which it # does not when the parachute comes from Rocket.add_parachute. @@ -281,7 +281,7 @@ def _noisy_pressure_and_height(self, context): self._last_noise = alpha * self._last_noise + beta * self._rng.normal( self.noise_bias, self.noise_deviation ) - pressure = context["pressure"] + self._last_noise + pressure = context.pressure + self._last_noise environment = context["environment"] height = environment.barometric_height.get_value_opt(pressure) return pressure, height - environment.elevation @@ -384,19 +384,19 @@ def trigger_event_wrapper(context): if self._has_noise: pressure, height = self._noisy_pressure_and_height(context) else: - pressure, height = context["pressure"], context["height_agl"] + pressure, height = context.pressure, context["height_agl"] return self.triggerfunc( - pressure, height, context["canonical_state"], context["sensors"] + pressure, + height, + context["canonical_state"], + [sensor for sensor, _ in context["sensors"].values()], ) else: trigger_event_wrapper = self.triggerfunc def trigger_callback(context): - time = context["time"] - flight = context["flight"] - - flight.parachute_events.append([time, self]) - + # The flight notes the deployment in its parachute_events when it + # applies this command context["event"].commands.set_dynamics(PARACHUTE_DYNAMICS, parachute=self) context["event"].commands.start_flight_phase( f"{self.name}_parachute_descent", diff --git a/rocketpy/rocket/rocket.py b/rocketpy/rocket/rocket.py index 9a5e3f8d0..276cdc474 100644 --- a/rocketpy/rocket/rocket.py +++ b/rocketpy/rocket/rocket.py @@ -1,13 +1,19 @@ # pylint: disable=too-many-lines -import inspect -import math import warnings from contextlib import contextmanager from collections.abc import Iterable import numpy as np -from rocketpy.control.controller import _Controller +from rocketpy.control._helpers import initial_controls, was_loaded +from rocketpy.control._legacy import _legacy_controller +from rocketpy.control.continuous_controller import ContinuousController +from rocketpy.control.controllable import ( + Controllable, + ForceEffector, + ThrustEffector, +) +from rocketpy.control.controller import Controller from rocketpy.mathutils.function import Function from rocketpy.mathutils.vector_matrix import Matrix, Vector from rocketpy.motors.empty_motor import EmptyMotor @@ -31,7 +37,6 @@ ) from rocketpy.rocket.aero_surface import ( AirBrakes, - ControllableGenericSurface, EllipticalFins, Fin, Fins, @@ -46,10 +51,11 @@ from rocketpy.rocket.aero_surface.linear_generic_surface import LinearGenericSurface from rocketpy.rocket.components import Components, position_vector from rocketpy.rocket.parachute import Parachute +from rocketpy.simulation.events.views import output_events from rocketpy.tools import ( deprecated, - find_obj_from_hash, parallel_axis_theorem_from_com, + point_around, ) @@ -149,9 +155,13 @@ class Rocket: Rocket.parachutes : list Collection of parachutes of the rocket. Rocket.air_brakes : list - Collection of air brakes of the rocket. - Rocket._controllers : list - Collection of controllers of the rocket. + The air brakes among the aerodynamic surfaces. + Rocket.controllers : tuple + Controllers of the rocket, added with :meth:`add_controller` or + :meth:`add_air_brakes`. Read-only. + Rocket.continuous_controllers : tuple + The rocket's :class:`rocketpy.ContinuousController` objects, added with + :meth:`add_controller`. Read-only. Rocket.aerodynamic_center : Function Position of the rocket's aerodynamic center, in meters, as a function of Mach number, in the user defined rocket reference system. It is the @@ -221,6 +231,10 @@ class Rocket: Rocket.nozzle_to_cdm : float Distance between the nozzle exit and the rocket's center of dry mass position, in meters. + Rocket.nozzle_exit : Vector + Position, in meters, of the motor's nozzle exit in the rocket's body + frame, from the rocket's center of dry mass: on the rocket's axis, + moved by the thrust eccentricity. Rocket.nozzle_gyration_tensor: Matrix Matrix representing the nozzle gyration tensor. Rocket.center_of_propellant_position : Function @@ -392,11 +406,22 @@ def __init__( # pylint: disable=too-many-statements # Parachute, Aerodynamic, Buttons, Controllers, Sensor data initialization self.parachutes = [] self._controllers = [] - self.air_brakes = [] + self._continuous_controllers = [] + self.effectors = Components() self.sensors = Components() self.sensors_by_name = {} self.aerodynamic_surfaces = Components() + # The surfaces added without a position: they act at the center of dry + # mass, and the position stored for them is moved with it + self._surfaces_at_center_of_dry_mass = set() self.surfaces_cp_to_cdm = {} + # What the equations of motion read of the effectors (see + # _evaluate_effectors): the ones that change the thrust, the ones that + # push the rocket, and where each was placed, in the body frame from + # the center of dry mass, or None for one placed nowhere + self._thrust_effectors = () + self._force_effectors = () + self._effector_points = {} # What the values derived from the surfaces were last built for (see # _refresh_aerodynamics, _refresh_aerodynamic_center, _refresh_margins) self._lever_arms_stamp = None @@ -627,6 +652,117 @@ def tails(self): """A list with all the tails currently added to the rocket""" return self.aerodynamic_surfaces.get_by_type(Tail) + @property + def air_brakes(self): + """A list with all the air brakes currently added to the rocket.""" + return self.aerodynamic_surfaces.get_by_type(AirBrakes) + + @property + def controllables(self): + """The parts of the rocket a controller can move: the aerodynamic + surfaces that have controls (air brakes, control fins, a surface built + with ``controls``), then the effectors that have controls, each in the + order they were added. + + A flight builds its control inputs from these, one per control of + each. See :attr:`control_names`. + + Returns + ------- + tuple + """ + surfaces = (surface for surface, _ in self.aerodynamic_surfaces) + return tuple( + part + for part in (*surfaces, *self.effectors.get_components()) + if part.controls + ) + + @property + def controllers(self): + """The controllers of the rocket, in the order they were added, which + run in every flight of the rocket. Read-only: add one with + :meth:`add_controller` (:meth:`add_air_brakes` adds its own). + + Returns + ------- + tuple of rocketpy.Controller + """ + return tuple(self._controllers) + + @property + def continuous_controllers(self): + """The continuous controllers of the rocket, in the order they were + added: the control laws evaluated inside the equations of motion at + every instant. Read-only: add one with :meth:`add_controller`. + + Returns + ------- + tuple of rocketpy.ContinuousController + """ + return tuple(self._continuous_controllers) + + @property + def control_names(self): + """Names of the control inputs the next flight of this rocket will + have, in order. Read-only. + + A control input is ``.``: the controllable's name in + snake_case, then the name of the control, one per control of each + controllable that has controls, such as ``("canards.deflection", + "air_brakes.deployment_level")``. A rocket with no controls has none. + A controller writes them as + ``context.controls.air_brakes.deployment_level = 0.5``. + + Returns + ------- + tuple of str + """ + return tuple(initial_controls(self.controllables)[0]) + + @property + def _parts_with_states(self): + """The parts a flight integrates along with the rocket: the aerodynamic + surfaces and effectors with states of their own, or with an + ``actual_controls`` of their own, in the order they were added. The + continuous controllers are not among them; see + ``_continuous_controllers``.""" + surfaces = (surface for surface, _ in self.aerodynamic_surfaces) + return tuple( + part + for part in (*surfaces, *self.effectors.get_components()) + if part._acts_on_its_own() + ) + + def _check_new_controllables(self, *controllables): + """Raise if one of ``controllables`` cannot be flown, or if their control + inputs or states could not be told apart from each other's and from those + of the rocket's other controllables. Called before + any of them is added, so a failed add leaves the rocket as it was.""" + for controllable in controllables: + if not isinstance(controllable, Controllable): + raise TypeError( + f"{controllable!r} cannot be added to the rocket: it is not one of " + "RocketPy's controllables. Use a RocketPy class, such as " + "ForceEffector or ThrustEffector built from a function." + ) + controllable._check_controls() + controllable._check_states() + initial_controls((*self.controllables, *controllables)) + # A flight integrates the controllables' states by name + owners = ( + *self._parts_with_states, + *self._continuous_controllers, + *controllables, + ) + names = [name for owner in owners for name in owner._state_names()] + repeated = sorted({name for name in names if names.count(name) > 1}) + if repeated: + raise ValueError( + f"Two controllables of the rocket would have a state named " + f"{repeated[0]!r}: give them different names." + ) + def evaluate_total_mass(self): """Calculates and returns the rocket's total mass. The total mass is defined as the sum of the motor mass with propellant and the @@ -728,8 +864,20 @@ def evaluate_center_of_dry_mass(self): self.center_of_mass_without_motor * self.mass + self.motor_center_of_dry_mass_position * self.motor.dry_mass ) / self.dry_mass + # A surface added without a position sits at the center of dry mass: + # its stored position, read by the stability analysis, the drawing and + # the file saved, moves with it + for surface in self._surfaces_at_center_of_dry_mass: + self.aerodynamic_surfaces.set_position( + surface, self.center_of_dry_mass_position + ) return self.center_of_dry_mass_position + def _is_at_center_of_dry_mass(self, surface): + """Whether ``surface`` was added to this rocket without a position, so + its force acts at the center of dry mass, wherever the motor puts it.""" + return surface in self._surfaces_at_center_of_dry_mass + def evaluate_reduced_mass(self): """Calculates and returns the rocket's total reduced mass. The reduced mass is defined as the product of the propellant mass and the rocket dry @@ -815,18 +963,23 @@ def _reading_surfaces(self, selection): def _refresh_aerodynamics(self): """Bring up to date what the simulation reads from the surfaces: each surface's center of pressure relative to the center of dry mass (for an - individual fin, its leading edge moves with the cant angle). Returns the - surfaces stamp.""" + individual fin, its leading edge moves with the cant angle), and where + each effector was placed. Returns the surfaces stamp.""" surfaces_stamp = self._surfaces_stamp() stamp = ( surfaces_stamp, self.center_of_dry_mass_position, self.cm_eccentricity_x, self.cm_eccentricity_y, + tuple( + (effector, None if position is None else tuple(position)) + for effector, position in self.effectors + ), ) if stamp != self._lever_arms_stamp: self._lever_arms_stamp = stamp self.evaluate_surfaces_cp_to_cdm() + self._evaluate_effectors() return surfaces_stamp def _refresh_aerodynamic_center(self): @@ -1379,6 +1532,46 @@ def evaluate_surfaces_cp_to_cdm(self): self.__evaluate_single_surface_cp_to_cdm(surface, position) return self.surfaces_cp_to_cdm + def _from_center_of_dry_mass(self, position): + """Return a point given in the user's coordinate system as the + equations of motion read it: in the body frame, from the center of dry + mass, which the center of mass eccentricity moves off the rocket's + axis.""" + return Vector( + [ + (position.x - self.cm_eccentricity_x) * self._csys, + (position.y - self.cm_eccentricity_y), + (position.z - self.center_of_dry_mass_position) * self._csys, + ] + ) + + def _evaluate_effectors(self): + """Store what the equations of motion read of the effectors. + + The effectors are split by what they do, each in the order they were + added: ``_thrust_effectors`` (the :class:`ThrustEffector`) and + ``_force_effectors`` (the :class:`ForceEffector`). An effector that is + both kinds is in each. + + ``_effector_points`` holds where each effector was placed (the + position given to :meth:`add_effector`), in the body frame from the + center of dry mass, or ``None`` for one placed nowhere, whose force + acts at the center of dry mass. + """ + effectors = self.effectors.get_components() + self._thrust_effectors = tuple( + effector for effector in effectors if isinstance(effector, ThrustEffector) + ) + self._force_effectors = tuple( + effector for effector in effectors if isinstance(effector, ForceEffector) + ) + self._effector_points = { + effector: None + if position is None + else self._from_center_of_dry_mass(position) + for effector, position in self.effectors + } + def _surface_origin(self, surface, position): """Where a surface's own frame sits, in the user's coordinate system: the position it was added at, except for an individual fin, whose frame @@ -1395,15 +1588,18 @@ def _surface_origin(self, surface, position): def __evaluate_single_surface_cp_to_cdm(self, surface, position): """Store where one surface applies its force, relative to the rocket's center of dry mass, in the body axes.""" + # Control fins turn a pitch or yaw command one way ahead of the center + # of dry mass and the other way behind it, so they are told where + # they sit + placed_at = getattr(surface, "_placed_at", None) + if self._is_at_center_of_dry_mass(surface): + self.surfaces_cp_to_cdm[surface] = Vector([0, 0, 0]) + if placed_at is not None: + placed_at(self.surfaces_cp_to_cdm[surface]) + return position = self._surface_origin(surface, position) # position of the surfaces coordinate system origin in body frame - pos_origin = Vector( - [ - (position.x - self.cm_eccentricity_x) * self._csys, - (position.y - self.cm_eccentricity_y), - (position.z - self.center_of_dry_mass_position) * self._csys, - ] - ) + pos_origin = self._from_center_of_dry_mass(position) # position of the force application point in body frame. Every surface # applies its resultant force at its center of pressure and transports # the moment geometrically; the surface-local application point is mapped @@ -1413,6 +1609,8 @@ def __evaluate_single_surface_cp_to_cdm(self, surface, position): + pos_origin ) self.surfaces_cp_to_cdm[surface] = pos + if placed_at is not None: + placed_at(pos) def evaluate_stability_margin(self): """Compute the stability margin of the rocket as a function of Mach @@ -1640,26 +1838,53 @@ def evaluate_nozzle_to_cdm(self): self.nozzle_to_cdm = ( -(self.nozzle_position - self.center_of_dry_mass_position) * self._csys ) + self.evaluate_nozzle_exit() return self.nozzle_to_cdm + def evaluate_nozzle_exit(self): + """Evaluates where the motor's nozzle exit is, in the rocket's body + frame (z along the rocket's axis, toward the nose), from the rocket's + center of dry mass: on the rocket's axis, moved by the thrust + eccentricity. Evaluated again whenever the nozzle's distance to the + center of dry mass or the thrust eccentricity changes. + + Returns + ------- + self.nozzle_exit : Vector + Position of the nozzle exit, in meters. + """ + self.nozzle_exit = Vector( + [ + self.thrust_eccentricity_x, + self.thrust_eccentricity_y, + -self.nozzle_to_cdm, + ] + ) + return self.nozzle_exit + def evaluate_nozzle_gyration_tensor(self): """Calculates and returns the nozzle gyration tensor relative to the - rocket's center of dry mass. The gyration tensor is saved and returned - in units of kg*m². + rocket's center of dry mass: the one of the nozzle exit, a disk at + ``nozzle_exit``, which the thrust eccentricity moves off the rocket's + axis. The gyration tensor is saved and returned in units of m². + Evaluated again whenever the nozzle exit changes. Returns ------- self.nozzle_gyration_tensor : Matrix Matrix containing the nozzle gyration tensor. """ + x, y, z = self.nozzle_exit S_noz_33 = 0.5 * self.motor.nozzle_radius**2 - S_noz_11 = S_noz_22 = 0.5 * S_noz_33 + self.nozzle_to_cdm**2 - S_noz_12, S_noz_13, S_noz_23 = 0, 0, 0 # Due to axis symmetry + S_noz_11 = 0.5 * S_noz_33 + y**2 + z**2 + S_noz_22 = 0.5 * S_noz_33 + x**2 + z**2 + # Zero for a nozzle on the rocket's axis + S_noz_12, S_noz_13, S_noz_23 = -x * y, -x * z, -y * z self.nozzle_gyration_tensor = Matrix( [ [S_noz_11, S_noz_12, S_noz_13], [S_noz_12, S_noz_22, S_noz_23], - [S_noz_13, S_noz_23, S_noz_33], + [S_noz_13, S_noz_23, S_noz_33 + x**2 + y**2], ] ) return self.nozzle_gyration_tensor @@ -1814,6 +2039,7 @@ def add_motor(self, motor, position): # pylint: disable=too-many-statements self.evaluate_reduced_mass() self.evaluate_thrust_to_weight() self.evaluate_surfaces_cp_to_cdm() + self._evaluate_effectors() self.evaluate_com_to_cdm_function() self.evaluate_nozzle_gyration_tensor() @@ -1821,12 +2047,22 @@ def __add_single_surface(self, surface, position): """Adds a single aerodynamic surface to the rocket. Makes checks for rail buttons case, and position type. """ + # Without a position, at the center of dry mass, wherever the motor + # puts it: the lever arm stays zero, and the position stored follows + # the center of dry mass (see evaluate_center_of_dry_mass) + at_center_of_dry_mass = position is None + if at_center_of_dry_mass: + position = self.center_of_dry_mass_position position = position_vector(position) if isinstance(surface, RailButtons): self.rail_buttons = Components() self.rail_buttons.add(surface, position) else: self.aerodynamic_surfaces.add(surface, position) + if at_center_of_dry_mass: + self._surfaces_at_center_of_dry_mass.add(surface) + else: + self._surfaces_at_center_of_dry_mass.discard(surface) self.__evaluate_single_surface_cp_to_cdm(surface, position) def add_surfaces(self, surfaces, positions): @@ -1839,13 +2075,18 @@ def add_surfaces(self, surfaces, positions): surfaces : list[GenericSurface], GenericSurface Aerodynamic surface to be added to the rocket. Can be a list of surfaces if more than one surface is to be added. - positions : int, float, tuple, list, Vector + positions : int, float, tuple, list, Vector, None Position(s) of the aerodynamic surface's reference point. Can be: - a single number (int or float) giving the z-coordinate along the rocket axis. - a sequence of three numbers (x, y, z) representing the full position in the user-defined coordinate system. + - ``None``: at the rocket's center of dry mass, following it if + the motor or the mass changes later (as in a Monte Carlo). For a + surface whose coefficients are already about the center of + mass, such as a whole-rocket model from CFD or a wind tunnel, so + its moments get no lever arm; also the air brakes' default. If passing multiple surfaces, provide a list of positions matching each surface in order. @@ -1884,11 +2125,19 @@ def add_surfaces(self, surfaces, positions): ) else: positions = [positions] * len(surfaces) - + # Every surface is checked before any is added + self._check_new_controllables(*surfaces) for surface, position in zip(surfaces, positions): self.__add_single_surface(surface, position) else: + self._check_new_controllables(surfaces) self.__add_single_surface(surfaces, positions) + # Air brakes whose curve is of the whole rocket are compared with the + # rocket's own drag, whichever way they were added + added = surfaces if isinstance(surfaces, Iterable) else (surfaces,) + for surface in added: + if isinstance(surface, AirBrakes) and surface.override_rocket_drag: + self._check_retracted_drag(surface) def add_full_body_aerodynamics(self, surfaces, position=None, overwrite=False): """Add a prebuilt full-body aerodynamic surface: the whole rocket @@ -1905,8 +2154,8 @@ def add_full_body_aerodynamics(self, surfaces, position=None, overwrite=False): - a :class:`GenericSurface`; - a :class:`LinearGenericSurface`; - - a :class:`ControllableGenericSurface` for coefficients that - also depend on control-deflection axes. + - a :class:`GenericSurface` built with ``controls``, for + coefficients that also depend on a control deflection. Reference the surface's coefficients to the rocket cross-section area and diameter (build it with ``reference_area=rocket.area`` and @@ -1924,24 +2173,22 @@ def add_full_body_aerodynamics(self, surfaces, position=None, overwrite=False): position : int, float, optional Position along the rocket's center axis (in the user coordinate system) where the surface's resultant force is applied and about - which its moment coefficients are taken. Defaults to the rocket's - center of dry mass at the time of the call, so add the motor first - (before that, it is the center of mass without the motor). + which its moment coefficients are taken. Default ``None``: the + rocket's center of dry mass, following it if the motor or the + mass changes later. overwrite : bool, optional If ``True``, make this the rocket's only aerodynamics: every aerodynamic surface already on the rocket is removed first, and both built-in drag curves (``power_on_drag`` and ``power_off_drag``) are - cleared. Default ``False`` (the model is added on top of the - existing aerodynamics). + cleared. Air brakes are kept, with their controller, and add their + drag to the model's. Default ``False`` (the model is added on top + of the existing aerodynamics). Returns ------- GenericSurface or list of GenericSurface The surface(s) added. """ - if position is None: - position = self.center_of_dry_mass_position - if overwrite: self._clear_aerodynamic_surfaces() @@ -1977,12 +2224,21 @@ def add_full_body_aerodynamics(self, surfaces, position=None, overwrite=False): def _clear_aerodynamic_surfaces(self): """Wipe the rocket's aerodynamics so a full-body model can fully replace - them: remove every aerodynamic surface, clear both built-in drag curves, - and reset the derived stability caches. Used by + them: remove every aerodynamic surface but the air brakes, clear both + built-in drag curves, and reset the derived stability caches. Used by :meth:`add_full_body_aerodynamics` with ``overwrite=True``. """ - self.aerodynamic_surfaces.clear() - self.surfaces_cp_to_cdm.clear() + # The air brakes stay: they are a device added on top of the rocket's + # aerodynamics, and the controller that sets them stays on the rocket + removed = [ + surface + for surface, _ in self.aerodynamic_surfaces + if not isinstance(surface, AirBrakes) + ] + for surface in removed: + self.aerodynamic_surfaces.remove(surface) + self._surfaces_at_center_of_dry_mass.discard(surface) + self.surfaces_cp_to_cdm.pop(surface, None) # Clear both built-in drag curves; the supplied surface(s) now provide # the complete aerodynamics, including any drag they carry. self._set_drag("power_on", 0) @@ -1991,7 +2247,8 @@ def _clear_aerodynamic_surfaces(self): "add_full_body_aerodynamics(overwrite=True): the rocket's existing " "aerodynamic surfaces and both built-in drag curves (power_on_drag, " "power_off_drag) were cleared; the supplied surface(s) now provide " - "the complete aerodynamics, including any drag they carry.", + "the complete aerodynamics, including any drag they carry. Air " + "brakes, if any, are kept.", UserWarning, stacklevel=3, ) @@ -2056,9 +2313,9 @@ def to_coefficients( can be included with an optional argument: - **Reynolds number.** Held at zero unless ``reynolds`` is given. - - **Control deflections.** Each control of a - :class:`ControllableGenericSurface` is held at its current value - unless it is listed in ``controls``. + - **Control deflections.** Each control of a surface (the names in its + ``controls``) is held at its default unless it is listed in + ``controls``. - **How the rate terms change with the angles.** The rate terms are read at zero angle unless ``rates="at_each_angle"`` (table model). In every case the effect of a rate is a straight line: the rate term @@ -2079,7 +2336,7 @@ def to_coefficients( only from them is reproduced exactly by the linear model to first order in the angles, and by the table model at every angle of an axisymmetric rocket. The optional arguments matter when you have added - a :class:`GenericSurface` or :class:`ControllableGenericSurface` (or a + a :class:`GenericSurface`, with or without controls (or a Reynolds-dependent :class:`LinearGenericSurface`) whose coefficients vary with Reynolds number, with a control deflection or, for the linear model, with the angles beyond a straight line. @@ -2141,12 +2398,12 @@ def to_coefficients( depends on the Reynolds number. controls : dict, optional Controls to keep as inputs of the coefficients, as a dict from the - name of a control of a :class:`ControllableGenericSurface` to the - values it is read at (at least two), for example - ``{"deflection": np.radians([-10, 0, 10])}``. Each control listed - becomes an input with that name. A control that is not listed is - held at its current value. The controls of the rocket's surfaces - are left as they were. + name of a control of a surface (one of the names in its + ``controls``) to the values it is read at (at least two), for + example ``{"deflection": np.radians([-10, 0, 10])}``. Each control + listed becomes an input with that name. A control that is not + listed is held at its default. The defaults of the rocket's + surfaces are left as they were. When several surfaces use the same control name, each is kept as a separate input named ``_`` (in lower @@ -2242,15 +2499,13 @@ def to_surface( controls : dict, optional Controls the surfaces keep, from control name to the values it is read at, for example ``{"deflection": np.radians([-10, 0, 10])}``. - Needs ``model="table"``; the surfaces returned are then - :class:`rocketpy.ControllableGenericSurface` objects with those - controls, each starting at 0. Default ``None``. See + Needs ``model="table"``; the surfaces returned then have those + controls, each with a default of 0. Default ``None``. See :meth:`to_coefficients`. Returns ------- - list of rocketpy.LinearGenericSurface, rocketpy.GenericSurface or \ -rocketpy.ControllableGenericSurface + list of rocketpy.LinearGenericSurface or rocketpy.GenericSurface Two surfaces, ``[power_off, power_on]``, each carrying the whole rocket's coefficients referenced to the rocket cross-section area and diameter and taken about the center of dry mass, and gated to @@ -2274,7 +2529,7 @@ def to_surface( for phase in ("power_off", "power_on"): label = f"{name} ({phase.replace('_', ' ')})" if model == "table" and controls: - surface = ControllableGenericSurface( + surface = GenericSurface( reference_area=self.area, reference_length=2 * self.radius, coefficients=lumped_surface_coefficients(coefficients[phase]), @@ -2304,24 +2559,40 @@ def to_surface( surfaces.append(surface) return surfaces - def _add_controllers(self, controllers): - """Adds a controller to the rocket. + def add_controller(self, controller): + """Add a controller to the rocket. It runs in every flight of the + rocket and sets the rocket's controls: a :class:`rocketpy.Controller` + at its sampling rate, a :class:`rocketpy.ContinuousController` at + every instant, inside the equations of motion. Parameters ---------- - controllers : list of Controller objects - List of controllers to be added to the rocket. If a single - Controller object is passed, outside of a list, a try/except block - will be used to try to append the controller to the list. + controller : Controller or ContinuousController + The controller, such as + ``Controller(controller_function, sampling_rate=10)`` or + ``ContinuousController(law)``. Returns ------- None - """ - try: - self._controllers.extend(controllers) - except TypeError: - self._controllers.append(controllers) + + See Also + -------- + rocketpy.Controller + rocketpy.ContinuousController + """ + if isinstance(controller, ContinuousController): + self._check_new_controllables(controller) + self._continuous_controllers.append(controller) + return + if not isinstance(controller, Controller): + raise TypeError( + "add_controller takes a rocketpy.Controller or a " + f"rocketpy.ContinuousController, got {controller!r}." + ) + # Raises if its outputs could not be told apart from another's + output_events((*self._controllers, controller)) + self._controllers.append(controller) def add_tail( self, top_radius, bottom_radius, length, position, radius=None, name="Tail" @@ -2758,10 +3029,11 @@ def add_parachute( - A callable function ``trigger(context)`` that returns ``True`` \ if the parachute ejection system should be triggered and \ ``False`` otherwise. ``context`` holds the simulation values \ - at the moment of the check, such as ``context.pressure`` \ - (Pa), ``context.height_agl`` (m), ``context.state`` (the \ - rocket's states, read by name, such as ``context.state.vz``) \ - and ``context.previous_state``. See :ref:`triggerdetails` \ + at the moment of the check, such as \ + ``context.pressure`` (Pa), ``context.height_agl`` (m), \ + ``context.state`` (the rocket's states, read by name, \ + such as ``context.state.vz``) and ``context.previous_state``. \ + See :ref:`triggerdetails` \ for how to write a trigger and the values it can read. The \ legacy form ``trigger(p, h, y)`` is deprecated. - A float value, representing an absolute height in meters. In this \ @@ -2839,10 +3111,24 @@ def add_parachute( def add_sensor(self, sensor, position): """Adds a sensor to the rocket. + During a flight, an event or controller function reads the sensor's + latest measurement by its name in snake_case, such as + ``context.sensors.accelerometer.az`` for a sensor named + ``"Accelerometer"``, and ``flight.sensor_history`` gives its readings + after the flight by the same names. A name used again, by another + sensor or by the same sensor added in another position, is numbered + from 2 in the order they were added: ``context.sensors["Barometer"]`` + and ``context.sensors["Barometer 2"]``, or + ``context.sensors.barometer`` and ``context.sensors.barometer_2``. + Adding a sensor never renames the ones already there. Giving each + sensor its own name, such as ``Barometer(..., name="Backup + Barometer")``, keeps the names readable. + Parameters ---------- sensor : Sensor - Sensor to be added to the rocket. + Sensor to be added to the rocket. The same sensor can be added in + more than one position: it then measures at each of them. position : int, float, tuple, list, Vector Position of the sensor. If a Vector, tuple or list is passed, it must be in the format (x, y, z) where x, y, and z are defined in the @@ -2875,14 +3161,13 @@ def add_sensor(self, sensor, position): except KeyError: sensor._attached_rockets[self] = 1 - # Create and store a position-specific event for this sensor-position - # This allows several objects of the same sensor type to be added to the - # rocket in different positions. + # One event per position of the sensor, which measures there and + # keeps its measurements in the position's own list of measured_data if not hasattr(self, "_sensor_events"): self._sensor_events = [] - - event = sensor.to_event(position) - self._sensor_events.append(event) + self._sensor_events.append( + (sensor, sensor.to_event(position, sensor._attached_rockets[self] - 1)) + ) def add_air_brakes( self, @@ -2892,11 +3177,11 @@ def add_air_brakes( clamp=True, reference_area=None, initial_observed_variables=None, - memory=None, override_rocket_drag=False, return_controller=False, name="AirBrakes", controller_name="AirBrakes Controller", + position=None, ): """Creates a new air brakes system, storing its parameters such as drag coefficient curve, controller function, sampling rate, and @@ -2905,8 +3190,8 @@ def add_air_brakes( Parameters ---------- drag_coefficient_curve : int, float, callable, array, string, Function - This parameter represents the drag coefficient associated with the - air brakes and/or the entire rocket, depending on the value of + The drag coefficient of the air brakes alone, or of the whole + rocket at each deployment level, depending on ``override_rocket_drag``. - If a constant, it should be an integer or a float representing a @@ -2924,80 +3209,100 @@ def add_air_brakes( - If a Function, it must take two parameters: deployment level and Mach number, and return the drag coefficient. - .. note:: For ``override_rocket_drag = False``, at - deployment level 0, the drag coefficient is assumed to be 0, - independent of the input drag coefficient curve. This means that - the simulation always considers that at a deployment level of 0, - the air brakes are completely retracted and do not contribute to - the drag of the rocket. + .. note:: At deployment level 0 the air brakes add no drag, + whatever the curve says: retracted, the rocket flies with its + own drag curves. controller_function : callable - Function that executes the control logic, with signature - ``controller_function(context) -> dict or None``. Invoked once per - sample; its return value is appended to the controller log. Set - ``air_brakes.deployment_level`` to apply the control action. - ``context`` holds the values listed in :class:`rocketpy.Event` - (``context.time``, ``context.state``, ``context.height_agl``, - ``context.sensors``, ``context.environment``, ``context.rocket``, - ``context.flight``, ``context.state_dot``, ``context.pressure``, - ``context.previous_state`` and so on) plus ``context.controller`` - (the :class:`_Controller`) and ``context.controlled.air_brakes`` - (the :class:`AirBrakes` being controlled). - The legacy positional form + The control logic, ``controller_function(context)``, called once + per sample. It sets the deployment level by writing + ``context.controls.air_brakes.deployment_level``, a value from + 0 (retracted) to 1 (fully deployed); the control input is named after + ``name`` (see below). ``context`` holds the values listed in + :class:`rocketpy.Event` (``context.time``, ``context.state``, + ``context.height_agl``, ``context.sensors``, + ``context.environment`` and so on). Values to look at after the + flight are kept with ``context.record(...)``, and values the next + call needs in ``context.memory``. See :class:`rocketpy.Controller`. + The positional form of v1.13, ``controller_function(time, sampling_rate, state, state_history, - observed_variables, interactive_objects[, sensors[, environment]])`` - is deprecated. + observed_variables, air_brakes[, sensors[, environment]])``, is + deprecated and will be removed in v1.16. sampling_rate : float The sampling rate of the controller function in Hertz (Hz). This means that the controller function will be called every `1/sampling_rate` seconds. clamp : bool, optional - If True, the simulation will clamp the deployment level to 0 or 1 if - the deployment level is out of bounds. If False, the simulation will - not clamp the deployment level and will instead raise a warning if - the deployment level is out of bounds. Default is True. + Whether the deployment level is kept between 0 (retracted) and 1 + (fully open): ``True`` (the default) moves a value outside that + range to the nearest end, ``False`` puts no limit on it. reference_area : float, optional Reference area used to calculate the drag force of the air brakes from the drag coefficient curve. If None, which is default, use rocket section area. Must be given in squared meters. - initial_observed_variables : list, optional - A list of the initial values of the variables that the controller - function returns. This list is used to initialize the - `observed_variables` argument of the controller function. The - default value is None, which initializes the list as an empty list. - - .. deprecated:: 1.13 - Passing `initial_observed_variables` directly to - ``add_air_brakes`` is deprecated. Provide initial observed - variables via the ``memory`` parameter as - ``memory={'observed_variables': [...]}`` instead. Support - for the positional argument will be removed in v1.14. - memory : dict, optional - The controller's own dictionary, kept from one run to the next. - Read and write it as ``context.controller.memory`` inside - ``controller_function``. Defaults to an empty dict. + initial_observed_variables : any, optional + The first item of the list a positional controller function + receives as ``observed_variables``. Defaults to ``None``: the list + starts empty. + + .. deprecated:: 1.15 + Record the values you want to see after the flight with + ``context.record(...)`` and read them as ``flight.records``. + Support for this argument will be removed in v1.16. override_rocket_drag : bool, optional - If False, the air brakes drag coefficient will be added to the - rocket's power off drag coefficient curve. If True, during the - simulation, the rocket's power off drag will be ignored and the air - brakes drag coefficient will be used for the entire rocket instead. - Default is False. + What ``drag_coefficient_curve`` is the drag coefficient of. + + - ``False`` (the default): the air brakes alone. Their drag is + added to the rocket's. + - ``True``: the whole rocket at each deployment level, as measured + in a wind tunnel or computed for the complete rocket. The air + brakes then add the difference between the curve and its value + at deployment level 0, at the same Mach number, to the rocket's + own drag. The curve is of the rocket with its motor off: while + the motor burns, the same difference is added to the rocket's + ``power_on_drag``. The curve must include deployment level 0, and + the rocket's ``power_off_drag`` should be that retracted drag: the + total drag is then the curve. A warning is shown when the two + differ by more than 5%, since the rocket's drag curves are then + the drag with the air brakes retracted and the curve only gives + what opening them adds. return_controller : bool, optional - If True, the function will return the controller object created. - Default is False. + If True, return the controller as well as the air brakes, as + ``(air_brakes, controller)``. Default is False: only the air + brakes are returned. + + .. deprecated:: 1.15 + The controller is the last of ``rocket.controllers`` right + after this call. Support for this argument will be removed in + v1.16. name : string, optional - AirBrakes name, such as drogue and main. Has no impact in - simulation, as it is only used to display data in a more - organized matter. + AirBrakes name. It also names their control input: the default + ``"AirBrakes"`` gives ``air_brakes.deployment_level``. Air brakes + added twice to one rocket need different names. controller_name : string, optional - Controller name. Has no impact in simulation, as it is only used to - display data in a more organized matter. + Controller name. It names the controller's records: + ``"AirBrakes Controller"`` gives + ``flight.records["AirBrakes Controller"].``. + position : int, float, tuple, optional + Where the air brakes are on the rocket, in meters, in the rocket's + coordinate system: a number along the axis, or ``(x, y, z)``. + Their drag acts there, along the rocket's axis. Default ``None``: + at the rocket's center of dry mass, wherever the motor puts it. + Returns ------- air_brakes : AirBrakes AirBrakes object created. controller : Controller - Controller object created. + Controller object created. Only returned if ``return_controller`` + is True. + + See Also + -------- + rocketpy.AirBrakes : The air brakes and their drag curve. + rocketpy.Controller : The controller and what it can read and write. + :ref:`airbrakes` : The air brakes guide. + :ref:`controllers` : The controllers guide. """ reference_area = reference_area if reference_area is not None else self.area air_brakes = AirBrakes( @@ -3005,97 +3310,174 @@ def add_air_brakes( reference_area=reference_area, clamp=clamp, override_rocket_drag=override_rocket_drag, - deployment_level=0, + initial_deployment_level=0, name=name, ) - # Prepare controller memory and compatibility wrapper for - # controller_function. The signature is `controller_function(context)`. - # To avoid breaking existing user code, wrap legacy functions that - # accept positional args. - controller_memory = memory.copy() if memory is not None else {} - - # Map initial_observed_variables into controller memory for the - # new API while emitting a deprecation warning for the positional - # argument usage. - if initial_observed_variables is not None: + controller_function = _legacy_controller( + controller_function, sampling_rate, name, initial_observed_variables + ) + controller = Controller( + controller_function=controller_function, + sampling_rate=sampling_rate, + name=controller_name, + ) + self.add_surfaces(air_brakes, position) + self.add_controller(controller) + if return_controller: warnings.warn( - "Passing `initial_observed_variables` to `add_air_brakes` is " - "deprecated; supply them via `memory={'observed_variables': ...}` " - "instead. Support for this argument will be removed in v1.14.", + "`return_controller` is deprecated: the controller of the air " + "brakes is the last of `rocket.controllers` right after " + "`add_air_brakes`. Support for this argument will be removed in " + "v1.16.", DeprecationWarning, + stacklevel=2, ) - controller_memory["observed_variables"] = initial_observed_variables - - orig_controller = controller_function - signature = inspect.signature(orig_controller) - parameters = tuple(signature.parameters.values()) - accepts_var_args = any( - p.kind == inspect.Parameter.VAR_POSITIONAL for p in parameters - ) - positional_parameter_count = sum( - p.kind - in ( - inspect.Parameter.POSITIONAL_ONLY, - inspect.Parameter.POSITIONAL_OR_KEYWORD, - ) - for p in parameters + return air_brakes, controller + return air_brakes + + def _check_retracted_drag(self, air_brakes): + """Warn when a whole-rocket air brakes curve and the rocket's power-off + drag disagree on the drag with the air brakes retracted, by more than + 5% at any Mach number of the curve (0.1 to 0.9 for a curve that is not + a table). Called by ``add_surfaces``, whose caller the warning points + at.""" + source = air_brakes.drag_coefficient.source + machs = ( + np.linspace(0.1, 0.9, 9) if callable(source) else np.unique(source[:, 1]) ) + rocket_drag = self.power_off_drag_7d.get_value_opt + for mach in machs: + of_rocket = self.area * rocket_drag(0, 0, mach, 0, 0, 0, 0) + of_curve = air_brakes.reference_area * air_brakes.drag_coefficient(0, mach) + if abs(of_curve - of_rocket) > 0.05 * abs(of_rocket): + warnings.warn( + f"The drag coefficient curve of {air_brakes.name} is of the " + "whole rocket (override_rocket_drag=True), but at deployment " + f"level 0 and Mach {mach:.2f} it gives a drag area of " + f"{of_curve:.4g} m², while the rocket's power_off_drag gives " + f"{of_rocket:.4g} m². Retracted, the rocket flies with its own " + "drag curves, and the air brakes add only the difference " + "between the curve and its deployment level 0 values. For the " + "total drag to be the curve, give the rocket the curve's " + "deployment level 0 values as its drag.", + stacklevel=3, + ) + return - if positional_parameter_count == 1 and not accepts_var_args: - controller_wrapper = orig_controller - else: - # A legacy positional controller must accept one of the supported - # signatures (5, 6 or 7 arguments). Reject any other count early so - # the user gets a clear error instead of a runtime failure mid-flight. - if not accepts_var_args and positional_parameter_count not in (5, 6, 7): + def add_effector(self, effector, position=None, angular_position=0, radius=0): + """Add an effector: a :class:`rocketpy.ThrustEffector` or a + :class:`rocketpy.ForceEffector`, which acts on the rocket other than + through the air: a thrust vectoring gimbal, a reaction control + thruster. (Air brakes, control fins and other aerodynamic parts are + added with :meth:`add_surfaces`.) + + The effector is kept in ``rocket.effectors`` with its position, as + ``rocket.effectors[0].component`` and ``.position``. What it does is + told by its class, and an effector can be both of these: + + - a :class:`rocketpy.ThrustEffector` changes the motor's thrust; + - a :class:`rocketpy.ForceEffector` pushes or turns the rocket + directly. + + A controller sets the effector's controls as + ``context.controls..``. + + Parameters + ---------- + effector : ThrustEffector or ForceEffector + The effector to add. + position : float or array_like, optional + Where the effector acts, in m, in the rocket's own coordinate + system (the one the surfaces and the motor are placed in, see + :ref:`rocket_axes`). One of: + + - ``None`` (the default): at the center of dry mass, wherever the + motor puts it, so the function's moment is the whole moment; + - a number: the position along the rocket, like a fin's, with + ``angular_position`` and ``radius`` placing it around the tube; + - three numbers ``(x, y, z)``: the point itself, and + ``angular_position`` and ``radius`` are not used. + + A force effector's force acts at this point. A thrust effector + has no position: it acts on the motor's + thrust at the motor's nozzle (a thruster somewhere else is a force + effector). + angular_position : float, optional + Angle around the rocket, in degrees, from the ``y`` axis of the + rocket's coordinate system, positive in the direction of positive + roll (the right-hand rule about ``z`` toward the nose), as for fins + and rail buttons: ``0`` is on the ``y`` axis, ``90`` on the + ``-x`` axis. Defaults to ``0``. + radius : float, optional + Distance from the rocket's centerline, in m: ``rocket.radius`` for + a thruster on the skin. Defaults to ``0``, on the centerline. + + Returns + ------- + None + + Raises + ------ + TypeError + If it is not one of the two kinds of effector, or it is an + aerodynamic surface, which :meth:`add_surfaces` adds; or if a + position is given for a thrust effector. + ValueError + If ``angular_position`` or ``radius`` is given without + ``position``, or with a three-number ``position``. + + See Also + -------- + rocketpy.ForceEffector : An effector built from a force and moment + function, with a worked example. + :ref:`controllers` : The controllers guide, with a roll thruster pair + and a gimbal. + """ + if isinstance(effector, GenericSurface): + raise TypeError( + f"'{effector.name}' is an aerodynamic surface: add it with " + "rocket.add_surfaces(surface, position)." + ) + if not isinstance(effector, (ThrustEffector, ForceEffector)): + raise TypeError( + f"{effector!r} cannot be added as an effector: an effector changes " + "the thrust or pushes the rocket, so it is a " + "rocketpy.ThrustEffector or ForceEffector." + ) + if any(effector is added for added, _ in self.effectors): + raise ValueError( + f"The effector '{effector.name}' is already on the rocket. To have " + "the same effector twice, build it twice." + ) + placed = angular_position != 0 or radius != 0 + if position is None: + if placed: raise ValueError( - "controller_function must take the event context as its " - "single argument, like `def controller(context): ...`. A " - "legacy positional controller_function must have 5, 6, or 7 " - f"arguments, but {positional_parameter_count} were given." + f"The effector '{effector.name}' has an angular_position or a " + "radius but no position: give its position along the rocket " + "too." ) - warnings.warn( - "Calling controller_function with positional arguments is " - "deprecated; use controller_function(context) instead. " - "Support for positional controller arguments will be removed " - "in v1.16.", - DeprecationWarning, - stacklevel=2, + elif not isinstance(effector, ForceEffector): + raise TypeError( + f"The effector '{effector.name}' changes the motor's thrust, which " + "acts at the motor's nozzle, so it has no position of its own. A " + "thruster somewhere else on the rocket is a ForceEffector." ) - - def controller_wrapper(context): - # Build positional args in the historical order described in - # the docs. - pos_args = [ - context["time"], - sampling_rate, - context["canonical_state"], - controller_memory.get("observed_variables", []), - context["controlled"][0], - context["sensors"], - context["environment"], - ] - if accepts_var_args: - legacy_args = pos_args - else: - legacy_args = pos_args[:positional_parameter_count] - return orig_controller(*legacy_args) - - # TODO: should this be in the airbrakes object instead? - _controller = _Controller( - controller_function=controller_wrapper, - controlled_objects=air_brakes, - controlled_objects_name="air_brakes", - sampling_rate=sampling_rate, - memory=controller_memory, - name=controller_name, - ) - self.air_brakes.append(air_brakes) - self._add_controllers(_controller) - if return_controller: - return air_brakes, _controller + elif isinstance(position, (Vector, tuple, list, np.ndarray)): + if placed: + raise ValueError( + f"The position of the effector '{effector.name}' is a point, " + "so angular_position and radius are not used: give one or " + "the other." + ) + position = Vector(position) else: - return air_brakes + position = Vector( + point_around(position, angular_position, radius, self._csys) + ) + self._check_new_controllables(effector) + self.effectors.add(effector, position) + self._evaluate_effectors() def set_rail_buttons( self, @@ -3148,11 +3530,7 @@ def set_rail_buttons( ) self.rail_buttons = Components() position = Vector( - [ - radius * -math.sin(math.radians(angular_position)), - radius * math.cos(math.radians(angular_position)), - lower_button_position, - ] + point_around(lower_button_position, angular_position, radius, self._csys) ) self.rail_buttons.add(rail_buttons, position) return rail_buttons @@ -3253,6 +3631,8 @@ def add_thrust_eccentricity(self, x, y): """ self.thrust_eccentricity_x = x self.thrust_eccentricity_y = y + self.evaluate_nozzle_exit() + self.evaluate_nozzle_gyration_tensor() return self def draw(self, vis_args=None, plane=None, *, filename=None): @@ -3355,11 +3735,20 @@ def to_dict(self, **kwargs): "stability_phase": self.stability_phase, "motor": self.motor, "motor_position": self.motor_position, - "aerodynamic_surfaces": self.aerodynamic_surfaces, + # A surface at the center of dry mass, wherever the motor puts it, + # is saved without a position + "aerodynamic_surfaces": [ + ( + surface, + None if self._is_at_center_of_dry_mass(surface) else position, + ) + for surface, position in self.aerodynamic_surfaces + ], "rail_buttons": self.rail_buttons, "parachutes": self.parachutes, - "air_brakes": self.air_brakes, + "effectors": self.effectors, "_controllers": self._controllers, + "continuous_controllers": list(self._continuous_controllers), "sensors": self.sensors, } @@ -3474,38 +3863,21 @@ def from_dict(cls, data): for sensor, position in data["sensors"]: rocket.add_sensor(sensor, position) - for air_brake in data["air_brakes"]: - rocket.air_brakes.append(air_brake) + # Saved before air brakes were aerodynamic surfaces, when they acted at + # the center of dry mass + for air_brake in data.get("air_brakes", []): + rocket.add_surfaces(air_brake, None) + for controllable, position in data.get("effectors", []): + if was_loaded(controllable, "effector", "class"): + rocket.add_effector(controllable, position) + + # A controller points at no object of the rocket: it writes control + # inputs by name, so there is nothing to reconnect for controller in data["_controllers"]: - # Reconnect the controller to the rocket's own reconstructed objects - # by matching the hash(es) it stored for its controlled objects - # against the reconstructed objects (see _Controller.to_dict). - controlled_objects_hash = getattr( - controller, "_serialized_controlled_objects_hash", None - ) - if controlled_objects_hash is not None: - is_iterable = isinstance(controlled_objects_hash, Iterable) - hashes = ( - controlled_objects_hash - if is_iterable - else [controlled_objects_hash] - ) - found = [] - for hash_ in hashes: - if hash_ is None: # unhashable controlled object; cannot match - continue - if (hashed_obj := find_obj_from_hash(data, hash_)) is not None: - found.append(hashed_obj) - else: - warnings.warn( - "Could not find controller controlled objects. " - "Deserialization will proceed, results may not be accurate." - ) - if found: - controller.rebind_controlled_objects( - found if is_iterable else found[0] - ) - rocket._add_controllers(controller) + rocket.add_controller(controller) + for controller in data.get("continuous_controllers", []): + if was_loaded(controller, "continuous controller", "law"): + rocket.add_controller(controller) return rocket diff --git a/rocketpy/sensors/barometer.py b/rocketpy/sensors/barometer.py index 98d70d847..64d087b53 100644 --- a/rocketpy/sensors/barometer.py +++ b/rocketpy/sensors/barometer.py @@ -50,6 +50,8 @@ class Barometer(ScalarSensor): units = "Pa" channels = [("pressure", "Pa")] + _reads_state_derivative = False + def __init__( self, sampling_rate, @@ -150,8 +152,9 @@ def measure(self, time, **kwargs): - u : np.array State vector of the rocket. - - u_dot : np.array - Derivative of the state vector of the rocket. + - u_dot : np.array or None + Derivative of the state vector of the rocket. Not read by this + sensor, and ``None`` during a flight. - relative_position : np.array Position of the sensor relative to the rocket center of mass. - environment : Environment diff --git a/rocketpy/sensors/gnss_receiver.py b/rocketpy/sensors/gnss_receiver.py index 1e33d1d4f..3ff8e5c2e 100644 --- a/rocketpy/sensors/gnss_receiver.py +++ b/rocketpy/sensors/gnss_receiver.py @@ -36,6 +36,8 @@ class GnssReceiver(ScalarSensor): units = "°, m" channels = [("latitude", "°"), ("longitude", "°"), ("altitude", "m")] + _reads_state_derivative = False + def __init__( self, sampling_rate, @@ -78,8 +80,9 @@ def measure(self, time, **kwargs): - u : np.array State vector of the rocket. - - u_dot : np.array - Derivative of the state vector of the rocket. + - u_dot : np.array or None + Derivative of the state vector of the rocket. Not read by this + sensor, and ``None`` during a flight. - relative_position : np.array Position of the sensor relative to the rocket center of mass. - environment : Environment diff --git a/rocketpy/sensors/gyroscope.py b/rocketpy/sensors/gyroscope.py index 457e557c1..3a42ce226 100644 --- a/rocketpy/sensors/gyroscope.py +++ b/rocketpy/sensors/gyroscope.py @@ -202,6 +202,11 @@ def __init__( self.prints = _GyroscopePrints(self) self.plots = _GyroscopePlots(self) + @property + def _reads_state_derivative(self): + # Only the acceleration sensitivity reads the acceleration + return self.acceleration_sensitivity != Vector.zeros() + def measure(self, time, **kwargs): """Measure the angular velocity of the rocket @@ -214,8 +219,10 @@ def measure(self, time, **kwargs): - u : np.array State vector of the rocket. - - u_dot : np.array - Derivative of the state vector of the rocket. + - u_dot : np.array or None + Derivative of the state vector of the rocket. Read only when + the gyroscope has an acceleration sensitivity, and ``None`` + during a flight otherwise. - relative_position : np.array Position of the sensor relative to the rocket center of mass. - environment : Environment diff --git a/rocketpy/sensors/sensor.py b/rocketpy/sensors/sensor.py index 4f9cb5fc3..a625a4850 100644 --- a/rocketpy/sensors/sensor.py +++ b/rocketpy/sensors/sensor.py @@ -1,5 +1,6 @@ import json from abc import ABC, abstractmethod +from copy import deepcopy import numpy as np @@ -46,6 +47,12 @@ class Sensor(ABC): temperature drift. """ + # Whether ``measure`` reads ``u_dot``, the derivative of the state with + # respect to time. Working it out takes an evaluation of the equations of + # motion at every reading, so a sensor that never reads it sets this to + # ``False`` and is given ``u_dot=None`` during a flight. + _reads_state_derivative = True + def __init__( self, sampling_rate, @@ -136,6 +143,7 @@ def __init__( self._counter = 0 self._save_data = self._save_data_single self._random_walk_drift = 0 + self._drift_log = [] self.normal_vector = Vector([0, 0, 0]) # handle measurement range @@ -166,7 +174,7 @@ def all_info(self): self.info() self.plots.all() - def to_event(self, position): + def to_event(self, position, index=0): """Create a simulation event for this sensor. Parameters @@ -178,29 +186,37 @@ def to_event(self, position): measurements (e.g. accelerometers). The position should be given as a Vector object representing the x, y and z coordinates of the sensor in meters. + index : int, optional + Which of the sensor's positions on the rocket this is, counted + from 0 in the order they were added. A sensor added more than once + keeps the measurements of each position in its own list of + ``measured_data``, at this index. Default is 0. Returns ------- Event Event object with an always-true trigger that delegates runtime - execution to this sensor. + execution to this sensor. Each reading goes into the flight's + solution, which drops the readings the flight goes back over and + keeps the rest with its other results. """ - # Local import avoids import-time coupling with simulation package. def sensor_callback(context): time = context["time"] state = context["canonical_state"] - state_dot = context["canonical_state_dot"] + # Asked for only when the sensor reads it: the context works it + # out with an evaluation of the equations of motion + state_dot = ( + context["canonical_state_dot"] if self._reads_state_derivative else None + ) rocket = context["rocket"] environment = context["environment"] - event = context["event"] - - # Get position from event memory (set when sensor added to rocket) - position = event.memory.get("position") relative_position = position - rocket._csys * Vector( [0, 0, rocket.center_of_dry_mass_position] ) + # The list of measured_data this position's measurement goes to + self._counter = index self.measure( time, @@ -213,22 +229,47 @@ def sensor_callback(context): earth_radius=environment.earth_radius, initial_coordinates=(environment.latitude, environment.longitude), ) + self._drift_log.append((time, self._random_walk_drift)) + reading = self.measurement + if not isinstance(reading, tuple): + reading = (reading,) + # Kept with the flight's other results, under the name the + # flight gives this position + context._solution._add_reading( # pylint: disable=protected-access + context["event"]._position_name, # pylint: disable=protected-access + time, + {label: value for (label, _), value in zip(self.channels, reading)}, + ) return Event( callback=sensor_callback, name=f"{self.name} Measurement", sampling_rate=self.sampling_rate, - memory={"position": position, "sensor": self}, trigger_only_once=False, priority=1, time_overshootable=True, ) - def _reset(self, simulated_rocket): - """Reset the sensor data for a new simulation.""" - self._random_walk_drift = ( - Vector([0, 0, 0]) if isinstance(self._random_walk_drift, Vector) else 0 + def _detached_copy(self): + """Return a copy of the sensor with the same settings, attached to no + rocket and holding no measurements.""" + # The copy starts with these empty, instead of copying the rockets the + # sensor is on and what it measured + return deepcopy( + self, + { + id(self._attached_rockets): {}, + id(self.measured_data): [], + id(self._drift_log): [], + }, ) + + def _reset(self, simulated_rocket): + """Reset the sensor data for a new simulation: no measurement yet, and + the noise drift back at zero.""" + self._random_walk_drift = self._no_drift() + self._drift_log = [] + self.measurement = None self.measured_data = [] if self._attached_rockets[simulated_rocket] > 1: self.measured_data = [ @@ -238,6 +279,21 @@ def _reset(self, simulated_rocket): else: self._save_data = self._save_data_single + def _no_drift(self): + """The drift of the random walk before any reading.""" + return Vector([0, 0, 0]) if isinstance(self._random_walk_drift, Vector) else 0 + + def _drop_drift_after(self, time): + """Take the random walk back to ``time``: its drift is again the one + after the last reading up to ``time``, without the steps of the + readings made after it, which the flight went back over.""" + log = self._drift_log + if not log or log[-1][0] <= time: + return + while log and log[-1][0] > time: + log.pop() + self._random_walk_drift = log[-1][1] if log else self._no_drift() + def _save_data_single(self, data): """Save the measured data to the sensor data list for a sensor that is added only once to the simulated rocket.""" diff --git a/rocketpy/simulation/events/commands.py b/rocketpy/simulation/events/commands.py index 0629c5f85..d12dd594e 100644 --- a/rocketpy/simulation/events/commands.py +++ b/rocketpy/simulation/events/commands.py @@ -1,5 +1,6 @@ class Commands: - """Command API exposed to hook trigger/callback callables.""" + """The requests an event's trigger or callback makes to the flight, as + ``context.commands``. A request takes effect once the function returns.""" def __init__(self): self.reset() @@ -8,25 +9,37 @@ def reset(self): self.exact_time = None self.exact_state = None self._disabled = None # None=no-op, True=disable, False=enable - self.rollback = False self.new_events = [] self.enable_events = [] self.disable_events = [] - self.new_controllers = [] - self.disable_controllers = [] self.new_dynamics = None self.new_dynamics_kwargs = {} self.new_flight_phase = None self.new_flight_phase_name = None self.new_flight_phase_lag = 0 self._terminate = False - self.terminate_phase_name = None self.surface_switches = [] + self.control_changes = {} + # Whether the equations of motion being flown read the control inputs. + # Set by the flight with ``control_changes`` + self._controls_read = True def disable(self): + """Stop running this event from now on. + + Use it when the function itself decides to stop, such as a controller + that gives up after a fault it detects. For a condition known when the + event is built, such as "at apogee" or "after 10 s", prefer the + event's ``disable_on``: it is checked for you and is saved with the + event. Both are recorded in ``event.disabled_times``, and the event + can be turned on again by its ``enable_on``. + """ self._disabled = True def enable(self): + """Cancel a ``disable()`` made earlier in the same call. A disabled + event does not run its function, so it cannot turn itself back on: + give it an ``enable_on`` for that.""" self._disabled = False def add_event(self, event): @@ -38,36 +51,37 @@ def add_event(self, event): Use this when the number of events is not known when the flight is built. When you do know, prefer giving the event to the ``Flight`` with - ``enabled=False`` and turning it on later, through ``enable_on`` or the - ``enable`` command. That way the flight knows about the event from the - start, which matters for the case below. + ``enabled=False`` and turning it on later, through its ``enable_on`` or + with ``enable_event`` from another event. That way the flight knows + about the event from the start. Parameters ---------- event : Event The event to add. - - Warns - ----- - UserWarning - If the event has ``changes_dynamics=True`` and the flight was not - already recording its post-process variables. A flight decides - whether to record the accelerations, aerodynamic forces and moments - and net thrust before it starts, from the events it was built with. - An event that changes the rocket and arrives later cannot turn that - on for the part of the flight already flown, so those variables are - worked out afterwards from the rocket in the state it ends the - flight in, and whatever the event changed is reported for the whole - flight rather than only from the moment it was added. The - trajectory itself is correct either way. Register such an event up - front, disabled, to avoid this. When the events cannot be written in - advance at all, give the flight one disabled placeholder event that - declares ``changes_dynamics=True``; see "Commands" in the event - usage guide. """ self.new_events.append(event) + def enable_event(self, event): + """Turn on another event of the flight, from now on. + + Parameters + ---------- + event : Event + The event to turn on: one given to the flight, or a controller + of the rocket. + """ + self.enable_events.append(event) + def disable_event(self, event): + """Turn off another event of the flight, from now on. + + Parameters + ---------- + event : Event + The event to turn off: one given to the flight, or a controller + of the rocket. + """ self.disable_events.append(event) def set_dynamics(self, dynamics, **phase_kwargs): @@ -85,25 +99,35 @@ def set_dynamics(self, dynamics, **phase_kwargs): **phase_kwargs Values the new equations need that are only known now, passed straight through to the derivative on every step. A parachute - descent uses this to carry which parachute is out:: + descent uses this to carry which parachute is out: - commands.set_dynamics(PARACHUTE_DYNAMICS, parachute=main) + .. code-block:: python - Notes - ----- - Changing the equations of motion invalidates the trajectory past the - trigger, so an event that calls this must be created with - ``changes_dynamics=True``. + commands.set_dynamics(PARACHUTE_DYNAMICS, parachute=main) """ self.new_dynamics = dynamics self.new_dynamics_kwargs = phase_kwargs def start_flight_phase(self, phase_name=None, lag=0): + """Start a new flight phase. + + The new phase flies the current equations of motion, unless + ``set_dynamics`` is called in the same function. + + Parameters + ---------- + phase_name : str, optional + Name of the new phase, read by events as ``context.phase_name``. + Default ``None``. + lag : float, optional + Time from now until the new phase starts, in s. Default 0. + """ self.new_flight_phase = True self.new_flight_phase_name = phase_name self.new_flight_phase_lag = lag def terminate_flight(self): + """End the flight at this moment.""" self._terminate = True def activate_surface(self, surface): @@ -112,10 +136,12 @@ def activate_surface(self, surface): Use it for a surface that only exists from some point of the flight. Build that surface with ``active=False`` so that it starts the flight switched off, add it to the rocket as usual, and call this from the - callback of an event:: + callback of an event: + + .. code-block:: python def switch_on(context): - context.event.commands.activate_surface(my_surface) + context.commands.activate_surface(my_surface) A surface with ``active_during="power_on"`` or ``"power_off"`` still only produces force during that motor phase once it is switched on. @@ -136,10 +162,12 @@ def deactivate_surface(self, surface): """Make an aerodynamic surface stop producing force from this moment on. Use it for a surface that stops existing at some point of the flight. - Call it from the callback of an event:: + Call it from the callback of an event: + + .. code-block:: python def switch_off(context): - context.event.commands.deactivate_surface(my_surface) + context.commands.deactivate_surface(my_surface) The change lasts for the rest of this flight only. The surface itself is not modified, so another flight of the same rocket starts with it @@ -162,16 +190,19 @@ def changes_trajectory(self): """Whether these commands change what happens at/after the trigger. Returns ``True`` when the queued commands start a new flight phase, - switch the equations of motion, terminate the flight, or switch an - aerodynamic surface on or off. In all these cases the trajectory past - the trigger is no longer valid, so during time overshoot the simulation - must be rolled back to the exact trigger crossing before the commands - are applied. Pure scheduling changes (enabling/disabling or adding - events) do not require a rollback. + switch the equations of motion, terminate the flight or switch an + aerodynamic surface on or off, or when the event's callback changed a + control through ``context.controls`` in a flight phase whose equations + read the control inputs (a parachute descent reads none). In all these + cases the trajectory past the trigger is no longer valid, so during + time overshoot the simulation must be rolled back to the exact trigger + crossing before the commands are applied. Pure scheduling changes + (enabling/disabling or adding events) do not require a rollback. """ return ( self.new_flight_phase is not None or self.new_dynamics is not None or self._terminate or bool(self.surface_switches) + or (self._controls_read and bool(self.control_changes)) ) diff --git a/rocketpy/simulation/events/event.py b/rocketpy/simulation/events/event.py index 682d1da10..4a3d6b7c8 100644 --- a/rocketpy/simulation/events/event.py +++ b/rocketpy/simulation/events/event.py @@ -1,13 +1,21 @@ import inspect +import keyword +import logging import warnings from copy import deepcopy from numbers import Real from ..._logging import logger +from ...tools import copied_value from .commands import Commands +from .event_context import EventContext, refresh_event_kwargs from .exact_time_solvers import SOLVERS + +# The conditions a trigger, ``enable_on`` and ``disable_on`` can name. Each +# holds from that moment on. PRESETS = { + # Coming down and above the ground "apogee": lambda context: ( context["canonical_state"][5] <= 0 < context["height_agl"] ), @@ -16,18 +24,41 @@ class Event: - """Event helper with trigger/callback execution and exact-time support. + """An action that runs when a condition is met during a flight. + + An event pairs a ``trigger``, the condition, with a ``callback``, the + action. Each time the event is checked, the trigger is evaluated and, when + it returns ``True``, the callback runs. Both receive the ``context``, a + :class:`rocketpy.EventContext` with the time, the rocket's state, the + sensor readings and the rest of what is known at that moment. - An ``Event`` is the main way RocketPy reacts to conditions during a - flight. It pairs a ``trigger`` predicate with a ``callback`` action: at - each evaluation the trigger is checked and, when it returns ``True``, - the callback runs. Callbacks can inspect the simulation state, store - persistent data in ``memory``, log return values, and queue commands - (through ``event.commands``) that modify the simulation, such as - starting a new flight phase, replacing the derivative, scheduling other - events, or terminating the flight. + A callback can keep data from one check to the next in + ``context.memory``, record values to read after the flight with + ``context.record``, share values with other events through + ``context.outputs``, and change the course of the flight through + ``context.commands``: start a new flight phase, change the equations of + motion, add other events or end the flight. See :ref:`eventusage` for a full guide with runnable examples. + + Attributes + ---------- + name : str + Name of the event. + enabled : bool + Whether the event is currently checked. + memory : dict + The event's own data, as the last check left it. + triggered_times : list of float + The times the event fired in the last flight, in s. + enabled_times, disabled_times : list of float + The times the event was turned on and off in the last flight, in s. + records : dict + What the event recorded in the last flight. + outputs : tuple of str + Names of the values the event shares with other events. + output_history : dict + What the event wrote to its outputs in the last flight. """ def __init__( # pylint: disable=too-many-arguments @@ -36,182 +67,183 @@ def __init__( # pylint: disable=too-many-arguments trigger=None, sampling_rate=None, memory=None, - disable_on=None, + *, + outputs=None, + name="Custom Event", + enabled=True, enable_on=None, - exact_time_function=None, - exact_time_config=None, + disable_on=None, trigger_only_once=False, time_overshootable=True, - changes_dynamics=False, - name="Custom Event", - enabled=True, - verbose=False, + exact_time_function=None, + exact_time_config=None, priority=4, + verbose=False, ): - """Initialize an Event object. + """Build an event. Parameters ---------- - callback : function - Required callable executed when the event triggers, with signature - ``callback(context) -> None or dict``. A returned ``dict`` is - appended to ``self.callback_log``. Queue commands via - ``context.event.commands`` and keep the event's own data in - ``context.event.memory``. - ``context`` holds the following values, each read as - ``context.``: - ``time`` (float, s), - ``state`` (the rocket's states, read by name, such as - ``context.state.vz``. The names are ``x``, ``y``, ``z`` - (position, m), ``vx``, ``vy``, ``vz`` (velocity, m/s), ``e0``, - ``e1``, ``e2``, ``e3`` (attitude quaternion) and ``w1``, ``w2``, - ``w3`` (angular velocity, rad/s), plus any state the current - flight phase follows on its own, read as - ``context.state.my_state`` for a state the phase calls - ``my_state``), - ``height_agl`` (float, m), - ``sensors`` (list of sensor objects), - ``sensors_by_name`` (dict of sensor objects), - ``environment`` (:class:`rocketpy.Environment`), - ``rocket`` (:class:`rocketpy.Rocket`), - ``flight`` (:class:`rocketpy.Flight`), - ``phase`` (current flight phase), - ``event`` (this :class:`Event` instance), - ``sampling_rate`` (float, Hz or ``None``), - ``step_size`` (float, s, how long the simulation has been inside - the solver step being evaluated; not the interval between checks - of this callback, and not ``1 / sampling_rate``), - ``state_dot`` (the derivative of each state with respect to - time, read by the same names as in :class:`rocketpy.Flight`: - ``context.state_dot.az`` is the vertical acceleration in m/s² - and ``context.state_dot.alpha1`` an angular acceleration in - rad/s²), - ``pressure`` (float, Pa, at the rocket's altitude), - ``previous_state`` (the ``state`` from the previous time this - event was checked, or ``None`` on the first check), - ``previous_time`` (float, s, or ``None`` on the first check). - ``state_dot`` and ``pressure`` are only worked out when a - function reads them, and once per solver step, so reading them - costs nothing unless they are used. Do not add values to - ``context``: it is shared by every event checked in the step. - trigger : function, optional - Predicate that returns ``True`` when the event should fire. It - receives the same ``context`` as ``callback`` (see above), but - its return value is interpreted as a boolean rather than logged. - It may also be the string ``"apogee"`` (the rocket is coming down - and above the ground) or ``"burnout"`` (the motor has burned - out), or a simulation time in seconds. These three stay ``True`` - from that moment on, so the event fires at every check after it. - Set ``trigger_only_once=True`` to fire once. - If ``None`` (default), the event fires every time it is evaluated. + callback : callable + The action, ``callback(context)``, run when the event triggers. + ``context`` is a :class:`rocketpy.EventContext`, read by attribute: + ``context.time``, ``context.state.vz``, ``context.height_agl``, + ``context.sensors.barometer.pressure``. What the callback returns + is ignored. + trigger : callable, str or float, optional + The condition that fires the event. One of: + + - a function ``trigger(context)`` that returns ``True`` when the + event should fire, given the same ``context`` as ``callback``; + - ``"apogee"`` (the rocket is coming down and above the ground) + or ``"burnout"`` (the motor has burned out); + - a number, the simulation time in s from which it fires. + + ``"apogee"``, ``"burnout"`` and a time stay ``True`` from that + moment on, so the event fires at every check after it. Set + ``trigger_only_once=True`` to fire once. + Default ``None``: the event fires every time it is checked. sampling_rate : float, optional - Evaluation frequency in hertz. If ``None`` (default), the event is - evaluated continuously at every solver time step. If a float (e.g. - ``10``), the event is sampled at that rate, i.e. every - ``1 / sampling_rate`` seconds. + How many times per second the event is checked, in Hz: with + ``10``, every 0.1 s. Default ``None``: the event is checked at the + end of every solver step. memory : dict, optional The event's own dictionary, kept from one check to the next and from trigger to callback. Read and write it as - ``context.event.memory``. Useful for counters, thresholds and - data shared between trigger and callback. It is restored to the - values given here when the event is reset for a new flight. - Defaults to an empty dict. - disable_on : str or int or float or callable, optional - Condition that automatically disables the event. May be a string - preset (``"apogee"`` or ``"burnout"``), a simulation time in seconds - (int or float), or a callable ``function(context)`` that returns - ``True`` when the event should be disabled. The times at which the - event is disabled are recorded in ``self.disabled_times``. - enable_on : str or int or float or callable, optional - Condition that automatically (re-)enables a disabled event. Uses the - same formats as ``disable_on`` (string preset, time threshold, or - callable predicate). The times at which the event is enabled are - recorded in ``self.enabled_times``. - exact_time_function : function, optional - Function that pins down the exact moment the event happened, between + ``context.memory``. It starts every flight with the values given + here. Defaults to an empty dictionary. + outputs : sequence of str or dict, optional + Values this event computes for other events to read. Give the name + of each output. It is then written and read through + ``context.outputs``, under the event's name in snake_case. For + example, an event named ``"Guidance"`` with + ``outputs=("pitch_setpoint",)`` writes its output in its callback, + and any other event reads it: + + .. code-block:: python + + context.outputs.guidance.pitch_setpoint = 0.1 # in "Guidance" + setpoint = context.outputs.guidance.pitch_setpoint # elsewhere + + An output can hold any value: a number, a vector, a text. It keeps + its value until it is written again, and only the event that + declared it can write it. Every output starts each flight as + ``None``, or at the value given with a dictionary, such as + ``outputs={"pitch_setpoint": 0.05}``. After the flight, + ``flight.event_outputs.guidance.pitch_setpoint`` is the list of + ``(time, value)`` pairs written. Two events with outputs cannot + have the same name. Default ``None``, no outputs. + name : str, optional + Name of the event. It names the event's records and outputs + (``flight.records.``) and appears in the log + messages. Defaults to ``"Custom Event"``. + enabled : bool, optional + Whether the event is checked from the start of the flight. An + event that is not can be turned on later by its ``enable_on``, or + by another event with ``context.commands.enable_event(event)``. + It can be changed after the event is built, ``event.enabled = + False``, and every flight from then on starts that way. + Defaults to ``True``. + enable_on : str, float or callable, optional + When a disabled event is turned on: ``"apogee"``, ``"burnout"``, a + simulation time in s, or a function ``f(context)`` that returns + ``True`` when the event should be turned on. The times it happens + are kept in ``event.enabled_times``. Default ``None``, never. + disable_on : str, float or callable, optional + When the event is turned off, in the same forms as ``enable_on``. + The times it happens are kept in ``event.disabled_times``. Default + ``None``, never. + trigger_only_once : bool, optional + If ``True``, the event turns itself off after the first time it + fires. Defaults to ``False``. + time_overshootable : bool, optional + How the flight reaches each sample of a sampled event. When + ``True`` (default) the solver may step past the sample and the + event runs at the interpolated state; if its commands or control + writes change the trajectory, the step is cut back to the sample + and the solver restarted there. When ``False`` every sample is a + point the solver stops at, so the event runs on the solver's own + state and no restart follows a change. The default is the faster + one, even for a controller that changes a control at every sample; + ``False`` is for an event that must run on the solver's own state + rather than an interpolated one. Always ``False`` for an event + without a ``sampling_rate``. Ignored when the flight has + ``time_overshoot=False``. + exact_time_function : callable, optional + Function that finds the exact moment the event happened, between two solver steps. It receives the same ``context`` as ``trigger``, worked out again at every moment the search tries, and returns a number that crosses zero (or the configured ``target``) at the - event. For example, to fire exactly at 500 m above ground level:: + event. For example, to fire exactly at 500 m above ground level: + + .. code-block:: python def altitude(context): return context.height_agl - 500 When a crossing is found, ``callback`` runs with the ``context`` - of that exact moment. Only supported for continuous events - (``sampling_rate=None``). + of that exact moment. Only for an event without a + ``sampling_rate``. exact_time_config : dict, optional How the exact moment is searched for. The ``"solver"`` key selects the method: ``"brentq"`` (default), ``"linear"`` or ``"cubic_hermite"``. Every solver accepts ``target`` (float, default ``0.0``); ``"brentq"`` also accepts ``xtol``, ``rtol`` and ``maxiter``; ``"cubic_hermite"`` requires ``derivative_function`` - (the time derivative of ``exact_time_function``, taking the same - ``context``). Any other key raises a ``ValueError``. See + (the derivative of ``exact_time_function`` with respect to time, + taking the same ``context``). Any other key raises a ``ValueError``. See :ref:`eventusage` for what each key does. - trigger_only_once : bool, optional - If ``True``, the event disables itself after the first successful - trigger. Useful for one-shot actions such as deployment or - separation. Defaults to ``False``. - time_overshootable : bool, optional - Enables overshoot-path evaluation for sampled events. Only relevant - when ``sampling_rate`` is a float. When ``True`` (default) the - simulation may integrate past the next sampling time and step back to - evaluate the event at the correct instant, allowing fewer integration - steps and faster simulation. When ``False`` the solver places strict - time nodes at multiples of the sampling interval, which is much - slower with no gain in accuracy. Automatically forced to ``False`` - when ``sampling_rate`` is ``None``. - changes_dynamics : bool, optional - Set to ``True`` when the callback changes anything that affects the - equations of motion. This includes changing an attribute of any - simulation object, and using the ``set_dynamics``, - ``start_flight_phase``, or ``terminate_flight`` commands. - Defaults to ``False``. - name : str, optional - Human-readable identifier used in logs and debugging. Defaults to - ``"Custom Event"``. - enabled : bool, optional - Initial enabled state. Disabled events can be re-enabled through the - ``enable`` command or via the ``enable_on`` parameter. Defaults to - ``True``. - verbose : bool, optional - When ``True``, the event prints a message and stores extra execution - logs in ``self.verbose_log`` whenever it triggers. Defaults to - ``False``. priority : int, optional - Integer event evaluation priority; lower numbers are evaluated - earlier. String aliases are not supported. Recommended mapping (used - by built-in events): + The order events are checked in when several are due at the same + time: lower numbers first. RocketPy's own events use: + + - 0: out of rail, apogee and landing + - 1: sensors + - 2: parachutes + - 3: controllers + - 4: events given to the flight (default) + verbose : bool, optional + When ``True``, every check of the event is reported by RocketPy's + logger at the ``INFO`` level instead of ``DEBUG``, which is shown + with ``Flight(..., verbose=True)`` or ``rocketpy.enable_logging()``. + Defaults to ``False``. - - 0: Core events (out of rail, apogee, landing) - - 1: Sensor events - - 2: Parachute events - - 3: Controller events - - 4: Custom / user-defined events (default) + Raises + ------ + ValueError + If ``callback``, ``trigger`` or ``exact_time_function`` is not a + function of the context alone, if a name given to ``trigger``, + ``enable_on`` or ``disable_on`` is not ``"apogee"`` or + ``"burnout"``, if an output name cannot be used, if + ``exact_time_config`` has a key its solver does not take, or if + ``exact_time_function`` is given with a ``sampling_rate``. + TypeError + If ``enable_on`` or ``disable_on`` is not one of the accepted + forms. See Also -------- + rocketpy.EventContext : The values a trigger and a callback are given. :ref:`eventusage` : User guide for building and using events. """ self.callback = self.__validate_callback(callback) self.name = name self.trigger = self.__validate_trigger(trigger) if trigger is not None else None self.memory = memory if memory is not None else {} + self._output_defaults = self.__validate_outputs(outputs) + self._outputs = deepcopy(self._output_defaults) + self._output_history = {} self.sampling_rate = sampling_rate self.trigger_only_once = trigger_only_once - self.changes_dynamics = bool(changes_dynamics) self.priority = priority self.time_overshootable = bool(time_overshootable) if self.time_overshootable and self.sampling_rate is None: self.time_overshootable = False self._initial_enabled = bool(enabled) - self.enabled = bool(enabled) + self._enabled = bool(enabled) self.verbose = verbose - self.verbose_log = [] - self.callback_log = [] self.triggered_times = [] - self._trigger_checked = False + self._records = {} self._forget_previous_check() self.is_discrete = self.sampling_rate is not None @@ -224,8 +256,6 @@ def altitude(context): self.enabled_times = [] self.disabled_times = [] self._initial_memory = deepcopy(self.memory) - self._initial_enabled_times = list(self.enabled_times) - self._initial_disabled_times = list(self.disabled_times) self.commands = Commands() @@ -244,37 +274,10 @@ def altitude(context): if self.exact_time_function is not None and self.sampling_rate is not None: raise ValueError( - "exact_time_function is only supported for continuous hooks " - "with sampling_rate=None." + "exact_time_function is only supported for an event without a " + "sampling_rate." ) - def _reset_commands(self): - self.commands.reset() - - def reset(self): - """Reset event runtime state. - - This clears per-run command/results state and internal logging buffers, - restores the initial ``enabled`` flag, and restores ``memory`` to its - construction-time snapshot. - - Returns - ------- - None - """ - self._reset_commands() - self.enabled = self._initial_enabled - self.verbose_log.clear() - self.callback_log.clear() - self.triggered_times.clear() - self._trigger_checked = False - self._forget_previous_check() - self.memory = deepcopy(self._initial_memory) - - # Restore enable/disable time history to initial snapshot - self.enabled_times = list(self._initial_enabled_times) - self.disabled_times = list(self._initial_disabled_times) - def __repr__(self): return ( f"{self.__class__.__name__}(name={self.name!r}, enabled={self.enabled}, " @@ -291,85 +294,95 @@ def __str__(self): f"trigger_only_once={self.trigger_only_once})" ) - def _forget_previous_check(self): - """Drop what this event saw the last time it was checked. - - Called when the event is built and again when it is reset, so a second - flight does not compare its first check against the last check of the - one before it. The context answers ``previous_state`` and - ``previous_time`` from these. - """ - self._previous_view = None - self._previous_state = None - self._previous_time = None - self._previous_raw_state = None - self._previous_phase_names = () + # Running the event def __call__(self, context, trigger_only=False, callback_only=False, reset=True): - """Evaluate the event trigger and execute the callback if triggered. + """Check the event: evaluate its trigger and, if it fires, run its + callback. Parameters ---------- context : EventContext - The values to hand the trigger and callback. It is shared with the - other events checked in this solver step, so this event is bound to - it here and unbound again when the next event is bound. + The values the trigger and the callback are given. It is shared + with the other events checked in this solver step, and points at + this event until the next one is checked. trigger_only : bool, optional - If True, only evaluate the trigger condition without executing the - callback. The enable_on function is also called. + If ``True``, the trigger and ``enable_on`` are evaluated and the + callback is not run. Defaults to ``False``. callback_only : bool, optional - If True, only execute the callback without evaluating the trigger - condition. The exact time function and disable_on function are also - called. + If ``True``, the callback is run without evaluating the trigger. + ``exact_time_function`` and ``disable_on`` are still evaluated. + Defaults to ``False``. reset : bool, optional - If True (default), reset the event's queued commands (via - ``_reset_commands``) before evaluating the trigger. + If ``True`` (default), the commands left by the previous check are + cleared first. Returns ------- bool - True if the event was triggered, False otherwise. + ``True`` if the event fired, ``False`` otherwise. """ - context.bind(self) - - if self.enabled is False: - # If event is disabled, only evaluate enable_on function if it exists. - if self._call_enable_on(context) is False: - return False + try: + context.bind(self) + except AttributeError: + raise TypeError( + "An event is checked with an EventContext, which the flight " + f"builds, not with a {type(context).__name__}. To check an event " + "by hand, build one: EventContext(time=0.0, " + "canonical_state=state, raw_state=state, phase_names=())." + ) from None if reset: - self._reset_commands() + self.commands.reset() + + # If event is disabled, only evaluate enable_on function if it exists. + if self._call_enable_on(context) is False: + return False # --- Trigger Phase --- # Skip evaluating triggers if we are only running the callback. if callback_only is False: - if self._call_enable_on(context) is False: - return False - + # Kept for the next check, triggered or not. Read from the context + # now, since it is rewritten during the step, and stored only after + # the callback, which must still see the check before this one. + # Read before the trigger, so a context that lacks them, which no + # flight builds, is refused before the trigger is called. + try: + check = ( + context["canonical_state"], + context["time"], + context["raw_state"], + context["phase_names"], + ) + except KeyError as error: + raise KeyError( + f"The event context has no {error.args[0]!r}. During a flight " + "the context is built by the flight. One built by hand needs " + "'time', 'canonical_state' (the 13 states), 'raw_state' (the " + "states of the flight phase being flown) and 'phase_names' " + "(the names of the states the phase adds, or an empty tuple)." + ) from None triggered = self._call_trigger(context) - - # Remember this check, whether or not it triggered, so the next one - # can be compared against it. Recorded before the early return so a - # trigger that did not fire is still part of the sequence. The - # plain arrays are kept, with the names of the phase's own states; - # the context builds a state view from them if asked. - self._previous_state = context["canonical_state"] - self._previous_time = context["time"] - self._previous_raw_state = context["raw_state"] - self._previous_phase_names = context["phase_names"] - - if triggered is False: - return False - - if trigger_only: - return True + if triggered is False or trigger_only: + ( + self._previous_state, + self._previous_time, + self._previous_raw_state, + self._previous_phase_names, + ) = check + return triggered # --- Callback Phase --- context = self._call_exact_time(context) - callback_log = self.callback(context) - - self.callback_log.append(callback_log) + self.callback(context) + if callback_only is False: + ( + self._previous_state, + self._previous_time, + self._previous_raw_state, + self._previous_phase_names, + ) = check self.triggered_times.append(context.get("time")) self._call_disable_on(context) @@ -377,14 +390,13 @@ def __call__(self, context, trigger_only=False, callback_only=False, reset=True) if self.trigger_only_once: self.commands.disable() - self._log( - triggered=True, - context=context, - ) + self._log(triggered=True, context=context) return True def _call_enable_on(self, context): - if not self.enabled: + """Return ``False`` if the event is disabled and stays so. If its + ``enable_on`` condition is met, ask the flight to enable it.""" + if not self._enabled: # No enable_on function. Event stays disabled if self.enable_on is None: self._log(triggered=False, context=context) @@ -403,6 +415,8 @@ def _call_enable_on(self, context): return False def _call_trigger(self, context): + """Return whether the trigger fires. An event without one always + does.""" if self.trigger is not None: if not self.trigger(context): self._log(triggered=False, context=context) @@ -440,8 +454,7 @@ def _compute_exact_time(self, context): ``context`` itself is shared with the other events of this step and is left as it is. """ - flight = context["flight"] - solution = flight.solution + solution = context._solution # pylint: disable=protected-access if len(solution) < 2: raise ValueError( "It fired before the first solver step, so there is no solver " @@ -456,7 +469,8 @@ def _compute_exact_time(self, context): stored = {t1: state1} if len(solution) - 2 >= solution.phases[-1].start: stored[t0] = state0 - dense_output = context["phase"].solver.dense_output() + phase = context._phase # pylint: disable=protected-access + dense_output = phase.solver.dense_output() # A solver may ask for the value and its rate at the same moment, so the # last context built is kept. @@ -466,7 +480,14 @@ def context_at(t): if t not in cached: raw_state = stored[t] if t in stored else dense_output(t) cached.clear() - cached[t] = context.at(t, raw_state) + # A copy, since the other events of this step share ``context`` + moved = EventContext( + context, + solution=solution, + phase=phase, + output_events=context._output_events, # pylint: disable=protected-access + ) + cached[t] = refresh_event_kwargs(moved, t, raw_state) return cached[t] options = dict(self.exact_time_config) @@ -511,6 +532,8 @@ def context_at(t): return exact_context def _call_disable_on(self, context): + """Ask the flight to disable the event if its ``disable_on`` condition + is met.""" if self.disable_on is not None: try: if self.disable_on(context): @@ -521,32 +544,201 @@ def _call_disable_on(self, context): UserWarning, ) - def _log( - self, - triggered, - context, - callback_executed=None, - skip_reason=None, - ): - if self.verbose: - self.verbose_log.append( - { - "time": context.get("time"), - "triggered": triggered, - "callback_executed": callback_executed, - "skip_reason": skip_reason, - } - ) - logger.debug( - "Event '%s' at t=%s: triggered=%s, callback_executed=%s, skip_reason=%s", + def _log(self, triggered, context): + """Report one check of the event to RocketPy's logger, at the ``INFO`` + level for a verbose event and ``DEBUG`` otherwise.""" + logger.log( + logging.INFO if self.verbose else logging.DEBUG, + "Event '%s' at t=%s: triggered=%s", self.name, context.get("time"), triggered, - callback_executed, - skip_reason, ) + # What the event keeps: its outputs and records + + @property + def outputs(self): + """The names of the values this event computes for other events to + read, as ``context.outputs..``. + Empty for an event without outputs. + + Returns + ------- + tuple of str + """ + return tuple(self._output_defaults) + + @property + def output_defaults(self): + """The value each output starts every flight with, by name. + + Returns + ------- + dict + """ + return dict(self._output_defaults) + + @property + def output_history(self): + """What this event wrote to its outputs, by name. + + Each output is the list of ``(time, value)`` pairs written, with the + value as it was when written. The list starts empty at every flight. + ``flight.event_outputs`` holds the outputs of every event of a flight. + + Returns + ------- + dict + Output name to list of ``(time, value)``. + """ + return {name: list(points) for name, points in self._output_history.items()} + + def _write_output(self, time, name, value): + """Set an output at ``time``. The value is kept as given for the events + that read it, and a copy is kept with its time, so a later change to + the object does not change what was written.""" + self._outputs[name] = value + self._output_history.setdefault(name, []).append((time, copied_value(value))) + + @property + def records(self): + """What this event recorded with ``context.record``, by name, exactly + as recorded. + + Each record is the list of ``(time, value)`` pairs the event stored, + with ``value`` the object passed to ``context.record``: a number, a + vector, a text, a dictionary. Records exist only at the times the + event ran, and start empty at every flight. ``flight.records`` holds + the records of every event of a flight. + + Returns + ------- + dict + Record name to list of ``(time, value)``. + """ + return {name: list(points) for name, points in self._records.items()} + + def _record(self, time, values): + """Store named values at ``time``, as given: a number as it is, + anything else as a copy, so a later change to the object does not + change what was recorded.""" + for name, value in values.items(): + self._records.setdefault(name, []).append((time, copied_value(value))) + + # Starting a new flight, and going back in time + + @property + def enabled(self): + """Whether the event is checked. + + Before a flight it is how the event starts each flight. During a + flight and after it, it is whether the event is on at that moment: a + flight turns an event on or off through its ``enable_on`` and + ``disable_on``, ``trigger_only_once`` and the commands of events. + + Setting it, ``event.enabled = False``, chooses how the event starts + every flight from then on. Inside a callback, use + ``context.commands.disable()`` or ``context.commands.enable_event`` + instead, which act on the flight being flown only. + """ + return self._enabled + + @enabled.setter + def enabled(self, value): + # Set from outside a flight: also what the next flights start from. + # A flight writes ``_enabled`` alone, which ``reset`` undoes + self._enabled = self._initial_enabled = bool(value) + + def reset(self): + """Prepare the event for a new flight. + + The event is enabled or not as it was built, or as ``enabled`` was + set since, its memory and outputs are back at the values it was built + with, and its records and the times it fired or was turned on and off + are cleared. A flight calls this on each of its events when it starts. + """ + self.commands.reset() + self._enabled = self._initial_enabled + self._records = {} + self._outputs = deepcopy(self._output_defaults) + self._output_history = {} + self.triggered_times.clear() + self._forget_previous_check() + self.memory = deepcopy(self._initial_memory) + + self.enabled_times = [] + self.disabled_times = [] + + def _forget_previous_check(self): + """Drop what this event saw the last time it was checked. + + Called when the event is built and again when it is reset, so a second + flight does not compare its first check against the last check of the + one before it. The context answers ``previous_state`` and + ``previous_time`` from these. + """ + self._previous_view = None + self._previous_state = None + self._previous_time = None + self._previous_raw_state = None + self._previous_phase_names = () + + def _check_state(self): + """Whether the event is enabled and what it saw at its previous check: + what a rollback puts back with :meth:`_restore_check_state`.""" + return ( + self._enabled, + self._previous_state, + self._previous_time, + self._previous_raw_state, + self._previous_phase_names, + ) + + def _restore_check_state(self, saved): + """Put back what :meth:`_check_state` returned.""" + ( + self._enabled, + self._previous_state, + self._previous_time, + self._previous_raw_state, + self._previous_phase_names, + ) = saved + + def _drop_after(self, time): + """Forget what was recorded, what was written to the outputs, and when + the event ran or was turned on or off, after ``time``, a moment the + flight went back to. An output is again the last value written up to + ``time``, or the value it started the flight with.""" + for points in self._records.values(): + while points and points[-1][0] > time: + points.pop() + for name, points in self._output_history.items(): + dropped = False + while points and points[-1][0] > time: + points.pop() + dropped = True + if dropped: + self._outputs[name] = copied_value( + points[-1][1] if points else self._output_defaults[name] + ) + for times in (self.triggered_times, self.enabled_times, self.disabled_times): + while times and times[-1] > time: + times.pop() + + # Checks of the arguments given to the event + + def __validate_callback(self, callback): + """Check that ``callback`` is a function of the context alone.""" + if not callable(callback): + raise ValueError("Callback must be a callable.") + + # What it returns is ignored, so its return annotation is not checked + return self.__validate_context_function(callback, "Callback function") + def __validate_trigger(self, trigger): + """Return the trigger as a function of the context: the one given, the + condition a preset names, or "the time has reached this number".""" if isinstance(trigger, str): if trigger not in PRESETS: raise ValueError( @@ -571,30 +763,35 @@ def __validate_trigger(self, trigger): return trigger - def __validate_callback(self, callback): - if not callable(callback): - raise ValueError("Callback must be a callable.") - - callback = self.__validate_context_function(callback, "Callback function") - - return_annotation = inspect.signature(callback).return_annotation - valid_return_annotations = ( - inspect.Signature.empty, - type(None), - None, - dict, - "dict", - ) - - if return_annotation not in valid_return_annotations: + def __validate_outputs(self, outputs): + """Return the event's outputs as a dictionary of name to the value + each starts a flight with (``None`` unless given).""" + if not outputs: + return {} + defaults = dict(outputs) if isinstance(outputs, dict) else {} + names = tuple(outputs) + for name in names: + # Read as an attribute, ``context.outputs..`` + if ( + not isinstance(name, str) + or not name.isidentifier() + or keyword.iskeyword(name) + or name.startswith("_") + ): + raise ValueError( + f"The output name {name!r} of the event '{self.name}' cannot " + "be used: a name is made of letters, digits and underscores, " + "and starts with a letter." + ) + if len(set(names)) != len(names): raise ValueError( - "Callback function return annotation must be None, dict, or unspecified when provided." + f"The event '{self.name}' has two outputs with the same name." ) - - return callback + return {name: defaults.get(name) for name in names} def __validate_gate_condition(self, condition, parameter_name): - """Normalize a gate condition to a callable or None.""" + """Return an ``enable_on`` or ``disable_on`` condition as a function of + the context, in the same forms as a trigger, or ``None``.""" if condition is None: return None if isinstance(condition, str): diff --git a/rocketpy/simulation/events/event_builders.py b/rocketpy/simulation/events/event_builders.py index 9d6b478be..343a3b616 100644 --- a/rocketpy/simulation/events/event_builders.py +++ b/rocketpy/simulation/events/event_builders.py @@ -1,20 +1,23 @@ +from functools import partial + from ..events.event import Event -def out_of_rail_trigger(context): +def out_of_rail_trigger(flight, context): """Check whether the rocket has left the launch rail. Parameters ---------- + flight : Flight + The flight the event belongs to. context : EventContext - Event context containing ``flight`` and ``state``. + Event context containing ``state``. Returns ------- bool ``True`` when the rail-exit condition is satisfied. """ - flight = context["flight"] state = context["canonical_state"] return len(flight.out_of_rail_state) == 1 and ( state[0] ** 2 + state[1] ** 2 + (state[2] - flight.env.elevation) ** 2 @@ -22,7 +25,7 @@ def out_of_rail_trigger(context): ) -def out_of_rail_callback(context): +def out_of_rail_callback(flight, context): """Handle the rail-exit event. The callback records the rail-exit state and time, switches the derivative @@ -30,15 +33,16 @@ def out_of_rail_callback(context): Parameters ---------- + flight : Flight + The flight the event belongs to. context : EventContext - Event context containing ``flight`` and ``event``. + Event context containing ``event``. Returns ------- None This callback performs in-place updates on ``flight`` and ``event``. """ - flight = context["flight"] event = context["event"] flight.out_of_rail_time = context["time"] @@ -56,13 +60,15 @@ def out_of_rail_callback(context): event.commands.start_flight_phase("free_flight") -def out_of_rail_exact_time_function(context): +def out_of_rail_exact_time_function(flight, context): """Evaluate the rail-exit event function. Parameters ---------- + flight : Flight + The flight the event belongs to. context : EventContext - Event context containing ``flight`` and ``state``. + Event context containing ``state``. Returns ------- @@ -70,7 +76,6 @@ def out_of_rail_exact_time_function(context): Value of the event function. The root corresponds to the effective rail length being reached. """ - flight = context["flight"] state = context["canonical_state"] return ( state[0] ** 2 @@ -80,20 +85,21 @@ def out_of_rail_exact_time_function(context): ) -def out_of_rail_exact_time_derivative(context): +def out_of_rail_exact_time_derivative(flight, context): """Evaluate the time derivative of the rail-exit event function. Parameters ---------- + flight : Flight + The flight the event belongs to. context : EventContext - Event context containing ``flight`` and ``state``. + Event context containing ``state``. Returns ------- float Time derivative of :func:`out_of_rail_exact_time_function`. """ - flight = context["flight"] state = context["canonical_state"] return 2.0 * ( state[0] * state[3] @@ -102,13 +108,15 @@ def out_of_rail_exact_time_derivative(context): ) -def apogee_trigger(context): +def apogee_trigger(flight, context): """Check whether the apogee event should fire. Parameters ---------- + flight : Flight + The flight the event belongs to. context : EventContext - Event context containing ``flight`` and ``state``. + Event context containing ``state``. Returns ------- @@ -116,7 +124,6 @@ def apogee_trigger(context): ``True`` when the vertical velocity crosses from positive to non-positive after the apogee state has not yet been recorded. """ - flight = context["flight"] state = context["canonical_state"] if len(flight.apogee_state) != 1 or len(flight.solution) < 2: return False @@ -126,7 +133,7 @@ def apogee_trigger(context): return previous_vz > 0 >= current_vz -def apogee_callback(context): +def apogee_callback(flight, context): """Handle the apogee event. The callback records the apogee state and time, updates the apogee position @@ -134,15 +141,16 @@ def apogee_callback(context): Parameters ---------- + flight : Flight + The flight the event belongs to. context : EventContext - Event context containing ``flight`` and ``event``. + Event context containing ``event``. Returns ------- bool Always returns ``False`` so the event remains non-blocking. """ - flight = context["flight"] event = context["event"] flight.apogee_state = context["canonical_state"] flight.apogee_time = context["time"] @@ -178,19 +186,17 @@ def impact_trigger(context): Parameters ---------- context : EventContext - Event context containing ``flight`` and ``state``. + Event context containing ``height_agl``. Returns ------- bool ``True`` when altitude is below the environment elevation. """ - flight = context["flight"] - state = context["canonical_state"] - return state[2] < flight.env.elevation + return context["height_agl"] < 0 -def impact_callback(context): +def impact_callback(flight, context): """Handle the impact event. The callback stores the impact state and velocity and terminates the flight @@ -198,15 +204,16 @@ def impact_callback(context): Parameters ---------- + flight : Flight + The flight the event belongs to. context : EventContext - Event context containing ``flight`` and ``event``. + Event context containing ``event``. Returns ------- None This callback performs in-place updates on ``flight`` and ``event``. """ - flight = context["flight"] event = context["event"] flight.impact_state = context["canonical_state"] @@ -251,8 +258,17 @@ def impact_event_exact_time_derivative(context): return context["canonical_state"][5] -def build_core_events(): - """Build the default core flight events. +def build_core_events(flight): + """Build the default core flight events of ``flight``. + + The events are the flight's own: they hold the flight and write its + results (rail exit, apogee, impact) on it, so the flight never has to be + handed to them through the context, which users' functions also see. + + Parameters + ---------- + flight : Flight + The flight the events belong to. Returns ------- @@ -260,14 +276,14 @@ def build_core_events(): ``(out_of_rail_event, apogee_event, impact_event)``. """ out_of_rail_event = Event( - trigger=out_of_rail_trigger, - callback=out_of_rail_callback, + trigger=partial(out_of_rail_trigger, flight), + callback=partial(out_of_rail_callback, flight), name="Out Of Rail", memory=None, - exact_time_function=out_of_rail_exact_time_function, + exact_time_function=partial(out_of_rail_exact_time_function, flight), exact_time_config={ "solver": "cubic_hermite", - "derivative_function": out_of_rail_exact_time_derivative, + "derivative_function": partial(out_of_rail_exact_time_derivative, flight), }, sampling_rate=None, trigger_only_once=True, @@ -276,8 +292,8 @@ def build_core_events(): ) apogee_event = Event( - trigger=apogee_trigger, - callback=apogee_callback, + trigger=partial(apogee_trigger, flight), + callback=partial(apogee_callback, flight), name="Apogee", memory=None, exact_time_function=apogee_event_exact_time_function, @@ -289,7 +305,7 @@ def build_core_events(): impact_event = Event( trigger=impact_trigger, - callback=impact_callback, + callback=partial(impact_callback, flight), name="Impact", memory=None, exact_time_function=impact_event_exact_time_function, diff --git a/rocketpy/simulation/events/event_context.py b/rocketpy/simulation/events/event_context.py index 36f38a723..cec084fdd 100644 --- a/rocketpy/simulation/events/event_context.py +++ b/rocketpy/simulation/events/event_context.py @@ -1,5 +1,6 @@ -from ..helpers.dynamics import CANONICAL_INDEX -from .state import _State, _StateDot +from ..helpers.conditions import FlightConditions +from ..helpers.state import CANONICAL_INDEX, _State, _StateDot +from .views import ControlsView, OutputsView, SensorsView # Altitude's slot in the canonical state. Reading it by position avoids a # by-name lookup on every event check. @@ -13,15 +14,14 @@ "state_dot", "canonical_state_dot", "raw_state_dot", - "pressure", - "step_size", + "conditions", ) # Keys answered from the event being evaluated, never stored in the context. _PREVIOUS_KEYS = frozenset({"previous_state", "previous_time"}) -class EventContext(dict): +class EventContext(dict): # pylint: disable=too-many-public-methods """The values an event's trigger and callback are given. One of these is built per solver step and shared by every event checked in @@ -31,18 +31,26 @@ class EventContext(dict): holds. Some values are only worked out when they are first read: ``state``, - ``state_dot``, ``pressure`` and ``step_size``. Once read they are kept for - the rest of the step, so a second event reading the same value in the same - step pays nothing. A value no function reads costs nothing at all. + ``state_dot``, ``conditions``, the air data (``pressure``, ``density``, + ``mach``, ...) and ``phase_name``. Once read, a value is kept for the rest + of the step, so a second event reading it in the same step does not work it + out again. ``previous_state`` and ``previous_time`` describe the previous check of the event being evaluated, so they are answered from that event and never stored here. - A context is shared and rewritten as the step is worked through, so nothing - may hold on to it, and a function should not add values to it: whatever it - writes is seen by the other events of the step. Keep an event's own data in - ``context.event.memory``. + The same context is given to every event of the step, and it is rewritten + as the step goes on. Do not keep a reference to it after the function + returns, and do not add values to it, since the other events of the step + would see them. Keep an event's own data in ``context.memory``. + + During a flight the context is built by the flight. To check an event by + hand, as in a test, build one with at least the time and the state: + ``EventContext(time=0.0, canonical_state=state, raw_state=state, + phase_names=())``, with ``state`` the 13 values ``[x, y, z, vx, vy, vz, + e0, e1, e2, e3, w1, w2, w3]``. An event checked with anything less raises + an error that names what is missing. """ # The values are stored as dictionary items, which is what RocketPy's own @@ -52,14 +60,105 @@ class EventContext(dict): # current phase integrates, which ``phase_names`` names in order. The # properties below are the documented way in. - __slots__ = ("_owned",) + __slots__ = ("_solution", "_phase", "_output_events") - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - # Keys the event currently being evaluated owns, which are cleared - # before the next event is bound. Keys every event writes are not - # listed, since they are overwritten rather than left behind. - self._owned = () + def __init__(self, *args, solution=None, phase=None, output_events=None, **values): + """Build a context from its values, as a dict is built. + + Parameters + ---------- + *args, **values + The values, as given to ``dict``. + solution : Solution, optional + The flight's solution so far. Default ``None``, outside a flight. + phase : _FlightPhase, optional + The flight phase being flown. Default ``None``, outside a flight. + output_events : dict, optional + The flight's events with outputs, by their name in snake_case. + Default ``None``, no outputs. + """ + super().__init__(*args, **values) + self._solution = solution + self._phase = phase + self._output_events = output_events + + def __dir__(self): + # What a trigger or callback reads, without the dictionary's own + # methods, so that completion in a notebook lists only these + return [ + name + for name, member in vars(EventContext).items() + if isinstance(member, property) or name == "record" + ] + + def __repr__(self): + """Return a summary of what a trigger or callback can read and write + here, with the names to use: ``print(context)`` inside a function + shows them. The equations of motion and the air data are not + evaluated for it.""" + lines = [] + + def add(section): + # A context built outside a flight may lack a part: skip it + try: + lines.extend(section()) + except Exception: # pylint: disable=broad-exception-caught + pass + + def header(): + parts = [f"EventContext at t = {self['time']:.6g} s"] + if self._phase is not None: + parts.append(f"phase '{self._phase.name}'") + if "event" in self: + parts.append(f"event '{self['event'].name}'") + return [", ".join(parts)] + + def state(): + return [f" state (context.state.): {', '.join(self['state'].names)}"] + + def height(): + return [f" height_agl: {self['height_agl']:.6g} m"] + + def controls(): + view = self.controls + groups = [ + f" {key}: {', '.join(view[name])}" for name, key in _keys(view) + ] + return [" controls (context.controls..):", *groups] + + def sensors(): + view = self.sensors + groups = [ + f" {key}: {', '.join(view[name])}" for name, key in _keys(view) + ] + return [" sensors (context.sensors..):", *groups] + + def outputs(): + view = self.outputs + groups = [ + f" {key}: {', '.join(view[name])}" for name, key in _keys(view) + ] + return [" outputs (context.outputs..):", *groups] + + def memory(): + keys = ", ".join(map(str, self["event"].memory)) or "empty" + return [f" memory (context.memory[]): {keys}"] + + def _keys(view): + # Each group of a view by its name as given, with its key; a view + # with no groups raises, so its section is left out + pairs = list(view._names().items()) # pylint: disable=protected-access + if not pairs: + raise LookupError + return pairs + + for section in (header, state, height, controls, sensors, outputs, memory): + add(section) + shown = {"time", "state", "height_agl", "controls", "sensors", "outputs"} + shown |= {"memory", "phase_name", "event"} + rest = [name for name in dir(self) if name not in shown] + lines.append(f" also: {', '.join(rest)}") + return "\n".join(lines) def __missing__(self, key): if key in _PREVIOUS_KEYS: @@ -93,12 +192,17 @@ def __missing__(self, key): ) elif key in ("canonical_state_dot", "raw_state_dot"): self._compute_derivatives() - elif key == "pressure": - self["pressure"] = self["environment"].pressure.get_value_opt( - self["canonical_state"][_Z_SLOT] + elif key == "conditions": + self["conditions"] = FlightConditions( + self["rocket"], + self["environment"], + self["time"], + self["canonical_state"], + self["phase_names"], + self["raw_state"], ) - elif key == "step_size": - self["step_size"] = infer_step_size(self["flight"], self["time"]) + elif key == "phase_name": + self["phase_name"] = self._phase.name else: raise KeyError(key) return self[key] @@ -112,9 +216,9 @@ def get(self, key, default=None): def _compute_derivatives(self): """Evaluate the equations of motion once, for both derivative views.""" - current = self["flight"].solution.phases[-1] + current = self._solution.phases[-1] raw_state = self["raw_state"] - raw_state_dot = self["phase"].dynamics(self["time"], raw_state) + raw_state_dot = self._phase.dynamics(self["time"], raw_state) self["raw_state_dot"] = raw_state_dot self["canonical_state_dot"] = current.canonical_derivative( raw_state_dot, raw_state @@ -128,43 +232,32 @@ def bind(self, event): event : Event The event being checked. """ - for key in self._owned: - del self[key] - self._owned = () self["event"] = event self["sampling_rate"] = event.sampling_rate - def own(self, **values): - """Add values that belong to the event being evaluated alone. + def record(self, **values): + """Record named values at the current time, to read after the flight. - They are removed again when the next event is bound, so no other event - of the step sees them. A controller uses this for ``controller`` and - the names of the objects it drives. - """ - self.update(values) - self._owned = self._owned + tuple(values) + .. code-block:: python - def at(self, time, raw_state): - """Return a copy of this context describing another moment of the step. + context.record(estimated_apogee=3012.0, error=0.4) + context.record(command=[0.1, -0.2, 0.0], mode="coast") - Everything that depends on the moment is worked out again for ``time``, - or dropped so that it is worked out when next read. The context itself - is not changed. + After the flight, ``event.records["estimated_apogee"]`` and + ``flight.records..estimated_apogee`` (the records of + every event, by the event's name) give each name as the list of + ``(time, value)`` pairs recorded, with the value exactly as given. + Unlike ``context.memory``, which keeps what the next call needs, a + record keeps every value with its time. Parameters ---------- - time : float - The moment, in seconds, inside the current solver step. - raw_state : sequence of float - The current phase's raw state at ``time``. - - Returns - ------- - EventContext + **values : float or object + The values to record, by name. A value that is not a number is + copied, so changing the object afterwards does not change what was + recorded. """ - moved = EventContext(self) - moved._owned = self._owned - return refresh_event_kwargs(self["flight"], moved, time, raw_state) + self["event"]._record(self["time"], values) # pylint: disable=protected-access @property def time(self): @@ -178,17 +271,20 @@ def state(self): @property def state_dot(self): - """Time derivative of each state, read as ``state_dot.az``.""" + """Derivative of each state with respect to time, read by name as + ``state_dot.az``.""" return self["state_dot"] @property def previous_state(self): - """The ``state`` at this event's previous check, or ``None``.""" + """The ``state`` at this event's previous check, or ``None`` on the + first check.""" return self["previous_state"] @property def previous_time(self): - """The ``time`` of this event's previous check, in s, or ``None``.""" + """The ``time`` of this event's previous check, in s, or ``None`` on + the first check.""" return self["previous_time"] @property @@ -196,19 +292,71 @@ def height_agl(self): """Height of the rocket above ground level, in m.""" return self["height_agl"] + @property + def conditions(self): + """The air data (``pressure``, ``density``, ``mach``, ...) as one + object, a :class:`rocketpy.control.FlightConditions`. It is the object a + controllable's methods receive inside the equations of motion, so use + it to pass the air data on to one of them. To read a single value, + ``context.pressure`` is shorter.""" + return self["conditions"] + + # The air data are worked out by the conditions object when first read, + # and kept for the rest of the step with it. + @property def pressure(self): - """Atmospheric pressure at the rocket's altitude, in Pa.""" - return self["pressure"] + """Air pressure at the rocket's altitude, in Pa.""" + return self["conditions"].pressure + + @property + def density(self): + """Air density at the rocket's altitude, in kg/m³.""" + return self["conditions"].density @property - def step_size(self): - """How long the simulation has been inside this solver step, in s.""" - return self["step_size"] + def speed_of_sound(self): + """Speed of sound at the rocket's altitude, in m/s.""" + return self["conditions"].speed_of_sound + + @property + def wind_velocity(self): + """Wind velocity at the rocket's altitude, in m/s, in the Earth frame + (x East, y North, z up).""" + return self["conditions"].wind_velocity + + @property + def stream_velocity(self): + """Velocity of the air relative to the rocket, in m/s, in the rocket's + body frame (z along the rocket's axis, toward the nose).""" + return self["conditions"].stream_velocity + + @property + def stream_speed(self): + """Speed of the air relative to the rocket, in m/s.""" + return self["conditions"].stream_speed + + @property + def mach(self): + """Mach number of the air relative to the rocket.""" + return self["conditions"].mach + + @property + def dt(self): + """Time since this event was last checked, in s. For a controller, this + is the time since its previous run. On the first check it is + ``1 / sampling_rate``, or ``None`` for an event with no + ``sampling_rate``, which is checked at every solver step.""" + previous_time = self["previous_time"] + if previous_time is not None: + return self["time"] - previous_time + sampling_rate = self["sampling_rate"] + return None if sampling_rate is None else 1 / sampling_rate @property def sampling_rate(self): - """How often the event being checked is sampled, in Hz, or ``None``.""" + """How often the event being checked is sampled, in Hz, or ``None`` for + an event checked at every solver step.""" return self["sampling_rate"] @property @@ -217,67 +365,109 @@ def event(self): return self["event"] @property - def flight(self): - """The flight being simulated.""" - return self["flight"] + def memory(self): + """A dictionary that belongs to the event being checked and is kept + from one check to the next. Store in it what the next call needs, such + as the integral of a PID controller. The same as + ``context.event.memory``.""" + return self["event"].memory @property - def rocket(self): - """The rocket being flown.""" - return self["rocket"] + def commands(self): + """The requests the event being checked makes to the flight, such as + ``context.commands.terminate_flight()`` or + ``context.commands.set_dynamics(...)``. This is the only way a trigger + or callback can change the course of the flight. A request takes + effect once the function returns. The same as + ``context.event.commands``. See + :class:`rocketpy.simulation.events.commands.Commands`.""" + return self["event"].commands @property - def environment(self): - """The environment the rocket flies in.""" - return self["environment"] + def controls(self): + """The rocket's control inputs, read and written by the name of the + controllable in snake_case, then the name of the control: + + .. code-block:: python + + context.controls.air_brakes.deployment_level = 0.5 + context.controls["Air Brakes"].deployment_level = 0.5 + context.controls[air_brakes].deployment_level = 0.5 + context.controls.canards[f"fin_{i}"] = 0.05 + + The second and third lines find the controllable by its name as given + and by the object itself. The last one writes a control whose name is + built in a loop. ``list(context.controls)`` gives the names of the + controllables. + + A value written outside the control's limits is moved to the nearest + limit once the callback returns. The new value acts from the event's + time on: if the solver step had already gone past that time, the step + is cut there. See + :class:`rocketpy.simulation.events.views.ControlsView`. + """ + owners = self.get("control_owners") + if owners is None: + owners = getattr(self.get("rocket"), "controllables", ()) + return ControlsView(self["controls"], owners) @property - def phase(self): - """The current flight phase.""" - return self["phase"] + def outputs(self): + """The values the events of the flight share with each other. An + event declares its outputs when it is built (``outputs=`` of + :class:`rocketpy.Event` and :class:`rocketpy.Controller`), writes them + under its own name in snake_case, and every other event reads them: - @property - def sensors(self): - """The rocket's sensors, in the order they were added.""" - return self["sensors"] + .. code-block:: python - @property - def sensors_by_name(self): - """The rocket's sensors, by name.""" - return self["sensors_by_name"] + context.outputs.guidance.pitch_setpoint = 0.1 # in "Guidance" + setpoint = context.outputs.guidance.pitch_setpoint # elsewhere + + An output can hold any value and keeps it until it is written again. + Only the event that declared an output can write it. + ``list(context.outputs)`` gives the names of the events with outputs. + See :class:`rocketpy.simulation.events.views.OutputsView`. + """ + return OutputsView(self._output_events or {}, self.get("event"), self["time"]) @property - def controller(self): - """The controller being run, or ``None`` outside a controller.""" - return self.get("controller") + def rocket(self): + """The rocket being flown. Do not change it here, since the same rocket + object is used by later flights.""" + return self["rocket"] @property - def controlled(self): - """The objects the controller drives, or ``None`` outside one.""" - return self.get("controlled") + def environment(self): + """The environment the rocket flies in, such as + ``context.environment.wind_velocity_x(z)``. Do not change it here.""" + return self["environment"] + @property + def phase_name(self): + """Name of the current flight phase: ``"initial_phase"`` (from the + start, on the rail), ``"free_flight"`` (after leaving the rail), or + ``"_parachute_descent"`` (under that parachute).""" + return self["phase_name"] -def infer_step_size(flight, time): - """Return how long the simulation has been inside the current solver step. + @property + def sensors(self): + """The latest reading of every channel of the rocket's sensors. Find + a sensor by its name as given, or by that name in snake_case as an + attribute, then read its channels by attribute, such as ``ax``, + ``wz``, ``pressure`` or ``latitude``. The two are the same: - This is ``time`` measured from the start of the step the solver is working - on, which is the time of the second-to-last stored row. At the end of a step - that is the whole step the solver just took; at a point interpolated inside - a step it is the part of the step up to that point. + .. code-block:: python - It reaches user callbacks as ``context.step_size``. It is not the - interval between checks of any one callback, and not ``1 / sampling_rate``: - a sampled callback is checked on its own schedule, which has nothing to do - with where the solver put its step boundaries. + context.sensors["Accelerometer"].az + context.sensors.accelerometer.az - Worked out from the stored rows rather than read off the solver, because the - solver's own ``step_size`` still describes the step it last attempted, which - after a rollback is a step the flight no longer contains. - """ - solution = flight.solution - if len(solution) < 2: - return 0.0 - return max(0.0, time - solution.raw_row(-2)[0]) + ``list(context.sensors)`` gives the names. Every sensor reads once on + the pad when the flight starts, so there is always a reading. The + readings cannot be written. The sensor objects themselves, with their + settings, are in ``context.rocket.sensors``. See + :class:`rocketpy.simulation.events.views.SensorsView`. + """ + return SensorsView(self["sensors"], self._solution) def build_event_kwargs(flight, time, state, phase): @@ -285,10 +475,10 @@ def build_event_kwargs(flight, time, state, phase): ``state`` is the raw state of the current flight phase, which may not be the full canonical state. The reconstructed canonical state is stored as - ``canonical_state``, so that built-in hooks always see the familiar - 13-variable layout, and the raw state as ``raw_state``, for internal use - such as rolling the solver back. User-written hooks read ``state``, a - ``_State`` over both that is only built when it is read. + ``canonical_state``, so that RocketPy's own events always see the 13 + standard states, and the raw state as ``raw_state``, for internal use such + as rolling the solver back. Triggers and callbacks written by users read + ``state``, a ``_State`` over both that is only built when it is read. Only what nearly every event reads is worked out here; the rest is worked out by the context itself when first read. @@ -301,8 +491,8 @@ def build_event_kwargs(flight, time, state, phase): Current simulation time, in seconds. state : sequence of float The current phase's raw state at ``time``. - phase : FlightPhase - Active flight phase. + phase : _FlightPhase + The flight phase being flown. Returns ------- @@ -321,18 +511,23 @@ def build_event_kwargs(flight, time, state, phase): "canonical_state": canonical, "raw_state": state, "phase_names": current.dynamics.states, - "sensors": flight.sensors, - "sensors_by_name": flight.sensors_by_name, + "sensors": flight._sensors_by_key, "environment": flight.env, "rocket": flight.rocket, - "flight": flight, - "phase": phase, "height_agl": canonical[_Z_SLOT] - flight.env.elevation, - } + # The same dictionary for the whole flight, so it is kept when the + # context moves to another moment of the step + "controls": flight._controls, + # The controllables the control inputs are named after + "control_owners": getattr(flight, "_control_owners", None), + }, + solution=flight.solution, + phase=phase, + output_events=getattr(flight, "_output_events", None), ) -def refresh_event_kwargs(flight, event_kwargs, interpolated_time, interpolated_state): +def refresh_event_kwargs(event_kwargs, interpolated_time, interpolated_state): """Rewrite the event context to describe another moment, in place. Used for a moment inside the solver step: a sampling time the step @@ -341,8 +536,6 @@ def refresh_event_kwargs(flight, event_kwargs, interpolated_time, interpolated_s Parameters ---------- - flight : Flight - Flight instance whose environment is used to recompute derived values. event_kwargs : EventContext Context (from :func:`build_event_kwargs`) updated in place. interpolated_time : float @@ -355,7 +548,7 @@ def refresh_event_kwargs(flight, event_kwargs, interpolated_time, interpolated_s EventContext The updated ``event_kwargs``. """ - current = flight.solution.phases[-1] + current = event_kwargs._solution.phases[-1] # pylint: disable=protected-access # A phase that already integrates the full canonical state needs no # reconstruction, and this runs on every overshootable node. if current.dynamics.is_canonical: @@ -365,7 +558,9 @@ def refresh_event_kwargs(flight, event_kwargs, interpolated_time, interpolated_s event_kwargs["time"] = interpolated_time event_kwargs["canonical_state"] = canonical event_kwargs["raw_state"] = interpolated_state - event_kwargs["height_agl"] = canonical[_Z_SLOT] - flight.env.elevation + event_kwargs["height_agl"] = ( + canonical[_Z_SLOT] - event_kwargs["environment"].elevation + ) for key in _LAZY_CONTEXT_KEYS: event_kwargs.pop(key, None) return event_kwargs diff --git a/rocketpy/simulation/events/event_execution.py b/rocketpy/simulation/events/event_execution.py index 55d70396d..3ba328a27 100644 --- a/rocketpy/simulation/events/event_execution.py +++ b/rocketpy/simulation/events/event_execution.py @@ -1,8 +1,216 @@ +import pickle import warnings +from copy import deepcopy +from ...control._helpers import check_writes from ..helpers.dynamics import _BoundDynamics from .event import Event from .event_context import build_event_kwargs +from .views import output_events + + +def call_event( + flight, + event, + context, + phase, + phase_index, + node_index, +): + """Run one event inside ``flight`` and apply what it asked for. + + Before the event runs, what a rollback needs is saved. After it runs, what + it wrote to the control inputs is checked: a changed value is kept inside + its limits and marks the event's commands, since the + trajectory changes from then on (see ``Commands.changes_trajectory``). + + If the event fired, its commands are applied. When they change the + trajectory and ``context`` describes a moment before the flight's current + time (a sampling time the solver step went past), the step is first cut + back to that moment, so the commands act from there. + + Parameters + ---------- + flight : Flight + Flight instance being updated. + event : Event + The event to run. + context : EventContext + The values handed to the event, shared with the other events checked + at the same moment. + phase : _FlightPhase + Current flight phase. + phase_index : int + Index of the current flight phase. + node_index : int + Index of the current time node. + + Returns + ------- + bool + Whether the event fired. + """ + controls = flight._controls + before = dict(controls) + save_for_rollback(flight, event, context["time"], before, phase) + fired = event(context) + limits = flight._control_limits # pylint: disable=protected-access + changes = check_writes(controls, before, limits, event.name) + event.commands.control_changes.update(changes) + if changes: + # In a phase whose equations read no control input, as under a + # parachute, the write is kept but the trajectory goes on as it was + dynamics = getattr(getattr(phase, "dynamics", None), "dynamics", None) + event.commands._controls_read = getattr(dynamics, "reads_controls", True) + # The derivatives were worked out with the controls as they were + for key in ("state_dot", "canonical_state_dot", "raw_state_dot"): + context.pop(key, None) + + if not fired: + # An event turned on by its enable_on stays on, even if its trigger + # did not fire in the same check + if event.commands._disabled is False: + save_schedule(flight, phase, context["time"]) + apply_enable_commands( + flight, event.commands, node_index, event, phase, context["time"] + ) + return fired + # The rollback writes into the solution, so it uses the raw phase-layout + # state, not the reconstructed canonical one + if event.commands.changes_trajectory and context["time"] < flight.t: + apply_rollback_command( + flight, context["time"], context["raw_state"], event.commands + ) + apply_event_commands( + flight=flight, + event=event, + event_results=event.commands, + phase=phase, + phase_index=phase_index, + node_index=node_index, + command_time=context["time"], + ) + return fired + + +def save_for_rollback(flight, event, time, controls, phase): + """Save what ``event`` is before its first run at ``time`` in the solver + step (its memory, whether it is enabled and its previous check), with + ``controls``, a copy of the flight's controls then, so a rollback to an + earlier time can put them back (see :func:`rewind`).""" + # There is no log before the first solver step, when nothing can be cut + log = getattr(flight, "_step_log", None) + if log is None: + return + # Keyed by time and event, so finding an earlier run of the event at this + # time does not take a pass over every run of the step + key = (time, id(event)) + if key in log: + return + memory = _copy_of(event.memory) if event.memory else {} + log[key] = (time, event, controls, memory, event._check_state(), phase) + + +def save_schedule(flight, phase, time): + """Save what the flight's schedule is before an event run at ``time`` + changes it, so a rollback to an earlier time can put it back (see + :func:`rewind`). + + The schedule is everything an event's commands can change besides the + control inputs: the flight phases and where each ends, the time nodes of + the current phase and its solver's status, the events and which are + enabled, the surfaces switched on or off, and the parachutes noted as + deployed. + """ + # There is no log before the first solver step, when nothing can be cut + log = getattr(flight, "_schedule_log", None) + if log is None: + return + nodes = phase.time_nodes + log.append( + ( + # The time the event has in the step's log: its sampling time, or + # the flight's time once an exact time cut the step + min(time, flight.t), + phase, + [(kept, kept.time_bound) for kept in flight.flight_phases.list], + [(node, list(node.events)) for node in nodes.list], + list(nodes.continuous_events), + phase.solver.status, + [(event, event._enabled) for event in flight.events], + list(flight.custom_events), + list(flight._overshootable_events), + list(flight._non_overshootable_events), + dict(flight._output_events), + {surface: len(rows) for surface, rows in flight._surface_switches.items()}, + len(flight.parachute_events), + ) + ) + + +def restore_schedule(flight, time): + """Put the flight's schedule back to what it was at ``time``: as it was + before the first event that changed it after ``time`` in this step (see + :func:`save_schedule`). Nothing is done when no event did.""" + log = getattr(flight, "_schedule_log", None) + if not log: + return + # Saved in the order the events ran, which is also in order of time + later = [saved for saved in log if saved[0] > time] + if not later: + return + log[:] = [saved for saved in log if saved[0] <= time] + ( + _, + phase, + phases, + nodes, + continuous_events, + solver_status, + events, + custom_events, + overshootable, + non_overshootable, + outputs, + switches, + parachutes, + ) = later[0] + + # In place, so every list stays the object the flight and its loops hold + flight.flight_phases.list[:] = [kept for kept, _ in phases] + for kept, time_bound in phases: + kept.time_bound = time_bound + phase.time_nodes.list[:] = [node for node, _ in nodes] + for node, node_events in nodes: + node.events[:] = node_events + phase.time_nodes.continuous_events[:] = continuous_events + phase.solver.status = solver_status + + flight.events[:] = [event for event, _ in events] + for event, enabled in events: + event._enabled = enabled + flight.custom_events[:] = custom_events + flight._overshootable_events[:] = overshootable + flight._non_overshootable_events[:] = non_overshootable + flight._output_events.clear() + flight._output_events.update(outputs) + + for surface in list(flight._surface_switches): + kept = switches.get(surface, 0) + if kept: + del flight._surface_switches[surface][kept:] + else: + del flight._surface_switches[surface] + del flight.parachute_events[parachutes:] + + +def _copy_of(memory): + """Return a deep copy of an event's memory. Plain data is copied through + pickle, several times faster than ``deepcopy`` for a long history.""" + try: + return pickle.loads(pickle.dumps(memory, pickle.HIGHEST_PROTOCOL)) + except Exception: # pylint: disable=broad-exception-caught + return deepcopy(memory) def process_overshootable_event( @@ -14,52 +222,23 @@ def process_overshootable_event( node_index, rolled_back, ): - """Evaluate one overshootable event and apply its side effects.""" - trigger_result = event(event_kwargs, trigger_only=True) - - if not trigger_result: - event._trigger_checked = False - return rolled_back, False - - event._trigger_checked = True - - if not event.changes_dynamics: - event(event_kwargs, callback_only=True, reset=False) - # If the callback queued commands that change the post-trigger - # trajectory (a new flight phase, a new derivative, or termination), - # the overshoot step-end state is no longer valid. Roll the flight - # state back to the interpolated trigger crossing first, so every - # queued command is applied on a consistent state and effects start - # exactly at the crossing rather than at the overshoot step-end. - # This lets any event (e.g. parachutes, or user-defined events that - # add a phase / terminate) work without declaring changes_dynamics. - # The rollback writes into the solution, so it must use the raw - # phase-layout state, not the reconstructed canonical one. - changed = event.commands.changes_trajectory - if changed: - apply_rollback_command( - flight, event_kwargs["time"], event_kwargs["raw_state"] - ) - apply_event_commands( - flight=flight, - event=event, - event_results=event.commands, - phase=phase, - phase_index=phase_index, - node_index=node_index, - command_time=event_kwargs["time"], - ) - event._trigger_checked = False - # A rollback means the rest of the step no longer happened: later - # sampling times in it are not checked, and the solver is restarted - # from the crossing if the phase goes on (a new phase after a lag). - return rolled_back or changed, False + """Run one event at a sampling time inside the solver step just taken. - if not rolled_back: - apply_rollback_command(flight, event_kwargs["time"], event_kwargs["raw_state"]) - return True, True + The callback runs at the sampling time. If its commands change the + trajectory (a new flight phase, new equations of motion, termination, a + surface switch, a change to the rocket or a control write), the rest of the + step is no longer valid: :func:`call_event` cuts it back to this time + before applying them, so their effects start exactly here. - return rolled_back, False + Returns + ------- + bool + Whether the step was cut, by this event or by an earlier one + (``rolled_back``). After a cut, later sampling times in the step are not + checked, and the solver is restarted from here if the phase goes on. + """ + fired = call_event(flight, event, event_kwargs, phase, phase_index, node_index) + return rolled_back or (fired and event.commands.changes_trajectory) def call_events( @@ -71,26 +250,30 @@ def call_events( time, state, ): + """Run ``events`` in order at ``time``, applying what each asks for. + + An event that happened at an exact time before ``time`` and changed the + trajectory takes the flight back to that time. The events after it then + run there, at the flight's new time and state, since the stretch up to + ``time`` was never flown. + + Returns + ------- + bool + Whether a fired event changed the trajectory. + """ event_kwargs = build_event_kwargs( flight=flight, time=time, state=state, phase=phase ) trajectory_changed = False for event in events: - trigger_result = event._trigger_checked - trigger_result = event(event_kwargs, callback_only=trigger_result) - if trigger_result: + if call_event(flight, event, event_kwargs, phase, phase_index, node_index): trajectory_changed |= event.commands.changes_trajectory - apply_event_commands( - flight=flight, - event=event, - event_results=event.commands, - phase=phase, - phase_index=phase_index, - node_index=node_index, - command_time=event_kwargs["time"], + if flight.t < event_kwargs["time"]: + event_kwargs = build_event_kwargs( + flight=flight, time=flight.t, state=flight.y_sol, phase=phase ) - event._trigger_checked = False return trajectory_changed @@ -111,8 +294,8 @@ def apply_event_commands( Flight instance being updated. event : Event Event that produced the results. - event_results : dict - Result payload returned by the event system. + event_results : Commands + The commands the event queued. phase : _FlightPhase Current flight phase. phase_index : int @@ -128,6 +311,21 @@ def apply_event_commands( t_apply = event_results.exact_time apply_exact_time_result(flight, event_results) + # Saved only before commands that change the schedule: the phases, the + # events and which are enabled, the surface switches or the flight's end. + # Written out, since this runs after every call of every event + if ( # pylint: disable=too-many-boolean-expressions + event_results.new_flight_phase is not None + or event_results.new_dynamics is not None + or event_results._terminate + or event_results.surface_switches + or event_results.new_events + or event_results.enable_events + or event_results.disable_events + or event_results._disabled is not None + ): + save_schedule(flight, phase, command_time) + # Before a new phase is started, so its solver begins with these surfaces apply_surface_switches(flight, event_results, time=t_apply) @@ -143,9 +341,6 @@ def apply_event_commands( apply_disable_commands( flight, event_results, node_index, event, phase, time=t_apply ) - if event.changes_dynamics: - # The callback may have changed a surface - flight.rocket._refresh_aerodynamics() def apply_surface_switches(flight, event_results, time): @@ -176,7 +371,7 @@ def apply_surface_switches(flight, event_results, time): flight._surface_switches.setdefault(surface, []).append((time, active)) -def apply_rollback_command(flight, time, state): +def apply_rollback_command(flight, time, state, event_results=None): """Apply a rollback request returned by an event trigger. Parameters @@ -187,17 +382,131 @@ def apply_rollback_command(flight, time, state): Interpolated simulation time to restore. state : array_like Interpolated flight state vector to restore. + event_results : Commands, optional + The commands of the event that asked for the rollback. The controls + its callback wrote and its memory are kept. Returns ------- None This function updates flight state/history in place. """ + rewind(flight, time, event_results) flight.t = time flight.y_sol = state flight.solution._replace_last([time, *state]) +def rewind(flight, time, event_results=None): + """Undo what the events did after ``time`` in the step being cut. + + Nothing is done when ``time`` is not before the flight's current time, + since nothing is cut then. Otherwise the control inputs go back to what + they were before the first event run after ``time`` in this step, and + every event run after ``time`` gets back its memory, whether it was + enabled and its previous check (all saved by :func:`save_for_rollback`). + The records, the outputs and the sensor readings made after ``time`` are + dropped, with the times events ran or were turned on or off after it. The + flight's schedule goes back too (see :func:`save_schedule`): a phase + started, an event added, enabled or disabled, a surface switched, a + parachute deployed or the flight ended after ``time`` is undone. The + event that cuts the step happened at ``time``, so its control writes, its + memory and its own state stand, and its commands are applied afterwards. + + Parameters + ---------- + flight : Flight + Flight instance being updated. + time : float + The time the flight goes back to, in seconds. + event_results : Commands, optional + The commands of the event that cuts the step. + """ + log = getattr(flight, "_step_log", None) + if log is None or not time < flight.t: + return + # Before the events are given back their own state, which is the state + # before their first run after ``time`` and may be older than the save + restore_schedule(flight, time) + # In the order the events ran, as the log was filled + later = [entry for entry in log.values() if entry[0] > time] + for entry in later: + del log[(entry[0], id(entry[1]))] + controls = flight._controls + if later: + controls.update(later[0][2]) + restored = set() + for _, event, _, memory, check_state, phase in later: + if id(event) in restored or event.commands is event_results: + continue + restored.add(id(event)) + # In place, so the dictionary a callback reads stays the same object + event.memory.clear() + event.memory.update(memory) + was_enabled = event._enabled + event._restore_check_state(check_state) # pylint: disable=protected-access + if event._enabled and not was_enabled and event.sampling_rate is None: + # Turned off after ``time``: checked at every step again + continuous = phase.time_nodes.continuous_events + if event not in continuous: + continuous.append(event) + if event_results is not None: + controls.update(event_results.control_changes) + for event in flight.events: + event._drop_after(time) # pylint: disable=protected-access + rewind_sensors(flight, time) + + +def rewind_sensors(flight, time): + """Take the sensors back to ``time``: the solution and their + ``measured_data`` lose the readings made after it, their ``measurement`` + is again the last one kept, so a controller reading a sensor never sees a + reading from the stretch of trajectory the flight went back over, and the + random walk of their noise loses the steps of those readings. + + Parameters + ---------- + flight : Flight + Flight instance being updated. + time : float + The time the flight goes back to, in seconds. + """ + positions_by_key = getattr(flight, "_sensors_by_key", None) + if positions_by_key is None: + return + solution = flight.solution + solution._drop_readings_after(time) # pylint: disable=protected-access + positions = {} + latest = {} + for sensor, event in positions_by_key.values(): + # A sensor added more than once keeps one list per position + index = positions.get(id(sensor), 0) + positions[id(sensor)] = index + 1 + data = sensor.measured_data + rows = data[index] if data and isinstance(data[0], list) else data + while rows and rows[-1][0] > time: + rows.pop() + sensor._drop_drift_after(time) # pylint: disable=protected-access + readings = [ + solution._latest_reading(event._position_name, label) # pylint: disable=protected-access + for label, _ in sensor.channels + ] + if not all(reading is not None for reading in readings): + latest.setdefault(id(sensor), (None, sensor, None)) + continue + read_at = readings[0][0] + kept = latest.get(id(sensor)) + # Of a sensor added more than once, the position read last + if kept is None or kept[0] is None or read_at >= kept[0]: + values = tuple(value for _, value in readings) + latest[id(sensor)] = (read_at, sensor, values) + for _, sensor, values in latest.values(): + if values is None: + sensor.measurement = None + else: + sensor.measurement = values if len(values) > 1 else values[0] + + def apply_disable_commands(_, event_results, node_index, event, phase, time): """Apply disable commands returned by an event solver. @@ -205,8 +514,8 @@ def apply_disable_commands(_, event_results, node_index, event, phase, time): ---------- _ : Flight Flight instance (unused; accepted for a uniform command signature). - event_results : dict - Result payload returned by the event system. + event_results : Commands + The commands the event queued. node_index : int Index of the current time node. event : Event @@ -218,12 +527,8 @@ def apply_disable_commands(_, event_results, node_index, event, phase, time): """ if event_results.disable_events: - disable_events = event_results.disable_events - if not isinstance(disable_events, (list, tuple)): - disable_events = [disable_events] - - for event_to_disable in disable_events: - event_to_disable.enabled = False + for event_to_disable in event_results.disable_events: + event_to_disable._enabled = False event_to_disable.disabled_times.append(time) _safe_disable_time_nodes_event( phase=phase, @@ -233,7 +538,7 @@ def apply_disable_commands(_, event_results, node_index, event, phase, time): ) if event_results._disabled: - event.enabled = False + event._enabled = False event.disabled_times.append(time) _safe_disable_time_nodes_event( phase=phase, @@ -250,8 +555,8 @@ def apply_enable_commands(flight, event_results, node_index, event, phase, time) ---------- flight : Flight Flight instance being updated. - event_results : dict - Result payload returned by the event system. + event_results : Commands + The commands the event queued. node_index : int Index of the current time node. event : Event @@ -263,12 +568,8 @@ def apply_enable_commands(flight, event_results, node_index, event, phase, time) """ if event_results.enable_events: - enable_events = event_results.enable_events - if not isinstance(enable_events, (list, tuple)): - enable_events = [enable_events] - - for event_to_enable in enable_events: - event_to_enable.enabled = True + for event_to_enable in event_results.enable_events: + event_to_enable._enabled = True event_to_enable.enabled_times.append(time) if event_to_enable in flight._non_overshootable_events: _safe_enable_time_nodes_event( @@ -280,7 +581,7 @@ def apply_enable_commands(flight, event_results, node_index, event, phase, time) # Commands API uses `_disabled` flag: True -> disable, False -> enable if event_results._disabled is False: - event.enabled = True + event._enabled = True event.enabled_times.append(time) # if the event is non-overshootable, we need to create discrete nodes @@ -314,6 +615,7 @@ def apply_exact_time_result(flight, event_results): solution = flight.solution previous_time = solution.raw_row(-2)[0] if len(solution) > 1 else None if event_results.changes_trajectory: + rewind(flight, time, event_results) if time == previous_time: # The event happened right where the step began, which is stored. solution._drop_last() @@ -323,9 +625,7 @@ def apply_exact_time_result(flight, event_results): flight.y_sol = state elif previous_time is not None and previous_time < time < solution.raw_row(-1)[0]: solution._insert_before_last([time, *state]) - # Recorded now, with the rocket as it was when the step was flown: an - # event later in this step may change it before the step is recorded. - flight._post_process_row(-2) # pylint: disable=protected-access + solution._set_controls(-2, dict(flight._controls)) def bind_new_dynamics(flight, event_results): @@ -369,8 +669,8 @@ def apply_new_phase_or_dynamics( ---------- flight : Flight Flight instance being updated. - event_results : dict - Result payload returned by the event system. + event_results : Commands + The commands the event queued. phase : _FlightPhase Current flight phase. phase_index : int @@ -394,6 +694,11 @@ def apply_new_phase_or_dynamics( # No new dynamics means the new phase keeps flying the current equations. dynamics = bind_new_dynamics(flight, event_results) or phase.dynamics + # A parachute coming out: the flight notes it, with the time it happened + parachute = event_results.new_dynamics_kwargs.get("parachute") + if parachute is not None: + flight.parachute_events.append([when_time, parachute]) + # Inserting the phase also moves the current phase's end to its start. flight.flight_phases.add_phase( when_time + lag, @@ -403,7 +708,9 @@ def apply_new_phase_or_dynamics( ) # Rollback solution to the trigger time - apply_rollback_command(flight, when_time, flight.solution.raw_row(-1)[1:]) + apply_rollback_command( + flight, when_time, flight.solution.raw_row(-1)[1:], event_results + ) if lag == 0: # Prepare to leave loops and start new flight phase @@ -424,8 +731,8 @@ def apply_termination(flight, event_results, phase, phase_index, node_index, tim ---------- flight : Flight Flight instance being updated. - event_results : dict - Result payload returned by the event system. + event_results : Commands + The commands the event queued. phase : _FlightPhase Current flight phase. phase_index : int @@ -466,8 +773,8 @@ def apply_event_list_updates(flight, event_results, phase, time): ---------- flight : Flight Flight instance being updated. - event_results : dict - Result payload returned by the event system. + event_results : Commands + The commands the event queued. phase : _FlightPhase Current flight phase. time : float @@ -481,18 +788,9 @@ def apply_event_list_updates(flight, event_results, phase, time): new_events = [new_events] for new_event in new_events: - if new_event.changes_dynamics and not flight.solution.records_post_values: - warnings.warn( - f"Event '{new_event.name}' has changes_dynamics=True but was " - f"added with add_event after the flight started. The " - f"trajectory is correct, but the accelerations, aerodynamic " - f"forces and moments and net thrust (flight.ax, flight.R1, " - f"flight.net_thrust, ...) will be wrong. Fix: build the " - f"Flight with an event that has changes_dynamics=True in " - f"custom_events (a disabled placeholder event is enough).", - UserWarning, - ) flight.events.append(new_event) + # Its outputs are read and written like those of any other event + flight._output_events.update(output_events([new_event])) flight.custom_events.append(new_event) is_new_event_overshootable = ( flight.time_overshoot diff --git a/rocketpy/simulation/events/views.py b/rocketpy/simulation/events/views.py new file mode 100644 index 000000000..42fb124ef --- /dev/null +++ b/rocketpy/simulation/events/views.py @@ -0,0 +1,468 @@ +"""The views an event or controller function reads the flight through: +``context.controls`` (the control inputs, written by controllers), +``context.outputs`` (the values events share with each other) and +``context.sensors`` (the latest sensor readings, read-only). A controllable, +an event or a sensor is found by its name as given, +``context.controls["Air Brakes"]``, or by that name in snake_case as an +attribute, ``context.controls.air_brakes``, and its values are then read by +attribute, such as ``context.controls["Air Brakes"].deployment_level`` or +``context.sensors.accelerometer.az``. After the flight the same values are +``flight.controls``, ``flight.event_outputs``, ``flight.sensor_history`` and +``flight.records``. +""" + +from rocketpy.tools import snake_case_key, unique_names + + +class ChannelsView: + """Groups of named values, found by name or by attribute. + + There is one group per controllable, event or sensor, and each value in a + group is a channel: ``view["Canards"].fin_1`` or ``view.canards.fin_1``. + This is the base of ``context.controls``, ``context.outputs`` and + ``context.sensors``. + + A subclass gives: + + - the groups and their channels by key, the name in snake_case + (:meth:`_groups`); + - the names as given (:meth:`_names`); + - how a channel is read (:meth:`_read`) and, if it can be, written + (:meth:`_write`); + - the words of the error messages, which list what exists so a misspelled + name is easy to fix. + """ + + __slots__ = () + + # Error messages, filled with the names involved + _unknown_name = "There is nothing named {name!r}. The names are: {names}." + _unknown_key = "There is nothing named '{key}'. The names are: {keys}." + _unknown_channel = ( + "'{key}' has no channel '{channel}'. Its channels are: {channels}." + ) + _key_written = "Write a channel, such as `{key}. = ...`." + _read_only = "These values are read-only." + + def _groups(self): + """Return each key with the tuple of its channels, in order.""" + raise NotImplementedError + + def _names(self): + """Return each name as given with its key, in order.""" + raise NotImplementedError + + def _read(self, key, channel): + """Return the value of one existing channel.""" + raise NotImplementedError + + def _write(self, key, channel, value): + """Write one existing channel.""" + raise AttributeError(self._read_only) + + def _check(self, key, channel): + """Raise an ``AttributeError`` with a list of what exists if + ``channel`` is not a channel of ``key``.""" + channels = self._groups()[key] + if channel not in channels: + raise AttributeError( + self._unknown_channel.format( + key=key, channel=channel, channels=", ".join(channels) + ) + ) + + def _key_of(self, name): + """Return the key of the group ``view[name]`` gives.""" + names = self._names() + if isinstance(name, str) and name in names: + return names[name] + raise KeyError( + self._unknown_name.format( + name=name, names=", ".join(map(repr, names)) or "none" + ) + ) + + def __getitem__(self, name): + return _KeyView(self, self._key_of(name)) + + def __setitem__(self, name, value): + raise TypeError(self._key_written.format(key=self._key_of(name))) + + def __iter__(self): + return iter(self._names()) + + def __len__(self): + return len(self._names()) + + def __contains__(self, name): + return isinstance(name, str) and name in self._names() + + def __getattr__(self, key): + if key.startswith("_"): + raise AttributeError(key) + groups = self._groups() + if key not in groups: + raise AttributeError( + self._unknown_key.format(key=key, keys=", ".join(groups) or "none") + ) + return _KeyView(self, key) + + def __setattr__(self, key, value): + raise AttributeError(self._key_written.format(key=key)) + + def __dir__(self): + return list(self._groups()) + + def __repr__(self): + groups = {name: repr(self[name]) for name in self} + return f"{type(self).__name__}({groups})" + + +class _KeyView: + """The channels of one controllable, event or sensor of a + :class:`ChannelsView`, read and written by attribute, + ``context.controls.canards.fin_1``, or by name, + ``context.controls.canards["fin_1"]``.""" + + __slots__ = ("_view", "_key") + + def __init__(self, view, key): + object.__setattr__(self, "_view", view) + object.__setattr__(self, "_key", key) + + def _get(self, channel): + self._view._check(self._key, channel) + return self._view._read(self._key, channel) + + def __getattr__(self, channel): + if channel.startswith("_"): + raise AttributeError(channel) + return self._get(channel) + + def __setattr__(self, channel, value): + self._view._check(self._key, channel) + self._view._write(self._key, channel, value) + + # The same by name, for a name built in a loop: ``controls.canards[fin]`` + def __getitem__(self, channel): + # Not through the attribute, so a channel named as a method of this + # class, ``update``, is still read here + try: + return self._get(channel) + except AttributeError as error: + raise KeyError(str(error)) from None + + def __setitem__(self, channel, value): + try: + setattr(self, channel, value) + except AttributeError as error: + raise KeyError(str(error)) from None + + def update(self, values): + """Write several channels at once from a dictionary of name to value, + such as the one :meth:`rocketpy.ControlFins.deflections` returns: + ``context.controls.canards.update(canards.deflections(roll=0.05))``.""" + for channel, value in values.items(): + self[channel] = value + + def __iter__(self): + return iter(self._view._groups()[self._key]) + + def __dir__(self): + return list(self._view._groups()[self._key]) + + def __repr__(self): + values = {channel: self[channel] for channel in self} + return f"{self._key}{values}" + + +class ControlsView(ChannelsView): + """The flight's control inputs as a controller sees them: ``context.controls`` + in a sampled controller or event, and ``controls`` in a continuous law. + + A controllable is found by its name in snake_case as an attribute, by its + name as given, or by the controllable itself, as returned by + ``rocket.add_air_brakes`` or given to ``rocket.add_surfaces``. Its + controls are then read and written by attribute, or by name when the name + is built in a loop. These are all the same: + + .. code-block:: python + + controls.canards.fin_1 = 0.05 + controls["Canards"].fin_1 = 0.05 + controls[canards].fin_1 = 0.05 + controls.canards["fin_1"] = 0.05 + + Looping over it gives the names of the controllables, and ``"Canards" in + controls`` tells whether there is one. Writing a control that does not + exist raises an error that lists the ones that do. + + Parameters + ---------- + controls : dict + The control inputs, ``"."`` to value. Written in place. + A name without a dot is not a control input and is not shown: the + dictionary a continuous law reads also holds the states of the + controllables, by their names. + controllables : sequence, optional + The rocket's controllables, which give the names. A key with no + controllable among them is found by the key itself. Default: none. + """ + + __slots__ = ("_controls", "_controllables", "_cache") + + _unknown_name = ( + "No controllable of the rocket is named {name!r}. The controllables " + "with controls are: {names}." + ) + _unknown_key = ( + "No controllable of the rocket has controls named '{key}'. The " + "controllables with controls are: {keys}." + ) + _unknown_channel = ( + "'{key}' has no control named '{channel}'. Its controls are: {channels}." + ) + _key_written = ( + "Write a control of a controllable, such as " + "`controls.{key}. = ...`, not the controllable itself." + ) + + def __init__(self, controls, controllables=()): + # The flight's own dictionary: a write here is a write to the flight + object.__setattr__(self, "_controls", controls) + object.__setattr__(self, "_controllables", controllables) + object.__setattr__(self, "_cache", None) + + def _point_at(self, controls): + """Read and write ``controls`` from now on: another dictionary of the + same control inputs. The equations of motion keep one view for their + continuous laws and point it at the values of each evaluation, which + is much faster than building a view every time.""" + object.__setattr__(self, "_controls", controls) + + def _groups(self): + # The control inputs of a flight never change, so this is built once + if self._cache is None: + groups = {} + for name in self._controls: + key, dot, channel = name.partition(".") + if dot: + groups.setdefault(key, []).append(channel) + object.__setattr__(self, "_cache", groups) + return self._cache + + def _names(self): + by_key = {snake_case_key(c.name): c.name for c in self._controllables} + return {by_key.get(key, key): key for key in self._groups()} + + def _key_of(self, name): + if isinstance(name, str) or not hasattr(name, "controls"): + return super()._key_of(name) + # A controllable, recognised by shape so this module does not import + # rocketpy.control + key = snake_case_key(name.name) + if key in self._groups(): + return key + return super()._key_of(name.name) + + def _read(self, key, channel): + return self._controls[f"{key}.{channel}"] + + def _write(self, key, channel, value): + self._controls[f"{key}.{channel}"] = value + + +class OutputsView(ChannelsView): + """The values the events of a flight share with each other, as an event + reads and writes them: ``context.outputs``. + + An event that declared outputs is found by its name in snake_case as an + attribute, by its name as given, or by the event itself. Its outputs are + then read and written by attribute, or by name. These are all the same: + + .. code-block:: python + + outputs.guidance.pitch_setpoint + outputs["Guidance"].pitch_setpoint + outputs[guidance].pitch_setpoint + outputs.guidance["pitch_setpoint"] + + Every event can read every output. Only the event that declared an output + can write it. Looping over the view gives the names of the events with + outputs. + + Parameters + ---------- + events : dict + The events with outputs, by their name in snake_case (see + :func:`output_events`). + writer : Event, optional + The event being run, the only one whose outputs can be written. + Default ``None``, a view that only reads. + time : float, optional + The time a write is stored with, in seconds. + """ + + __slots__ = ("_events", "_writer", "_time") + + _unknown_name = ( + "No event with outputs is named {name!r}. The events with outputs are: {names}." + ) + _unknown_key = ( + "No event has outputs under the name '{key}'. The events with outputs " + "are: {keys}." + ) + _unknown_channel = ( + "'{key}' has no output named '{channel}'. Its outputs are: {channels}." + ) + _key_written = ( + "Write an output of the event, such as `outputs.{key}. = ...`, " + "not the event itself." + ) + + def __init__(self, events, writer=None, time=None): + object.__setattr__(self, "_events", events) + object.__setattr__(self, "_writer", writer) + object.__setattr__(self, "_time", time) + + def _groups(self): + return {key: event.outputs for key, event in self._events.items()} + + def _names(self): + return {event.name: key for key, event in self._events.items()} + + def _key_of(self, name): + if not isinstance(name, str) and hasattr(name, "outputs"): + # The event itself + key = snake_case_key(name.name) + if self._events.get(key) is name: + return key + name = name.name + return super()._key_of(name) + + def _read(self, key, channel): + return self._events[key]._outputs[channel] + + def _write(self, key, channel, value): + event = self._events[key] + if event is not self._writer: + raise AttributeError( + f"The output '{key}.{channel}' is written only by '{event.name}', " + "the event that declared it. Other events read it." + ) + event._write_output(self._time, channel, value) + + +def output_events(events): + """Return the events of ``events`` that declared outputs, by their name in + snake_case, which is how ``context.outputs`` finds them. + + Raises + ------ + ValueError + If two events with outputs have names that give the same key, since + their outputs could not be told apart. + """ + found = {} + for event in events: + if not event.outputs: + continue + key = snake_case_key(event.name) + if key in found: + raise ValueError( + f"The events '{found[key].name}' and '{event.name}' both have " + f"outputs, and their outputs would both be named " + f"'{key}.'. Give them different names." + ) + found[key] = event + return found + + +def sensor_positions(sensor_events): + """Return each sensor position of a rocket by its key, as ``{key: (sensor, + event)}``, and give each event the name its readings go by + (``event._position_name``). + + The name is the sensor's own, and the key is that name in snake_case: + ``"Nose IMU"`` and ``nose_imu``. A name used again, by another sensor or + by the same sensor added in another position, is numbered from 2 in the + order they were added: ``"Nose IMU 2"`` and ``nose_imu_2`` (see + :func:`rocketpy.tools.unique_names`). Adding a sensor never renames the + ones already there, so a controller reading them keeps working. + + Parameters + ---------- + sensor_events : sequence + The rocket's ``(sensor, event)`` pairs, in the order they were added. + + Returns + ------- + dict + """ + names = unique_names([sensor.name for sensor, _ in sensor_events]) + positions = {} + for name, (sensor, event) in zip(names, sensor_events): + event._position_name = name + positions[snake_case_key(name)] = (sensor, event) + return positions + + +class SensorsView(ChannelsView): + """The latest reading of every channel of the rocket's sensors, as an + event reads them: ``context.sensors``. + + A sensor is found by its name as given, or by that name in snake_case as + an attribute. Its channels are then read by name, such as ``ax``, ``wz``, + ``pressure`` or ``latitude``. These are the same: + + .. code-block:: python + + sensors["Accelerometer"].az + sensors.accelerometer.az + + A name used again, by another sensor or by the same sensor in another + position, is numbered from 2 in the order they were added: + ``"Accelerometer"`` and ``"Accelerometer 2"``, read as ``accelerometer`` + and ``accelerometer_2``, each with its own readings. Looping over the view + gives the names. Every sensor reads once on the pad when the flight + starts, so there is always a reading. The readings cannot be written. + + Parameters + ---------- + sensors : dict + Key to ``(sensor, event)`` for each sensor position (see + :func:`sensor_positions`). + solution : Solution + The flight's solution, which holds the readings. + """ + + __slots__ = ("_sensors", "_solution") + + _unknown_name = "The rocket has no sensor named {name!r}. Its sensors are: {names}." + _unknown_key = "The rocket has no sensor named '{key}'. Its sensors are: {keys}." + _unknown_channel = ( + "The sensor '{key}' has no channel named '{channel}'. Its channels are: " + "{channels}." + ) + _key_written = "Sensor readings are read-only." + _read_only = "Sensor readings are read-only." + + def __init__(self, sensors, solution): + object.__setattr__(self, "_sensors", sensors) + object.__setattr__(self, "_solution", solution) + + def _groups(self): + return { + key: tuple(label for label, _ in sensor.channels) + for key, (sensor, _) in self._sensors.items() + } + + def _names(self): + return {event._position_name: key for key, (_, event) in self._sensors.items()} + + def _read(self, key, channel): + # The last value the solution holds, or None before the first reading + latest = self._solution._latest_reading( + self._sensors[key][1]._position_name, channel + ) + return None if latest is None else latest[1] diff --git a/rocketpy/simulation/flight.py b/rocketpy/simulation/flight.py index d6e733f9e..52279059d 100644 --- a/rocketpy/simulation/flight.py +++ b/rocketpy/simulation/flight.py @@ -6,9 +6,13 @@ import numpy as np from scipy.integrate import BDF, DOP853, LSODA, RK23, RK45, OdeSolver, Radau -from rocketpy.simulation.flight_data_exporter import FlightDataExporter +from rocketpy.simulation.flight_data_exporter import ( + FlightDataExporter, + _sensor_rows, +) from .._logging import enable_logging, logger +from ..control._helpers import initial_controls, limited_value from ..mathutils.function import Function, funcify_method from ..mathutils.vector_matrix import Matrix from ..motors.solid_motor import SolidMotor @@ -18,10 +22,13 @@ deprecated, euler313_to_quaternions, find_closest, + history_function, inverted_haversine_array, quaternions_to_nutation, quaternions_to_precession, quaternions_to_spin, + snake_case_key, + unique_names, ) from .events.event_builders import ( build_core_events, @@ -29,7 +36,11 @@ out_of_rail_trigger, ) from .events.event_context import build_event_kwargs, refresh_event_kwargs -from .events.event_execution import call_events, process_overshootable_event +from .events.event_execution import ( + call_events, + process_overshootable_event, +) +from .events.views import output_events, sensor_positions from .helpers.dynamics import ( PARACHUTE_DYNAMICS, RAIL_DYNAMICS, @@ -38,7 +49,7 @@ THREE_DOF_DYNAMICS, ) from .helpers.flight_phase import _FlightPhases, _TimeNodes -from .solution import Solution +from .solution import Solution, _ResultsDict ODE_SOLVER_MAP = { "RK23": RK23, @@ -80,8 +91,9 @@ class Flight: # pylint: disable=too-many-instance-attributes, too-many-public-m the beginning of the rail. Flight.name: str Name of the flight. - Flight._controllers : list - List of controllers to be used during simulation. + Flight.controllers : list + The controllers that flew with the rocket, from + ``rocket.add_controller`` and ``rocket.add_air_brakes``. Flight.max_time : int, float Maximum simulation time allowed. Refers to physical time being simulated, not time taken to run simulation. @@ -223,6 +235,21 @@ class Flight: # pylint: disable=too-many-instance-attributes, too-many-public-m Flight.time_steps : array List of time steps taking during numerical integration in seconds. + Flight.controls : dict + The control inputs over the flight, by controllable, each a Function + of time, such as ``flight.controls.air_brakes.deployment_level``. + Flight.state_history : dict + The states of the rocket's controllables over the flight, by + controllable, each a Function of time. + Flight.sensor_history : dict + What the sensors read during the flight, by sensor, each channel a + Function of time. + Flight.records : dict + What the events and controllers recorded with ``context.record``, by + event, each record a list of ``(time, value)`` pairs. + Flight.event_outputs : dict + What the events and controllers wrote to their outputs, by event, each + output a list of ``(time, value)`` pairs. Flight.wind_velocity_x : Function Wind velocity X (East) experienced by the rocket as a function of time. @@ -577,10 +604,14 @@ def __init__( # pylint: disable=too-many-arguments,too-many-statements w1_init, w2_init, w3_init ] - If a Flight object is used, the last state vector will be - used as initial solution. If None, the initial solution will start - with all null values, except for the euler parameters which will be - calculated based on given values of inclination and heading. + If a Flight object is used, the flight goes on from where that one + ended: its last state is the initial solution, and the control + inputs and the controllables' states (an air brake's deployment + level, a fin's angle...) keep the values they had at its end. + Controllers, events and sensors start fresh. If None, the initial + solution will start with all null values, except for the euler + parameters which will be calculated based on given values of + inclination and heading. Default is None. terminate_on_apogee : boolean, optional Whether to terminate simulation when rocket reaches apogee. @@ -718,13 +749,13 @@ def __init_events(self): """Initialize events and event triggers. The order of the list is the order that the events will be called. Core events should be first, then sensors, then parachutes, then controllers, then user defined events.""" - self.__init_eventful_objects() + self.__init_eventful_objects(self.custom_events) - self.events = [*build_core_events()] + self.events = [*build_core_events(self)] # Sensor events (position-specific, created when sensors added to rocket) - if hasattr(self.rocket, "_sensor_events"): - self.events.extend(self.rocket._sensor_events) + for _, event in getattr(self.rocket, "_sensor_events", ()): + self.events.append(event) # Parachute events for parachute in self.parachutes: @@ -732,15 +763,13 @@ def __init_events(self): self.events.append(parachute.event) # Controller events - for controller in self._controllers: - self.events.append(controller.event) + self.events.extend(self.controllers) # User-defined events are appended last self.events.extend(self.custom_events) self._overshootable_events = [] self._non_overshootable_events = [] - self._has_change_dynamics_events = False for event in self.events: # Separate time overshootable and non overshootable events if ( @@ -752,28 +781,41 @@ def __init_events(self): else: self._non_overshootable_events.append(event) - self._has_change_dynamics_events |= event.changes_dynamics - event.reset() # Reset event state (commands/logs/enabled flag) # Sort by canonical order (lower priority runs first) self._overshootable_events.sort(key=lambda x: x.priority) self._non_overshootable_events.sort(key=lambda x: x.priority) - def __init_eventful_objects(self): - """Initialize controllers and sensors""" - self._controllers = self.rocket._controllers[:] + def __init_eventful_objects(self, user_events): + """Initialize the control inputs, controllers and sensors. + ``user_events`` are the events given to the flight.""" + # Everything with control inputs in this flight + self._control_owners = self.rocket.controllables + # The events that share values with the others, by their name in + # snake_case: what context.outputs reads and writes + self._output_events = output_events((*self.rocket.controllers, *user_events)) + # The control inputs of this flight: name to value, every one + # at its default. A new dictionary for every flight, so no + # flight inherits another's controls and the rocket itself is never + # changed by flying. + ( + self._controls, + self._control_names, + self._control_limits, + ) = initial_controls(self._control_owners) + self.controllers = list(self.rocket.controllers) self.sensors = self.rocket.sensors.get_components() self.sensors_by_name = self.rocket.sensors_by_name - - # reset controllable object to initial state (only airbrakes for now) - for air_brakes in self.rocket.air_brakes: - air_brakes._reset() - - self.sensor_data = {} for sensor in self.sensors: sensor._reset(self.rocket) # resets noise and measurement list - self.sensor_data[sensor] = [] + # Each sensor position by its key (the sensor's name in snake_case, + # numbered from 2 at the positions after the first of a sensor added + # in several positions), with its event: what context.sensors reads, + # and how the results find the positions + self._sensors_by_key = sensor_positions( + getattr(self.rocket, "_sensor_events", ()) + ) def __init_solution_monitors(self): # Initialize solution monitors @@ -795,8 +837,8 @@ def __init_solution_monitors(self): def __init_equations_of_motion(self): """Initialize equations of motion.""" # Bind each phase's dynamics (states + equations of motion) to this - # flight. Each bound object is callable as (t, u), so it is a drop-in - # for the old derivative functions. + # flight. Each bound object is callable as (t, u), with the flight's + # control inputs as they are, which is what the ODE solver needs. self.u_dot = SOLID_PROPULSION_DYNAMICS.bind(self) self.u_dot_generalized = SIX_DOF_DYNAMICS.bind(self) self.u_dot_generalized_3dof = THREE_DOF_DYNAMICS.bind(self) @@ -804,6 +846,11 @@ def __init_equations_of_motion(self): self.udot_rail1 = RAIL_DYNAMICS.bind(self) self.udot_rail2 = self.u_dot_generalized + # The thrust acts through the nozzle exit, worked out again here in + # case the thrust eccentricity was set on the rocket directly + self.rocket.evaluate_nozzle_exit() + self.rocket.evaluate_nozzle_gyration_tensor() + # The switches events make during the flight: surface -> [(time, active)] self._surface_switches = {} @@ -863,26 +910,38 @@ def __init_solver_monitors(self): self.function_evaluations = [] # Initialize solution state self.solution = Solution() - # A flight that changes the rocket as it flies has to record its - # post-process variables while it runs. Telling the solution so makes - # the recorded values the only answer it will give for them. - self.solution.records_post_values = self._has_change_dynamics_events self.__init_flight_state() self.t_initial = self.initial_solution[0] + self.initial_dynamics = self.initial_dynamics.started_from( + tuple(self.initial_solution[1:]) + ) self.solution._start_phase( self.initial_dynamics, start_canonical=tuple(self.initial_solution[1:]), t_start=self.t_initial, name="initial_phase", # the same name _FlightPhases gives it ) - self.solution._append(list(self.initial_solution)) + # The first row: the phase's states seeded from the given initial + # solution, then the controllables' states, from the flight this one + # continues when it has them, else from their starting values + self.solution._append( + [ + self.t_initial, + *self.initial_dynamics.initial_state( + self.t_initial, self.initial_solution[1:], self._previous_states + ), + ] + ) self.t, *self.y_sol = self.solution.raw_row(-1) self.__set_ode_solver(self.ode_solver) def __init_flight_state(self): """Initialize flight state variables.""" + # The states of the flight this one continues, by name, for the + # controllables' states; empty when the flight starts on its own + self._previous_states = {} if self.initial_solution is None: # Initialize time and state variables self.t_initial = 0 @@ -938,6 +997,19 @@ def __init_flight_state(self): previous_flight = self.initial_solution self.t_initial = previous_flight.solution.raw_row(-1)[0] self.initial_solution = previous_flight.solution.canonical_row(-1) + # The controllables go on from where that flight left them: its + # last control inputs, for the ones this flight also has and + # inside this flight's limits, and its last states, which the + # first phase takes by name + previous_controls = previous_flight.solution._controls[-1] or {} + for name, value in previous_controls.items(): + if name in self._controls: + self._controls[name] = limited_value( + value, self._control_limits[name], name + ) + self._previous_states = previous_flight.solution.phases[-1].state_dict( + previous_flight.solution.raw_row(-1)[1:] + ) # Set unused monitors self.out_of_rail_state = self.initial_solution[1:] self.out_of_rail_time = self.initial_solution[0] @@ -1016,10 +1088,16 @@ def __initialize_flight_phases(self): def __simulate_phase(self, phase, phase_index): """Run one Flight phase across all time nodes.""" if phase_index > 0: - # A new phase begins. Seed its raw state from the canonical state - # that ended the previous phase and open a fresh one in the solution. + # A new phase begins. Seed its raw state from the state that ended + # the previous phase and open a fresh one in the solution. previous_canonical = self.solution.canonical_row(-1)[1:] - y0 = phase.dynamics.initial_state(phase.t, previous_canonical) + previous = self.solution.phases[-1].state_dict( + self.solution.raw_row(-1)[1:] + ) + # A phase that does not integrate every canonical state holds the + # others at the values it began with + phase.dynamics = phase.dynamics.started_from(previous_canonical) + y0 = phase.dynamics.initial_state(phase.t, previous_canonical, previous) self.solution._start_phase( phase.dynamics, start_canonical=tuple(previous_canonical), @@ -1047,6 +1125,14 @@ def __simulate_phase(self, phase, phase_index): # Initialize phase time nodes self.__setup_phase_time_nodes(phase) + if phase_index == 0: + # Every sensor reads once on the pad, as a flight computer has + # readings before launch, so no event or controller ever finds a + # sensor without one. The schedule never samples the start itself. + sensor_events = [ + event for _, event in getattr(self.rocket, "_sensor_events", ()) + ] + call_events(self, sensor_events, phase, phase_index, 0, phase.t, y0) self.__simulate_phase_nodes(phase, phase_index) def __setup_phase_time_nodes(self, phase): @@ -1070,12 +1156,18 @@ def __setup_phase_time_nodes(self, phase): self._non_overshootable_events, phase.t, phase.time_bound ) - # Add motor burn nodes so that integration always happen during burn + # Add motor burn nodes so that integration always happen during burn. + # A rocket sitting still on the rail lets the solver's steps grow + # freely, and one step could go over the whole burn, leaving the + # rocket on the pad. A step that ends at the time of maximum thrust + # ends with the rocket being pushed, so the solver refines it. motor = self.rocket.motor + burn_times = [motor.max_thrust_time] if motor.burn_start_time > 0: - for t_burn in (motor.burn_start_time, motor.burn_out_time): - if phase.t < t_burn < phase.time_bound: - phase.time_nodes.add_node(t_burn, []) + burn_times += [motor.burn_start_time, motor.burn_out_time] + for t_burn in burn_times: + if phase.t < t_burn < phase.time_bound: + phase.time_nodes.add_node(t_burn, []) # Organize time nodes phase.time_nodes.sort() @@ -1137,10 +1229,19 @@ def __run_node_solver_loop(self, phase, phase_index, node_index): while phase.solver.status == "running": self.__execute_solver_step(phase) self.__process_events(phase, phase_index, node_index) - self.__post_process_step() + self.__store_row_controls() def __execute_solver_step(self, phase): """Execute one solver step and update simulation history.""" + # What each event run in this step found (controls and memory), so a + # rollback inside it can undo what was done after the time it goes + # back to, by time and event, in the order they ran. Filled by + # event_execution.save_for_rollback + self._step_log = {} + # What the flight's schedule was before each event that changed it in + # this step, in the order they ran. Filled by + # event_execution.save_schedule + self._schedule_log = [] # Execute solver step, log solution and function evaluations phase.solver.step() self.solution._append([phase.solver.t, *phase.solver.y]) @@ -1156,17 +1257,17 @@ def __execute_solver_step(self, phase): print(f"Current Simulation Time: {self.t:3.4f} s", end="\r") def __process_events(self, phase, phase_index, node_index): - # 1. Determine if we must rollback - time, state, events_to_evaluate, rolled_back = ( - self.__process_overshootable_nodes(phase, phase_index, node_index) + # 1. The sampling times the step went past, which may cut it + time, state, rolled_back = self.__process_overshootable_nodes( + phase, phase_index, node_index ) - # 2. Add continuous events to the pool and order based on priority - events_to_evaluate.extend(phase.time_nodes.continuous_events) - events_to_evaluate.sort(key=lambda event: event.priority) - - # 3. Evaluate combined events in sequence ordered by priority - trajectory_changed = call_events( + # 2. The events checked at every step, in order of priority, at the + # step's end or where it was cut + events_to_evaluate = sorted( + phase.time_nodes.continuous_events, key=lambda event: event.priority + ) + call_events( flight=self, events=events_to_evaluate, phase=phase, @@ -1176,26 +1277,36 @@ def __process_events(self, phase, phase_index, node_index): state=state, ) - # 4. If the flight was rolled back, or a command moved this phase's - # end, and the phase is still being flown, restart the solver from - # the flight's current state. - if (rolled_back or trajectory_changed) and phase.solver.status == "running": + # 3. After a rollback, or an event that happened at an exact time + # inside the step and changed the trajectory, the solver stands past + # the flight, so it is rebuilt from the flight's state unless the + # node is over. An event that moved the phase's end without changing + # the trajectory (a new phase after a lag) only moves the solver's + # bound. + next_node_time = phase.time_nodes[node_index + 1].t + if (rolled_back or self.t < phase.solver.t) and self.t < next_node_time: self.__restart_phase_solver(phase, node_index) + elif phase.solver.status == "running" and ( + phase.solver.t_bound != next_node_time + ): + self.__sync_node_solver_bound( + phase, phase.time_nodes[node_index], node_index + ) def __process_overshootable_nodes(self, phase, phase_index, node_index): - """Checks for overshootable node triggers without executing state - changes, rolls back if needed.""" + """Run the events of the sampling times the solver step went past, in + time order, and cut the step at the first one whose commands change the + trajectory. Returns the time and raw state the step now ends at, and + whether it was cut.""" # Construct nodes considering all events discrete call times overshootable_nodes = self.__build_overshootable_nodes() if not any(node.events for node in overshootable_nodes.list): - return self.t, self.y_sol, [], False # Nothing scheduled in this step + return self.t, self.y_sol, False # Nothing scheduled in this step # Evaluate common kwargs parameters for event triggers. event_kwargs = build_event_kwargs(self, self.t, self.y_sol, phase) - # Feed overshootable time nodes trigger - events_to_evaluate = [] interpolator = phase.solver.dense_output() for overshootable_node in overshootable_nodes.list: if not overshootable_node.events: @@ -1204,18 +1315,17 @@ def __process_overshootable_nodes(self, phase, phase_index, node_index): interpolated_time = overshootable_node.t event_kwargs = refresh_event_kwargs( - flight=self, event_kwargs=event_kwargs, interpolated_time=interpolated_time, interpolated_state=interpolated_state, ) - if out_of_rail_trigger(event_kwargs) or impact_trigger(event_kwargs): + if out_of_rail_trigger(self, event_kwargs) or impact_trigger(event_kwargs): continue # past the rail exit or the impact, where the step is cut # Check events for current node rolled_back = False for event in overshootable_node.events: - rolled_back, should_recall = process_overshootable_event( + rolled_back = process_overshootable_event( flight=self, event=event, event_kwargs=event_kwargs, @@ -1224,21 +1334,18 @@ def __process_overshootable_nodes(self, phase, phase_index, node_index): node_index=node_index, rolled_back=rolled_back, ) - if should_recall: - events_to_evaluate.append(event) if rolled_back: - return interpolated_time, interpolated_state, events_to_evaluate, True + return interpolated_time, interpolated_state, True - return self.t, self.y_sol, events_to_evaluate, False + return self.t, self.y_sol, False def __restart_phase_solver(self, phase, node_index): """Rebuild the phase's solver from the flight's current time and state. - Used when the state the solver holds is no longer the flight's: after - a rollback, or after a command moved the phase's end. The phase, its - equations and its node schedule are kept, so the solver simply runs on - to the next node. + Used when the state the solver holds is no longer the flight's, after + a rollback. The phase, its equations and its node schedule are kept, + so the solver simply runs on to the next node. """ phase.solver = self._solver( phase.dynamics, @@ -1277,80 +1384,35 @@ def __build_overshootable_nodes(self): return overshootable_nodes - def __post_process_step(self): - """Record the post-process variables of every stored row that lacks them. - - Does nothing unless the flight has an event that changes the dynamics. - Recording as the simulation runs captures a parameter change a - controller made, which a later replay over the stored states could not - reproduce: the replay would read the rocket in the configuration it - ended the flight in. This is what keeps the accelerations, forces and - moments accurate for a flight whose controllers move an air brake or a - fin. - - Called once per solver step, after the step's events are handled. The - rows without values are the ones written since the last call, and they - always sit together at the end: normally just the step's own row. A - row an event inserts to mark its exact time is recorded when it is - inserted (see :meth:`_post_process_row`), since a later event of the - same step may change the rocket. - """ - solution = self.solution - if not solution.records_post_values: - return - post_values = solution._post_values - index = len(post_values) - 1 - while index >= 0 and post_values[index] is None: - self._post_process_row(index) - index -= 1 + def __store_row_controls(self): + """Store a copy of the control inputs with every row that has none. - def _post_process_row(self, index): - """Record the post-process variables of one stored row. - - Computed from the row's own time and state, with the rocket as it is - now. Does nothing unless the flight records its post-process values. - - Parameters - ---------- - index : int - Row position across the whole flight. Negative values count from - the end. + Called once per solver step, after the step's events are handled, so + a row carries what its events wrote. The rows without controls are the + ones written since the last call: normally just the step's own row, + plus the flight's first row on the first call. A row an event inserts + at its exact time gets its controls when it is inserted. """ - solution = self.solution - if not solution.records_post_values: + controls = self.solution._controls + index = len(controls) - 1 + if index < 0 or controls[index] is not None: return - # The phase that owns the row, which is not always the phase being - # flown: one that has only just begun holds no rows yet. - phase = solution.phases[solution.phase_index_at(index)] - row = solution.raw_row(index) - solution._set_post_values( - index, - phase.dynamics.post_process_values( - phase.bound_dynamics.post_process_at(row[0], row[1:]) - ), - ) + stored = dict(self._controls) + while index >= 0 and controls[index] is None: + self.solution._set_controls(index, stored) + index -= 1 def __finalize_simulation(self): """Finalize and cache simulation outputs.""" self.t_final = self.t - if self.sensors: - self.__cache_sensor_data() + # Copied, since the events are reset if the rocket flies again + self._records = self.records + self._event_outputs = self.event_outputs logger.info("Simulation completed at time: %.4f s", self.t) - def __cache_sensor_data(self): - """Cache sensor data for simulations with sensors.""" - sensor_data = {} - sensors = [] - for sensor in self.sensors: - # skip sensors that are used more then once in the rocket - if sensor not in sensors: - sensors.append(sensor) - sensor_data[sensor] = sensor.measured_data[:] - self.sensor_data = sensor_data - @deprecated( reason="Flight.get_solution_at_time is deprecated", - version="v1.14", + version="v1.16", alternative="flight.solution.at(t)", ) def get_solution_at_time(self, t, atol=1e-3): @@ -1449,7 +1511,7 @@ def lateral_surface_wind(self): @cached_property @deprecated( reason="Flight.solution_array is deprecated", - version="v1.14", + version="v1.16", alternative="flight.solution['name'] for a single variable, or " "flight.solution.canonical_array for the full 14-column table", ) @@ -1570,84 +1632,84 @@ def w3(self): def ax(self): """Acceleration of the rocket's center of dry mass along the X (East) axis in the inertial frame as a function of time.""" - return self.solution.post["ax"] + return self.solution.ax @funcify_method("Time (s)", "Ay (m/s²)", "spline", "zero") def ay(self): """Acceleration of the rocket's center of dry mass along the Y (North) axis in the inertial frame as a function of time.""" - return self.solution.post["ay"] + return self.solution.ay @funcify_method("Time (s)", "Az (m/s²)", "spline", "zero") def az(self): """Acceleration of the rocket's center of dry mass along the Z (Up) axis in the inertial frame as a function of time.""" - return self.solution.post["az"] + return self.solution.az @funcify_method("Time (s)", "α1 (rad/s²)", "spline", "zero") def alpha1(self): """Angular acceleration of the rocket in the x direction of the rocket's body frame as a function of time, in rad/s. Sometimes referred to as pitch acceleration.""" - return self.solution.post["alpha1"] + return self.solution.alpha1 @funcify_method("Time (s)", "α2 (rad/s²)", "spline", "zero") def alpha2(self): """Angular acceleration of the rocket in the y direction of the rocket's body frame as a function of time, in rad/s. Sometimes referred to as yaw acceleration.""" - return self.solution.post["alpha2"] + return self.solution.alpha2 @funcify_method("Time (s)", "α3 (rad/s²)", "spline", "zero") def alpha3(self): """Angular acceleration of the rocket in the z direction of the rocket's body frame as a function of time, in rad/s. Sometimes referred to as roll acceleration.""" - return self.solution.post["alpha3"] + return self.solution.alpha3 # Process third type of outputs - Temporary values @funcify_method("Time (s)", "R1 (N)", "spline", "zero") def R1(self): """Aerodynamic force acting along the x-axis of the rocket's body frame as a function of time. Expressed in Newtons (N).""" - return self.solution.post["R1"] + return self.solution.R1 @funcify_method("Time (s)", "R2 (N)", "spline", "zero") def R2(self): """Aerodynamic force acting along the y-axis of the rocket's body frame as a function of time. Expressed in Newtons (N).""" - return self.solution.post["R2"] + return self.solution.R2 @funcify_method("Time (s)", "R3 (N)", "spline", "zero") def R3(self): """Aerodynamic force acting along the z-axis of the rocket's body frame as a function of time. Expressed in Newtons (N).""" - return self.solution.post["R3"] + return self.solution.R3 @funcify_method("Time (s)", "M1 (Nm)", "linear", "zero") def M1(self): """Aerodynamic moment acting along the x-axis of the rocket's body frame as a function of time. Expressed in Newtons (N).""" - return self.solution.post["M1"] + return self.solution.M1 @funcify_method("Time (s)", "M2 (Nm)", "linear", "zero") def M2(self): """Aerodynamic moment acting along the y-axis of the rocket's body frame as a function of time. Expressed in Newtons (N).""" - return self.solution.post["M2"] + return self.solution.M2 @funcify_method("Time (s)", "M3 (Nm)", "linear", "zero") def M3(self): """Aerodynamic moment acting along the z-axis of the rocket's body frame as a function of time. Expressed in Newtons (N).""" - return self.solution.post["M3"] + return self.solution.M3 @funcify_method("Time (s)", "Net Thrust (N)", "linear", "zero") def net_thrust(self): """Net thrust of the rocket as a Function of time. This is the actual thrust force experienced by the rocket. It may be corrected with the atmospheric pressure if a reference pressure is defined.""" - return self.solution.post["net_thrust"] + return self.solution.net_thrust @funcify_method("Time (s)", "Pressure (Pa)", "spline", "constant") def pressure(self): @@ -1680,7 +1742,214 @@ def wind_velocity_y(self): """Wind velocity in the Y direction (north) as a Function of time.""" return [(t, self.env.wind_velocity_y.get_value_opt(z)) for t, z in self.z] - # Process fourth type of output - values calculated from previous outputs + # Process fourth type of outputs - the controls, the controllables' states, + # the sensor readings and the events' records, as the flight kept them + @cached_property + def controls(self): + """The control inputs over the flight, by controllable, as Functions + of time. + + A controllable is found by its name as given, or by that name in + snake_case as an attribute, as a controller writes it in + ``context.controls``: + + .. code-block:: python + + flight.controls["Air Brakes"].deployment_level(5.0) + flight.controls.air_brakes.deployment_level(5.0) + + both give the deployment level in force at 5 s. A control written by + sampled controllers holds its value until it was written again; one a + continuous controller's law wrote is known at every stored row and + interpolated between them. The raw numbers are + ``flight.solution.controls``. Looping over it gives the names of the + controllables. Empty for a flight without controls. + + Returns + ------- + dict + Controllable name to its control inputs. + """ + owners = { + snake_case_key(owner.name): owner.name for owner in self._control_owners + } + data = {} + for name in self.solution.control_names: + key, _, control = name.partition(".") + owner = owners.get(key, key) + label = f"{owner} {control}" + history, by_law = self.solution._control_history(name) + if by_law: + function = Function(history, "Time (s)", label, "linear", "constant") + else: + function = history_function(history, label) + data.setdefault(owner, {})[control] = function + return _ResultsDict(data) + + @cached_property + def state_history(self): + """The states of the rocket's controllables over the flight, by + controllable: the angle a lagging fin reached, the integral of a + continuous controller. + + A controllable is found by its name as given, or by that name in + snake_case as an attribute, the two being the same, and each of its + states is a :class:`rocketpy.Function` of time: + + .. code-block:: python + + flight.state_history["Canards"].a1(2.0) + flight.state_history.canards.a1.plot() + flight.state_history.roll_pi.integral + + Looping over it gives the names of the controllables with states. + Empty for a rocket whose controllables have none. + + Returns + ------- + dict + Controllable name to its states, by state name. + """ + data = {} + rocket = self.rocket + for controllable in ( + *rocket._parts_with_states, + *rocket._continuous_controllers, + ): + if controllable.states: + data[controllable.name] = { + state: Function( + self.solution[name], + "Time (s)", + f"{controllable.name} {state}", + "linear", + "constant", + ) + for state, name in zip( + controllable.states, controllable._state_names() + ) + } + return _ResultsDict(data) + + @property + def records(self): + """What the events of the flight recorded with ``context.record``, + by event, exactly as recorded. + + An event, such as a controller, is found by its name as given, or by + that name in snake_case as an attribute, the two being the same: + + .. code-block:: python + + flight.records["Roll Damper"].error + flight.records.roll_damper.error + + Each record is the list of ``(time, value)`` pairs the event stored, + with ``value`` the object it passed to ``context.record``: a number, a + vector, a text, a dictionary. Events with the same name are numbered + from 2 in the order they were given to the flight (``"Event"``, + ``"Event 2"``). Looping over it gives the names of the events that + recorded something. + + Returns + ------- + dict + Event name to its records, each record name to its list of + ``(time, value)`` pairs. + """ + # A flight that ended, or was loaded from a file, keeps its records; + # one still flying reads them off its events, where they are growing + kept = getattr(self, "_records", None) + if kept is not None: + return kept + events = list(getattr(self, "events", ())) + names = unique_names([event.name for event in events]) + return _ResultsDict( + { + name: { + record: list(values) for record, values in event._records.items() + } + for name, event in zip(names, events) + if event._records + } + ) + + @property + def event_outputs(self): + """What the events of the flight wrote to their outputs, by event. + + An output is a value an event shares with the other events through + ``context.outputs``. An event, such as a controller, is found by its + name as given, or by that name in snake_case as an attribute, the two + being the same: + + .. code-block:: python + + flight.event_outputs["Guidance"].pitch_setpoint + flight.event_outputs.guidance.pitch_setpoint + + Each output is the list of ``(time, value)`` pairs the event wrote, + with the value as it was when written: a number, a vector, a text, a + dictionary. Looping over it gives the names of the events that wrote + an output. + + Returns + ------- + dict + Event name to its outputs, each output name to its list of + ``(time, value)`` pairs. + """ + # As for the records: kept once the flight ended or was loaded + kept = getattr(self, "_event_outputs", None) + if kept is not None: + return kept + return _ResultsDict( + { + event.name: { + name: list(points) for name, points in event._output_history.items() + } + for event in getattr(self, "_output_events", {}).values() + if event._output_history + } + ) + + @cached_property + def sensor_history(self): + """What the sensors of the flight read, by sensor, as Functions of time. + + A sensor is found by its name as given, or by that name in snake_case + as an attribute, the two being the same, as an event function reads + it in ``context.sensors``. Each channel holds each reading until the + next one, which is what a flight computer reading the sensor sees: + + .. code-block:: python + + flight.sensor_history["Barometer"].pressure(5.0) + flight.sensor_history.barometer.pressure(5.0) + + both give the last pressure read at or before 5 s, with its noise and + resolution. A sensor added in several positions is numbered from 2 at + the positions after the first: ``"Accelerometer"``, + ``"Accelerometer 2"``. The readings themselves are + ``flight.solution.sensors``. Looping over it gives the names. + + Returns + ------- + dict + Sensor name to its channels. Empty for a flight without + sensors. + """ + return _ResultsDict( + { + name: { + channel: history_function(points, f"{name} {channel}") + for channel, points in channels.items() + } + for name, channels in self.solution._sensors.items() + } + ) + + # Process fifth type of output - values calculated from previous outputs # Frame conversions @cached_property def _stacked_velocity_body_frame(self): @@ -3128,6 +3397,8 @@ def to_dict(self, **kwargs): "M2": self.M2, "M3": self.M3, "net_thrust": self.net_thrust, + "records": self.records, + "event_outputs": self.event_outputs, "surface_switches": surface_switches, } @@ -3191,24 +3462,59 @@ def from_dict(cls, data): simulation_mode=data.get("simulation_mode", "6DOF"), ) + @property + @deprecated( + reason="Flight.sensor_data is deprecated", + version="v1.16.0", + alternative="`flight.sensor_history` for each sensor's readings as " + "Functions of time, or `flight.solution.sensors` for the readings", + ) + def sensor_data(self): + """What each sensor read over the flight, as in v1.13: a dictionary + from the sensor object to its list of ``(time, *reading)`` tuples, or + to one such list per position when the sensor was added to the rocket + in more than one position. + + .. deprecated:: 1.15 + Use :attr:`sensor_history`, which gives each sensor's readings by + name as Functions of time, or ``flight.solution.sensors`` for the + readings themselves. + """ + return _sensor_rows(self) + @deprecated( reason="Controller observed variables are no longer supported.", version="v1.16.0", - alternative="Access the desired variables via controller.log", + alternative="Record values with `context.record(...)` in the controller " + "function and read them as `flight.records`", ) def get_controller_observed_variables(self): - """Retrieve the observed variables from each controller. + """Retrieve the observed variables of each controller. + + For a controller function written the deprecated positional way, this + is its ``observed_variables`` list, as in v1.13: the + ``initial_observed_variables`` (if any), then every value it returned + other than ``None``. For any other controller, it is an empty list: + such a controller records values with ``context.record``, read after + the flight in ``flight.records``. - If there is only one controller, its log is returned directly. If - there are multiple controllers, a list of logs is returned. + If there is only one controller, its list is returned directly. If + there are multiple controllers, a list of lists is returned. Returns ------- list - Controller log(s) containing the return values of each - controller function call. + The observed variables of each controller. """ - observed_variables = [controller.log for controller in self._controllers] + # pylint: disable-next=import-outside-toplevel + from ..control._legacy import _PositionalController + + observed_variables = [ + c.controller_function.observed_variables + if isinstance(c.controller_function, _PositionalController) + else [] + for c in self.controllers + ] return ( observed_variables[0] if len(observed_variables) == 1 diff --git a/rocketpy/simulation/flight_data_exporter.py b/rocketpy/simulation/flight_data_exporter.py index 16cb22dfb..36bd33b3e 100644 --- a/rocketpy/simulation/flight_data_exporter.py +++ b/rocketpy/simulation/flight_data_exporter.py @@ -39,7 +39,7 @@ def pressures(self, file_name, time_step): .. note:: Noisy pressure signal export has been removed. To export noisy pressure readings, add a Barometer Sensor with the desired noise - model to the rocket and access its data via ``flight.sensor_data``. + model to the rocket and access its data via ``flight.solution.sensors``. This function was created especially for the 'Projeto Jupiter' Electronics Subsystems team and aims to help in configuring @@ -200,29 +200,29 @@ def sensor_data(self, file_name, sensor=None): as a string with the sensor name. If None, all sensors data will be exported. Default is None. """ - f = self._flight + sensor_rows = _sensor_rows(self._flight) if sensor is None: data_dict = {} - for used_sensor, measured_data in f.sensor_data.items(): + for used_sensor, measured_data in sensor_rows.items(): data_dict[used_sensor.name] = measured_data else: # export data of only that sensor data_dict = {} if not isinstance(sensor, str): - data_dict[sensor.name] = f.sensor_data[sensor] + data_dict[sensor.name] = sensor_rows[sensor] else: # sensor is a string - matching_sensors = [s for s in f.sensor_data if s.name == sensor] + matching_sensors = [s for s in sensor_rows if s.name == sensor] if len(matching_sensors) > 1: data_dict[sensor] = [] for s in matching_sensors: - data_dict[s.name].append(f.sensor_data[s]) + data_dict[s.name].append(sensor_rows[s]) elif len(matching_sensors) == 1: - data_dict[sensor] = f.sensor_data[matching_sensors[0]] + data_dict[sensor] = sensor_rows[matching_sensors[0]] else: - raise ValueError("Sensor not found in the Flight.sensor_data.") + raise ValueError("Sensor not found in the flight's sensors.") with open(file_name, "w") as file: json.dump(data_dict, file) @@ -313,8 +313,8 @@ def kml( kml.save(file_name) print("File ", file_name, " saved with success!") - # Deprecated aliases -- kept for backward compatibility with the - # ``export_*`` method names used prior to v1.15. + # Deprecated aliases, kept for backward compatibility with the earlier + # ``export_*`` method names until their removal in v1.16. @deprecated(version="v1.16.0", alternative="pressures") def export_pressures(self, file_name, time_step): return self.pressures(file_name, time_step) @@ -330,3 +330,28 @@ def export_sensor_data(self, file_name, sensor=None): @deprecated(version="v1.16.0", alternative="kml") def export_kml(self, *args, **kwargs): return self.kml(*args, **kwargs) + + +def _sensor_rows(flight): + """Return what each sensor of ``flight`` read as ``(time, *reading)`` + tuples, keyed by the sensor object: one list, or one list per position + when the sensor was added to the rocket in more than one position. The + shape of a sensor's ``measured_data``, built from the flight's solution so + it is the same for a flight read back from a file.""" + readings = flight.solution._sensors # pylint: disable=protected-access + runs = {} + for sensor, event in flight._sensors_by_key.values(): # pylint: disable=protected-access + channels = readings.get(event._position_name, {}) + points = [channels.get(label) for label, _ in sensor.channels] + rows = [] + if all(channel for channel in points): + rows = list( + zip( + [t for t, _ in points[0]], + *([value for _, value in channel] for channel in points), + ) + ) + runs.setdefault(sensor, []).append(rows) + return { + sensor: lists[0] if len(lists) == 1 else lists for sensor, lists in runs.items() + } diff --git a/rocketpy/simulation/helpers/conditions.py b/rocketpy/simulation/helpers/conditions.py new file mode 100644 index 000000000..406dea43a --- /dev/null +++ b/rocketpy/simulation/helpers/conditions.py @@ -0,0 +1,203 @@ +from functools import cached_property + +from rocketpy.mathutils.vector_matrix import Matrix, Vector + +from .state import _State + + +class FlightConditions: + """The flight at one moment: where the rocket is and the air around it. + + One of these is given as ``conditions`` to: + + - the methods of :class:`rocketpy.ThrustEffector` and + :class:`rocketpy.ForceEffector`; + - the ``actual_controls`` and ``state_derivative`` of every controllable; + - the law of a :class:`rocketpy.ContinuousController`. + + An event or controller function reads the same values on its context, as + ``context.pressure`` or ``context.mach``, and the object itself as + ``context.conditions``. + + The air data are looked up the first time they are read, so reading only + what is needed keeps the simulation fast. Every flight phase gives the 13 + standard states listed below, so all of these can be read in any phase. + + Attributes + ---------- + time : float + Time, in s. + state : _State + The rocket's state, read by name, ``conditions.state.w3``, or by + position, ``conditions.state[12]``. The 13 standard states are + ``x``, ``y``, ``z`` (m) and ``vx``, ``vy``, ``vz`` (m/s) in the Earth + frame, the attitude quaternion ``e0`` to ``e3``, and ``w1``, ``w2``, + ``w3`` (rad/s) in the rocket's body frame. Any other state the + current phase follows is read by name only, such as + ``conditions.state.canards_a1`` for a state of a controllable. + height_agl : float + Height above the ground, in m. + pressure : float + Air pressure at the rocket's altitude, in Pa. + density : float + Air density at the rocket's altitude, in kg/m³. + speed_of_sound : float + Speed of sound at the rocket's altitude, in m/s. + dynamic_viscosity : float + Dynamic viscosity of the air at the rocket's altitude, in Pa s. + wind_velocity : Vector + Wind velocity at the rocket's altitude, in m/s, in the Earth frame + (x East, y North, z up). + stream_velocity : Vector + Velocity of the air relative to the rocket, in m/s, in the rocket's + body frame (z along the rocket's axis, toward the nose). + stream_speed : float + Speed of the air relative to the rocket, in m/s. + mach : float + Mach number of the air relative to the rocket. + body_to_earth : Matrix + Rotation from the rocket's body frame to the Earth frame: + ``conditions.body_to_earth @ vector`` gives, in the Earth frame, a + vector given in the body frame. + earth_to_body : Matrix + The opposite rotation, from the Earth frame to the body frame. + rocket : Rocket + The rocket being flown. + environment : Environment + The environment it flies in. + """ + + def __init__( + self, + rocket, + environment, + time, + state, + phase_names=(), + phase_state=(), + ): + """Describe the flight of ``rocket`` in ``environment`` at ``time``. + + Parameters + ---------- + rocket : Rocket + The rocket being flown. + environment : Environment + The environment it flies in. + time : float + Time, in s. + state : sequence of float + The rocket's 13 standard states, in their order (see the class). + phase_names : sequence of str, optional + The names of the states the flight phase follows, to read the + ones that are not among the 13 by name, including the states of + the rocket's controllables. Default is none. + phase_state : sequence of float, optional + The value of each state in ``phase_names``, in the same order. + """ + self.time = time + self._state = state + self.rocket = rocket + self.environment = environment + self._phase_names = phase_names + self._phase_state = phase_state + + @cached_property + def state(self): + """The rocket's state, by name or by position (see the class).""" + return _State(self._state, self._phase_names, self._phase_state) + + @cached_property + def height_agl(self): + """Height of the rocket above the ground, in m.""" + return self._state[2] - self.environment.elevation + + def states_of(self, controllable): + """Return the values of ``controllable``'s own states, in the order of + its ``states``. Empty for a controllable without states. + + Inside an effector's method, ``conditions.states_of(self)`` gives the + effector its states without it having to know how they are named in + the flight. + + Parameters + ---------- + controllable : Controllable + The controllable whose states are wanted. + + Returns + ------- + list of float + """ + names, values = self._phase_names, self._phase_state + return [ + values[names.index(name)] + for name in controllable._state_names() # pylint: disable=protected-access + ] + + @cached_property + def pressure(self): + """Air pressure at the rocket's altitude, in Pa.""" + return self.environment.pressure.get_value_opt(self._state[2]) + + @cached_property + def density(self): + """Air density at the rocket's altitude, in kg/m³.""" + return self.environment.density.get_value_opt(self._state[2]) + + @cached_property + def speed_of_sound(self): + """Speed of sound at the rocket's altitude, in m/s.""" + return self.environment.speed_of_sound.get_value_opt(self._state[2]) + + @cached_property + def wind_velocity(self): + """Wind velocity at the rocket's altitude, in m/s, in the Earth frame + (x East, y North, z up).""" + z = self._state[2] + return Vector( + [ + self.environment.wind_velocity_x.get_value_opt(z), + self.environment.wind_velocity_y.get_value_opt(z), + 0, + ] + ) + + @cached_property + def dynamic_viscosity(self): + """Dynamic viscosity of the air at the rocket's altitude, in Pa s.""" + return self.environment.dynamic_viscosity.get_value_opt(self._state[2]) + + @cached_property + def body_to_earth(self): + """Rotation from the rocket's body frame to the Earth frame, as a + matrix.""" + return Matrix.transformation(self._state[6:10]) + + @cached_property + def earth_to_body(self): + """Rotation from the Earth frame to the rocket's body frame, as a + matrix.""" + return self.body_to_earth.transpose + + @cached_property + def _stream_velocity_earth(self): + """Velocity of the air relative to the rocket, in m/s, in the Earth + frame.""" + return self.wind_velocity - Vector(self._state[3:6]) + + @cached_property + def stream_velocity(self): + """Velocity of the air relative to the rocket, in m/s, in the rocket's + body frame (z along the rocket's axis, toward the nose).""" + return self.earth_to_body @ self._stream_velocity_earth + + @cached_property + def stream_speed(self): + """Speed of the air relative to the rocket, in m/s.""" + return abs(self._stream_velocity_earth) + + @cached_property + def mach(self): + """Mach number of the air relative to the rocket.""" + return self.stream_speed / self.speed_of_sound diff --git a/rocketpy/simulation/helpers/dynamics.py b/rocketpy/simulation/helpers/dynamics.py index 8850c1159..f5f14b4b2 100644 --- a/rocketpy/simulation/helpers/dynamics.py +++ b/rocketpy/simulation/helpers/dynamics.py @@ -1,5 +1,11 @@ +import inspect +import math + import numpy as np +from ...control._helpers import initial_controls, not_finite_error +from ..events.views import ControlsView +from .conditions import FlightConditions from .flight_derivatives import ( u_dot, u_dot_generalized, @@ -8,24 +14,9 @@ udot_rail1, ) -CANONICAL_STATE_NAMES = ( - "x", - "y", - "z", - "vx", - "vy", - "vz", - "e0", - "e1", - "e2", - "e3", - "w1", - "w2", - "w3", -) - -"""Names of the 13 states in RocketPy's full flight state, in order.""" -CANONICAL_INDEX = {name: index for index, name in enumerate(CANONICAL_STATE_NAMES)} +# The names of the 13 canonical states are defined with the state view, a +# module with no imports of its own, and reached from here by everyone else +from .state import CANONICAL_INDEX, CANONICAL_STATE_NAMES # The accelerations, linear and angular. ACCELERATION_VARS = ("ax", "ay", "az", "alpha1", "alpha2", "alpha3") @@ -61,8 +52,8 @@ class _PhaseDynamics: Notes ----- - RocketPy defines one of these per kind of flight phase it knows how to fly: - ``RAIL_DYNAMICS``, ``SOLID_PROPULSION_DYNAMICS``, ``SIX_DOF_DYNAMICS``, + RocketPy defines one description per kind of flight phase it knows how to + fly: ``RAIL_DYNAMICS``, ``SOLID_PROPULSION_DYNAMICS``, ``SIX_DOF_DYNAMICS``, ``THREE_DOF_DYNAMICS`` and ``PARACHUTE_DYNAMICS``. """ @@ -75,6 +66,7 @@ def __init__( # pylint: disable=too-many-arguments to_canonical=None, to_canonical_dot=None, initial_state=None, + reads_controls=True, ): """Describe one kind of flight phase. @@ -83,16 +75,27 @@ def __init__( # pylint: disable=too-many-arguments name : str Name of this kind of phase, such as ``"parachute"``. derivative : callable or None - The function ``f(flight, t, u)`` giving the time derivative of each - state in ``states``, in that same order. ``u`` is the phase's own - state. With ``None`` the phase's states can still be read by name, - but the phase cannot be flown or post-processed. + The function ``f(flight, t, u, controls)`` giving the time + derivative of each state in ``states``, in that same order. ``u`` + is the phase's own state and ``controls`` the flight's control + inputs, a dictionary from name to value, such as + ``controls["canards.deflection"]``. + With ``None`` the phase's states can still be read by name, but the + phase cannot be flown or post-processed. A phase that reports post-process variables writes - ``f(flight, t, u, post_processing=False)`` instead, and when the + ``f(flight, t, u, controls, post_processing=False)`` instead, and when the flag is true returns those variables in ``post_process_vars`` order. A phase that reports nothing never sees the flag and can leave it out. + + A derivative that drives the rocket's effectors takes + ``conditions=None`` as well: the :class:`FlightConditions` of the + moment, which it hands to the effector sums of + :mod:`rocketpy.simulation.helpers.flight_derivatives`. It is given + whenever + the rocket has effectors, to every derivative that names the + parameter or takes ``**kwargs``. states : sequence of str Ordered names of the states this phase integrates. Position ``i`` in this list is the position of that state inside every state row of @@ -102,9 +105,11 @@ def __init__( # pylint: disable=too-many-arguments it can add states of its own. An extra state is read by name like any other, through ``solution["my_state"]`` or ``solution.at(t)``, and by events as ``context.state.my_state``. It is not part of the - canonical state, so sensors do not see it. Give an - ``initial_state`` rule to seed it. A state cannot be called - ``names`` or ``values``, which ``context.state`` uses itself. + canonical state, so sensors do not see it. It starts from the + value of the state of the same name in the previous phase; give + an ``initial_state`` rule to seed it otherwise. A state cannot be + called ``names`` or ``values``, which ``context.state`` uses + itself. post_process_vars : sequence of str, optional Ordered names of the variables this phase reports besides its states, such as ``("ax", "ay", "az")``. The order must match what @@ -115,7 +120,9 @@ def __init__( # pylint: disable=too-many-arguments ``values`` is a dictionary of name to value holding this phase's own states plus the value every other canonical state had at the start of the phase, so the function only has to work out the states - it rebuilds and copy the rest:: + it rebuilds and copy the rest: + + .. code-block:: python def my_to_canonical(values): half = values["my_angle"] / 2 @@ -136,14 +143,22 @@ def my_to_canonical(values): Default is None: the phase's own derivatives are used, and every other canonical state has derivative zero. initial_state : callable, optional - Rule ``f(flight, t, canonical_state) -> list`` that seeds this - phase's state from the full canonical state that ended the previous - phase. It must return exactly one value per state in ``states``. + Rule ``f(flight, t, canonical_state, previous) -> list`` that seeds + this phase's state from the full canonical state that ended the + previous phase, and from ``previous``, every state of the previous + phase by name (an empty dictionary at the start of the flight). It + must return exactly one value per state in ``states``. Defaults to picking this phase's states out of the canonical state, which works whenever every state it integrates is a canonical one. - + reads_controls : bool, optional + Whether ``derivative`` reads the control inputs. Give ``False`` for + a phase where the rocket's controllable parts do nothing, as under + a parachute: a control input written during the phase is still + stored, but the solver is not stopped at the moment it is written, + which makes the phase faster to fly. Default is ``True``. """ self.name = name + self.reads_controls = bool(reads_controls) self.derivative = derivative self.states = tuple(states) # ``context.state`` has these two names itself @@ -158,6 +173,10 @@ def my_to_canonical(values): self.state_index = {name: i for i, name in enumerate(self.states)} self.width = len(self.states) self.is_canonical = self.states == CANONICAL_STATE_NAMES + # The 13 canonical states first, in order, then states of its own + self._canonical_first = ( + self.states[: len(CANONICAL_STATE_NAMES)] == CANONICAL_STATE_NAMES + ) self.post_process_vars = tuple(post_process_vars) self.post_process_index = { name: i for i, name in enumerate(self.post_process_vars) @@ -165,6 +184,15 @@ def my_to_canonical(values): self.to_canonical = to_canonical self.to_canonical_dot = to_canonical_dot self._initial_state = initial_state + # Set by _with_controllables on the extended dynamics it builds for one + # rocket: the dynamics it was built from. Dynamics that were not + # extended are their own base. + self._base = self + # Whether the derivative takes the canonical state the phase began + # with, as ``start_canonical``: only the one _with_controllables builds for + # a phase that is not canonical does, to hand the canonical state to + # the rocket's controllables. _BoundDynamics.started_from gives it. + self._takes_start = False # (canonical slot, own index) for each canonical state this phase # integrates: the default way to fill the canonical state. self._own_fills = tuple( @@ -213,18 +241,35 @@ def canonicalize(self, state, start_canonical): The phase's state (without time), in this phase's order. start_canonical : sequence of float or None The canonical state captured at the start of the phase, used to fill - in any state this phase does not integrate. + in any state this phase does not integrate. ``None`` only for a + phase that integrates every canonical state or rebuilds them all. Returns ------- list or sequence of float The 13-value canonical state. When this phase integrates all of them in canonical order, ``state`` is returned unchanged (no copy). + + Raises + ------ + ValueError + If this phase holds some canonical states at their start-of-phase + value and ``start_canonical`` was not given. """ if self.is_canonical: return state if self.to_canonical is not None: return list(self.to_canonical(self.state_values(state, start_canonical))) + if self._canonical_first: + return state[: len(CANONICAL_STATE_NAMES)] + if start_canonical is None: + if len(self._own_fills) < len(CANONICAL_STATE_NAMES): + raise ValueError( + f"Flight phase '{self.name}' does not integrate every " + "canonical state, so its canonical state needs the state " + "the phase began with. Pass start_canonical." + ) + return [state[index] for _, index in self._own_fills] result = list(start_canonical) for slot, index in self._own_fills: result[slot] = state[index] @@ -273,6 +318,8 @@ def canonicalize_derivative(self, state_dot, state=None, start_canonical=None): dict(zip(self.states, state_dot)), ) ) + if self._canonical_first: + return state_dot[: len(CANONICAL_STATE_NAMES)] result = [0.0] * len(CANONICAL_STATE_NAMES) for slot, index in self._own_fills: result[slot] = state_dot[index] @@ -280,8 +327,8 @@ def canonicalize_derivative(self, state_dot, state=None, start_canonical=None): # -- Seeding and solver settings ---------------------------------------- - def initial_state(self, flight, t, canonical_state): - """Seed this phase's state from the canonical state ending the previous one. + def initial_state(self, flight, t, canonical_state, previous=None): + """Seed this phase's state from the state ending the previous one. Parameters ---------- @@ -291,17 +338,24 @@ def initial_state(self, flight, t, canonical_state): The time the phase begins, in seconds. canonical_state : sequence of float The full 13-value canonical state. + previous : dict, optional + Every state of the previous phase by name, canonical or not. A + state that is not canonical carries over from it when this phase + has one of the same name. Default ``None``, at the start of the + flight. Returns ------- list of float The phase's state, in this phase's order. """ + previous = previous or {} if self._initial_state is not None: - return self._initial_state(flight, t, canonical_state) + return self._initial_state(flight, t, canonical_state, previous) if self.is_canonical: return list(canonical_state) - return [canonical_state[CANONICAL_INDEX[name]] for name in self.states] + values = {**previous, **dict(zip(CANONICAL_STATE_NAMES, canonical_state))} + return [values[name] for name in self.states] def select_atol(self, atol): """Map an absolute-tolerance setting onto this phase's states. @@ -315,10 +369,11 @@ def select_atol(self, atol): Returns ------- float or list of float - A single number is returned unchanged. A 13-value canonical vector is - matched to this phase's states by name (states that are not + A single number is returned unchanged. A 13-value canonical vector + is matched to this phase's states by name (states that are not canonical use the largest supplied tolerance), even when the phase - also integrates 13 states. + also integrates 13 states. A vector with one value per state of + this phase is returned as given. Raises ------ @@ -329,8 +384,6 @@ def select_atol(self, atol): if not np.iterable(atol): return atol atol = list(atol) - if self.is_canonical: - return atol if len(atol) == len(CANONICAL_STATE_NAMES): fallback = max(atol) return [ @@ -376,9 +429,11 @@ def post_process_values(self, values): ) return values - def post_process_at(self, flight, t, u, **kwargs): + def post_process_at(self, flight, t, u, controls, **kwargs): """Return this phase's post-process variables at time ``t``. + ``u`` is the phase's state and ``controls`` the control inputs at that + time. Any extra keyword arguments are the phase-specific ones fixed onto the phase when it began, such as which parachute is descending. @@ -390,18 +445,24 @@ def post_process_at(self, flight, t, u, **kwargs): """ if not self.post_process_vars: return [] - return self.derivative(flight, t, u, post_processing=True, **kwargs) + return self.derivative(flight, t, u, controls, post_processing=True, **kwargs) # -- Binding ---------------------------------------------------------- def bind(self, flight, **derivative_kwargs): - """Return a callable bound to ``flight`` for use as a phase derivative. + """Return these dynamics bound to ``flight``, as a :class:`_BoundDynamics` + the solver can call. Any extra keyword arguments are fixed onto the derivative. This is how a - phase carries a parameter that is only known once it begins, such as - which parachute is descending. + flight phase carries a parameter that is only known once it begins, + such as which parachute is descending. The rocket's controllables and + continuous controllers are folded in first (see + :func:`_with_controllables`), so the bound dynamics may have more states + than these. """ - return _BoundDynamics(self, flight, derivative_kwargs) + rocket = getattr(flight, "rocket", None) + dynamics = self if rocket is None else _with_controllables(self, rocket) + return _BoundDynamics(dynamics, flight, derivative_kwargs) class _BoundDynamics: @@ -413,9 +474,16 @@ class _BoundDynamics: reachable through :attr:`dynamics`. """ - __slots__ = ("dynamics", "flight", "kwargs", "__name__") + __slots__ = ( + "dynamics", + "flight", + "kwargs", + "start_canonical", + "_kwargs", + "__name__", + ) - def __init__(self, dynamics, flight, kwargs=None): + def __init__(self, dynamics, flight, kwargs=None, start_canonical=None): """Bind a phase's dynamics to the flight being simulated. Parameters @@ -428,45 +496,331 @@ def __init__(self, dynamics, flight, kwargs=None): Extra arguments fixed onto the derivative and the post-processing pass, for a parameter only known once the phase begins (such as which parachute is descending). Default is none. + start_canonical : sequence of float, optional + The canonical state the phase began with. Kept only by dynamics + whose derivative takes it, those extended for a rocket from a + phase that is not canonical, which fill the canonical states the + phase does not integrate from it. Default is none: see + :meth:`started_from`. """ self.dynamics = dynamics self.flight = flight self.kwargs = dict(kwargs or {}) + # pylint: disable-next=protected-access + self.start_canonical = start_canonical if dynamics._takes_start else None + # What the derivative is called with: the phase's arguments, and the + # start when kept + self._kwargs = ( + self.kwargs + if self.start_canonical is None + else {**self.kwargs, "start_canonical": self.start_canonical} + ) self.__name__ = getattr(dynamics.derivative, "__name__", dynamics.name) + def started_from(self, start_canonical): + """Return these dynamics for a phase that began with the canonical + state ``start_canonical``: a copy that carries it when the derivative + takes it, else these dynamics themselves. + + A flight calls this as each phase begins, so a phase that does not + integrate every canonical state knows the values to hold the others + at, in every call the solver or the post-processing makes. + """ + if not self.dynamics._takes_start: # pylint: disable=protected-access + return self + return _BoundDynamics(self.dynamics, self.flight, self.kwargs, start_canonical) + def __call__(self, t, u): - """Return the state derivative at ``t``, as the ODE solver needs it.""" - return self.dynamics.derivative(self.flight, t, u, **self.kwargs) + """Return the state derivative at ``t``, as the ODE solver needs it, + with the flight's control inputs as they are now.""" + return self.dynamics.derivative( + self.flight, t, u, self.flight._controls, **self._kwargs + ) + + def derivative_at(self, t, u, controls): + """Return the state derivative at ``t`` with the control inputs + ``controls``.""" + return self.dynamics.derivative(self.flight, t, u, controls, **self._kwargs) + + def base_derivative(self, t, u, controls, post_processing=False, conditions=None): + """Return what the phase's own equations give, without the states of + the rocket's controllables the flight adds to them (see + :func:`_with_controllables`). + + For another derivative that reuses these equations from inside its own + call: ``u`` is then the phase's own states, ``controls`` already holds + the values the controllables act with and ``conditions`` is what that + derivative was handed, passed on when given. With ``post_processing`` + the post-process variables are returned instead of the derivative. + """ + kwargs = ( + self.kwargs + if conditions is None + else {**self.kwargs, "conditions": conditions} + ) + return self.dynamics._base.derivative( # pylint: disable=protected-access + self.flight, t, u, controls, post_processing=post_processing, **kwargs + ) + + def post_process_at(self, t, u, controls=None): + """Return this phase's post-process variables at ``t``. - def post_process_at(self, t, u): - """Return this phase's post-process variables at ``t``.""" - return self.dynamics.post_process_at(self.flight, t, u, **self.kwargs) + ``controls`` are the control inputs in force at ``t``, such as the values + stored with a row of the solution. ``None`` uses the flight's control + inputs as they are now. + """ + if controls is None: + controls = getattr(self.flight, "_controls", None) + return self.dynamics.post_process_at( + self.flight, t, u, controls, **self._kwargs + ) - def initial_state(self, t, canonical_state): - """Seed this phase's state from a canonical state.""" - return self.dynamics.initial_state(self.flight, t, canonical_state) + def initial_state(self, t, canonical_state, previous=None): + """Seed this phase's state from a canonical state, and the previous + phase's states by name.""" + return self.dynamics.initial_state(self.flight, t, canonical_state, previous) def __repr__(self): return f"_BoundDynamics(name={self.dynamics.name!r})" +def _with_controllables(dynamics, rocket): # pylint: disable=too-many-statements + """Return a new ``_PhaseDynamics`` that also integrates the rocket's + controllables, or ``dynamics`` itself when there is nothing to add. + + The new dynamics appends to the phase's states the states of the rocket's + continuous controllers (an integrator), then those of its other + controllables (a servo angle). On every solver call its derivative: + + 1. runs the continuous controllers' laws in turn, which write the + control inputs, and keeps what each wrote inside the limits, so the + next law reads the limited values; + 2. lets each controllable turn the values written to its controls + into the ones it acts with; + 3. calls the phase's derivative with those values, and appends the + derivatives of the added states to what it returns. + + The laws and the controllables are told about the flight through a + :class:`FlightConditions`, which reads the 13 canonical states. A + phase with other states, more or fewer, has them worked out from its + own at every call (see :meth:`_PhaseDynamics.canonicalize`), so the + conditions are right in any phase. The same conditions are handed to the phase's derivative + as ``conditions`` when it takes them, for the rocket's effectors; a + rocket with effectors is extended for that alone. + + When there is a continuous controller, the control inputs its law + wrote are also stored with every row, as ``controls..``, + for ``Flight.controls``. + + Parameters + ---------- + dynamics : _PhaseDynamics + The phase's states and equations of motion. + rocket : Rocket + The rocket whose controllables are folded in. + + Returns + ------- + _PhaseDynamics + The extended dynamics, or ``dynamics``. + """ + if dynamics._base is not dynamics: + return dynamics + controls, control_names, limits = initial_controls(rocket.controllables) + # The names of the added states: distinct, and checked to be, when + # each controllable was added to the rocket + names = [] + + def place(controllable): + # Add the controllable's states after the ones already there and + # return where they sit in the phase's state + start = dynamics.width + len(names) + names.extend(controllable._state_names()) + return slice(start, dynamics.width + len(names)) + + # The continuous controllers, then the parts with states or an + # ``actual_controls`` of their own, each with where its states sit. + # Everything the derivative needs is worked out here, once: the + # derivative runs at every evaluation of the equations of motion, so + # it only loops over what is ready. + laws = tuple( + (controller, place(controller)) for controller in rocket._continuous_controllers + ) + acting = tuple( + (part, place(part), control_names.get(part, ())) + for part in rocket._parts_with_states + ) + # Whether the phase's equations accept ``conditions``, by naming it + # or by taking ``**kwargs`` + try: + parameters = inspect.signature(dynamics.derivative).parameters.values() + takes_conditions = any( + p.name == "conditions" or p.kind is p.VAR_KEYWORD for p in parameters + ) + except (TypeError, ValueError): + takes_conditions = False + # The effectors are driven by the equations that take the conditions, + # which are built here + has_effectors = takes_conditions and bool(rocket.effectors.get_components()) + if not (laws or acting or has_effectors): + return dynamics + # The controllers whose states are integrated + integrated = tuple(law for law in laws if law[0].states) + # Each added state with its position in the phase's state + published = tuple(zip(names, range(dynamics.width, dynamics.width + len(names)))) + # With a law, what the laws wrote is stored with every row + recorded = tuple(controls) if laws else () + # The control inputs with limits: a law's write is kept inside them + limited = tuple( + (name, *bounds) for name, bounds in limits.items() if bounds is not None + ) + # The ones without: a law's write is only checked to be a finite number + unlimited = tuple(name for name, bounds in limits.items() if bounds is None) + is_finite = math.isfinite + # The laws read and write the control inputs as a sampled controller + # does, ``controls.canards.fin_1``. One view, pointed at each call's + # values: building one per call costs more than everything else here + view = ControlsView({}, rocket.controllables) + width, equations = dynamics.width, dynamics.derivative + state_names = (*dynamics.states, *names) + is_canonical, canonicalize = dynamics.is_canonical, dynamics.canonicalize + + def written_by(controller): + return f"the continuous controller {controller.name!r}" + + def derivative( + flight, + t, + u, + controls, + post_processing=False, + start_canonical=None, + **kwargs, + ): + own = u[:width] + # The 13 canonical states, which the conditions read. A canonical + # state this phase does not integrate comes from the state the + # phase began with, which the bound dynamics pass + canonical = own if is_canonical else canonicalize(own, start_canonical) + # What the controllables act with: the control inputs, and each + # added state by name, which is how the phase's own equations read + # a controllable's state (they are only given the phase's states) + actual = dict(controls) + for name, index in published: + actual[name] = u[index] + conditions = FlightConditions( + flight.rocket, flight.env, t, canonical, state_names, u + ) + if takes_conditions: + kwargs["conditions"] = conditions + rates = [] + if laws: + view._point_at(actual) + for controller, piece in laws: + controller.law(u[piece], view, conditions) + # Kept inside the limits before the next law reads them. + # ``limited_value``, written out: this runs at every call + for name, low, high in limited: + value = actual[name] + if value != controls[name]: + value = float(value) + # A NaN is the only value that differs from itself. An + # infinite one goes to the limit below + if value != value: # pylint: disable=comparison-with-itself + raise not_finite_error(name, value, written_by(controller)) + actual[name] = ( + low if value < low else high if value > high else value + ) + for name in unlimited: + value = actual[name] + if value != controls[name] and not is_finite(value): + raise not_finite_error(name, value, written_by(controller)) + for controller, piece in integrated: + rates.extend(controller.state_derivative(u[piece], view, conditions)) + # The control inputs as the laws left them, before the + # controllables turn them into what they act with + written = [actual[name] for name in recorded] if post_processing else () + for controllable, piece, inputs in acting: + states = u[piece] + commands = [actual[name] for name in inputs] + for name, value in zip( + inputs, controllable.actual_controls(states, commands, conditions) + ): + actual[name] = value + rates.extend(controllable.state_derivative(states, commands, conditions)) + if post_processing: + values = ( + equations(flight, t, own, actual, post_processing=True, **kwargs) + if dynamics.post_process_vars + else () + ) + return [*values, *written] + return [*equations(flight, t, own, actual, **kwargs), *rates] + + derivative.__name__ = getattr(dynamics.derivative, "__name__", dynamics.name) + + def initial_state(flight, t, canonical_state, previous): + # The phase's states, then each added one: from the previous + # phase when it had it, else from its controllable + starts = [ + start + for controllable, *_ in (*laws, *acting) + for start in controllable.initial_states() + ] + return [ + *dynamics.initial_state(flight, t, canonical_state, previous), + *(previous.get(name, start) for name, start in zip(names, starts)), + ] + + extended = _PhaseDynamics( + dynamics.name, + derivative, + state_names, + (*dynamics.post_process_vars, *(f"controls.{name}" for name in recorded)), + dynamics.to_canonical, + dynamics.to_canonical_dot, + initial_state, + # A state added here follows the control inputs even when the phase's + # own equations read none of them + reads_controls=dynamics.reads_controls or bool(acting or integrated), + ) + extended._base = dynamics + extended._takes_start = not is_canonical + return extended + + RAIL_DYNAMICS = _PhaseDynamics( - "rail", udot_rail1, CANONICAL_STATE_NAMES, FULL_POST_PROCESS_VARS + "rail", + udot_rail1, + CANONICAL_STATE_NAMES, + FULL_POST_PROCESS_VARS, ) SOLID_PROPULSION_DYNAMICS = _PhaseDynamics( - "solid_propulsion", u_dot, CANONICAL_STATE_NAMES, FULL_POST_PROCESS_VARS + "solid_propulsion", + u_dot, + CANONICAL_STATE_NAMES, + FULL_POST_PROCESS_VARS, ) SIX_DOF_DYNAMICS = _PhaseDynamics( - "six_dof", u_dot_generalized, CANONICAL_STATE_NAMES, FULL_POST_PROCESS_VARS + "six_dof", + u_dot_generalized, + CANONICAL_STATE_NAMES, + FULL_POST_PROCESS_VARS, ) THREE_DOF_DYNAMICS = _PhaseDynamics( - "three_dof", u_dot_generalized_3dof, CANONICAL_STATE_NAMES, FULL_POST_PROCESS_VARS + "three_dof", + u_dot_generalized_3dof, + CANONICAL_STATE_NAMES, + FULL_POST_PROCESS_VARS, ) PARACHUTE_DYNAMICS = _PhaseDynamics( "parachute", u_dot_parachute, CANONICAL_STATE_NAMES, PARACHUTE_POST_PROCESS_VARS, + # The air brakes, the control fins and the effectors do nothing under a + # parachute, so a controller that keeps writing to them costs no solver stop + reads_controls=False, ) # Every kind of phase RocketPy ships, by name, so a saved flight gets back the diff --git a/rocketpy/simulation/helpers/flight_derivatives.py b/rocketpy/simulation/helpers/flight_derivatives.py index 83d945bc2..543d1c966 100644 --- a/rocketpy/simulation/helpers/flight_derivatives.py +++ b/rocketpy/simulation/helpers/flight_derivatives.py @@ -14,12 +14,12 @@ def _compute_drag_area( dynamic_viscosity, omega, ): - """Drag coefficient times reference area of the rocket, air brakes included, - in squared meters. + """Drag coefficient times reference area of the rocket's body, in squared + meters. - Selects the power-on/power-off drag curve based on the motor burn state, and - then adds (or, when ``override_rocket_drag`` is set, substitutes) the drag of - any deployed air brakes. The force follows from it as + Selects the power-on/power-off drag curve based on the motor burn state. + The air brakes' drag is not part of it: they are aerodynamic surfaces, + summed with the others. The force follows from it as ``0.5 * rho * stream_speed * drag_area`` times the velocity of the air relative to the rocket: its component along the rocket's axis in a 6-DOF phase, the whole vector in a 3-DOF one. The rocket's drag curve is its axial @@ -80,29 +80,140 @@ def _compute_drag_area( omega[2] * reduced, ) - # Air brakes are drag-only and may override the rocket drag. - for air_brakes in rocket.air_brakes: - if air_brakes.deployment_level > 0: - reduced = air_brakes.reference_length * reduced_per_length - air_brakes_area = air_brakes.reference_area * air_brakes.cA.get_value_opt( - *air_brakes._coefficient_arguments( - alpha, - beta, - mach, - reynolds, - omega[0] * reduced, - omega[1] * reduced, - omega[2] * reduced, - ) - ) - if air_brakes.override_rocket_drag: - drag_area = air_brakes_area # Substitutes rocket drag - else: - drag_area += air_brakes_area return drag_area -def udot_rail1(flight, t, u, post_processing=False): +# What a rocket without force effectors adds. Never changed in place. +_NO_VECTOR = Vector([0, 0, 0]) + + +def _effector_thrust(flight, conditions, net_thrust, controls): + """Return the thrust force, its moment about the center of dry mass and + the nozzle exit, all in the body frame. + + The motor's net thrust acts along the rocket's axis, through the nozzle + exit, which is on the axis moved by the thrust eccentricity. The rocket's + thrust effectors, if it has any, then turn the force and move the nozzle + exit, each in turn.""" + force = Vector([0, 0, net_thrust]) + nozzle = flight.rocket.nozzle_exit + names = flight._control_names + for effector in flight.rocket._thrust_effectors: + force, nozzle = effector.thrust_and_nozzle( + force, + nozzle, + [controls[name] for name in names.get(effector, ())], + conditions, + ) + force, nozzle = Vector(force), Vector(nozzle) + return force, nozzle ^ force, nozzle + + +def _effector_force_and_moment(flight, conditions, controls): + """Return the sum of the force effectors' forces and of their moments + about the center of dry mass, in the body frame. + + An effector placed somewhere on the rocket (``rocket.add_effector``'s + ``position``) acts there: the moment of its force about the center of dry + mass is added to the moment it returns. Both are zero for a rocket without + force effectors.""" + effectors = flight.rocket._force_effectors + if not effectors: + return _NO_VECTOR, _NO_VECTOR + force, moment = Vector([0, 0, 0]), Vector([0, 0, 0]) + names, points = flight._control_names, flight.rocket._effector_points + for effector in effectors: + effector_force, effector_moment = effector.force_and_moment( + [controls[name] for name in names.get(effector, ())], conditions + ) + effector_force = Vector(effector_force) + point = points[effector] + if point is not None: + effector_moment = Vector(effector_moment) + (point ^ effector_force) + force = force + effector_force + moment = moment + Vector(effector_moment) + return force, moment + + +def _surface_forces( # pylint: disable=too-many-arguments + flight, t, z, K, Kt, velocity_in_body_frame, w, controls, R1, R2, R3, M1, M2, M3 +): + """Add the forces and moments of the rocket's active aerodynamic surfaces + to the sums given, in the body frame, and return them. + + Each surface meets the air at its own point: the air at its altitude, + moving relative to it as the rocket translates and rotates. Its controls, + if it has any, are read from ``controls`` by name. + + Parameters + ---------- + flight : Flight + Flight object providing the rocket and the environment. + t : float + Time in seconds, for which surfaces are active. + z : float + Altitude of the rocket's center of dry mass, in m. + K : Matrix + Rotation from the body frame to the Earth frame. + Kt : Matrix + Its transpose. + velocity_in_body_frame : Vector + Velocity of the rocket in the body frame, in m/s. + w : Vector + Angular velocity of the rocket in the body frame, in rad/s. + controls : dict + The flight's control inputs, name to value. + R1, R2, R3, M1, M2, M3 : float + The sums to add to, so a caller keeps its own order of summation. + + Returns + ------- + tuple of float + ``(R1, R2, R3, M1, M2, M3)`` with the surfaces added. + """ + rocket, env = flight.rocket, flight.env + names = flight._control_names + for aero_surface, _ in rocket.aerodynamic_surfaces: + if not aero_surface.is_active(t, flight): + continue + # Component cp relative to CDM in body frame + comp_cp = rocket.surfaces_cp_to_cdm[aero_surface] + # Component absolute velocity in body frame + comp_vb = velocity_in_body_frame + (w ^ comp_cp) + # Air at the component's altitude + comp_z = z + (K @ comp_cp).z + comp_wind_vx = env.wind_velocity_x.get_value_opt(comp_z) + comp_wind_vy = env.wind_velocity_y.get_value_opt(comp_z) + # Component freestream velocity in body frame + comp_wind_vb = Kt @ Vector([comp_wind_vx, comp_wind_vy, 0]) + comp_stream_velocity = comp_wind_vb - comp_vb + comp_stream_speed = abs(comp_stream_velocity) + comp_rho = env.density.get_value_opt(comp_z) + comp_speed_of_sound = env.speed_of_sound.get_value_opt(comp_z) + comp_stream_mach = comp_stream_speed / comp_speed_of_sound + # Forces and moments + X, Y, Z, M, N, L = aero_surface.compute_forces_and_moments( + comp_stream_velocity, + comp_stream_speed, + comp_stream_mach, + comp_rho, + comp_cp, + w, + env.density, + env.dynamic_viscosity, + comp_z, + [controls[name] for name in names.get(aero_surface, ())], + ) + R1 += X + R2 += Y + R3 += Z + M1 += M + M2 += N + M3 += L + return R1, R2, R3, M1, M2, M3 + + +def udot_rail1(flight, t, u, controls, *, post_processing=False, conditions=None): """Compute the 1-DOF rail-flight state derivative. The rail model advances translation along the launch rail while keeping the @@ -116,16 +227,24 @@ def udot_rail1(flight, t, u, post_processing=False): Time in seconds. u : list State vector ``[x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3]``. + controls : dict + The flight's control inputs, name to value. During the flight + it is the live dictionary; when a stored row is worked out again, the + copy stored with that row. post_processing : bool, optional If ``True``, return this phase's post-process variables instead of the state derivative. Default is ``False``. + conditions : FlightConditions, optional + The flight at this moment, handed on to the rocket's effectors. The + equations do not read it themselves. ``None`` for a rocket without + effectors, continuous laws or parts with states. Returns ------- - list or dict + list State derivative ``[vx, vy, vz, ax, ay, az, e0dot, e1dot, e2dot, e3dot, alpha1, alpha2, alpha3]``. With ``post_processing``, this phase's - post-process variables as a variable name to value map. + post-process variables in its declared order. """ # Retrieve integration data _, _, z, vx, vy, vz, e0, e1, e2, e3, _, _, _ = u @@ -145,9 +264,9 @@ def udot_rail1(flight, t, u, post_processing=False): free_stream_speed = abs(free_stream_velocity) free_stream_mach = free_stream_speed / flight.env.speed_of_sound.get_value_opt(z) rho = flight.env.density.get_value_opt(z) - stream_velocity_body = ( - Matrix.transformation([e0, e1, e2, e3]).transpose @ free_stream_velocity - ) + K = Matrix.transformation([e0, e1, e2, e3]) + Kt = K.transpose + stream_velocity_body = Kt @ free_stream_velocity dynamic_viscosity = flight.env.dynamic_viscosity.get_value_opt(z) drag_area = _compute_drag_area( flight, @@ -168,6 +287,28 @@ def udot_rail1(flight, t, u, post_processing=False): 0, ) R3 = 0.5 * rho * free_stream_speed * stream_velocity_body[2] * drag_area + # On the rail the rocket can only slide along it: only the parts of the + # forces along its axis move it, so of the surfaces' forces only the + # axial one is kept (the drag of air brakes, of a generic surface given + # a cA). The rocket does not turn on the rail. + _, _, R3, _, _, _ = _surface_forces( + flight, + t, + z, + K, + Kt, + Kt @ Vector([vx, vy, vz]), + Vector([0, 0, 0]), + controls, + 0.0, + 0.0, + R3, + 0.0, + 0.0, + 0.0, + ) + net_thrust = _effector_thrust(flight, conditions, net_thrust, controls)[0].z + R3 += _effector_force_and_moment(flight, conditions, controls)[0].z # Calculate Linear acceleration a3 = (R3 + net_thrust) / total_mass_at_t - ( @@ -181,14 +322,22 @@ def udot_rail1(flight, t, u, post_processing=False): ax, ay, az = 0, 0, 0 if post_processing: - values = list(flight.u_dot_generalized.post_process_at(t, u)) + # The forces and moments the free-flight equations report, with the + # rail's own accelerations + values = list( + flight.u_dot_generalized.base_derivative( + t, u, controls, post_processing=True, conditions=conditions + ) + ) values[:6] = [ax, ay, az, 0.0, 0.0, 0.0] return values return [vx, vy, vz, ax, ay, az, 0, 0, 0, 0, 0, 0, 0] -def udot_rail2(flight, t, u, post_processing=False): # pragma: no cover +def udot_rail2( # pragma: no cover + flight, t, u, controls, *, post_processing=False, conditions=None +): """Compute the rail-flight derivative through the generalized solver. This function is a placeholder for a dedicated 3DOF rail model. The current @@ -202,22 +351,30 @@ def udot_rail2(flight, t, u, post_processing=False): # pragma: no cover Time in seconds. u : list State vector ``[x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3]``. + controls : dict + The flight's control inputs, name to value. During the flight + it is the live dictionary; when a stored row is worked out again, the + copy stored with that row. post_processing : bool, optional If ``True``, return this phase's post-process variables instead of the state derivative. Default is ``False``. + conditions : FlightConditions, optional + The flight at this moment, handed on to the rocket's effectors. The + equations do not read it themselves. ``None`` for a rocket without + effectors, continuous laws or parts with states. Returns ------- - list or dict + list Whatever :func:`u_dot_generalized` returns for the same arguments. """ # Hey! We will finish this function later, now we just can use u_dot - if post_processing: - return flight.u_dot_generalized.post_process_at(t, u) - return flight.u_dot_generalized(t, u) + return flight.u_dot_generalized.base_derivative( + t, u, controls, post_processing=post_processing, conditions=conditions + ) -def u_dot(flight, t, u, post_processing=False): +def u_dot(flight, t, u, controls, *, post_processing=False, conditions=None): """Compute the simplified 6DOF free-flight derivative. This solver is used for powered ascent and coasting descent without parachutes. @@ -232,9 +389,17 @@ def u_dot(flight, t, u, post_processing=False): Time in seconds. u : list State vector ``[x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3]``. + controls : dict + The flight's control inputs, name to value. During the flight + it is the live dictionary; when a stored row is worked out again, the + copy stored with that row. post_processing : bool, optional If ``True``, return this phase's post-process variables instead of the state derivative. Default is ``False``. + conditions : FlightConditions, optional + The flight at this moment, handed on to the rocket's effectors. The + equations do not read it themselves. ``None`` for a rocket without + effectors, continuous laws or parts with states. Returns ------- @@ -250,28 +415,25 @@ def u_dot(flight, t, u, post_processing=False): R1, R2, M1, M2, M3 = 0, 0, 0, 0, 0 # Thrust correction parameters pressure = flight.env.pressure.get_value_opt(z) + motor = flight.rocket.motor # Determine current behavior - if flight.rocket.motor.burn_start_time < t < flight.rocket.motor.burn_out_time: + if motor.burn_start_time < t < motor.burn_out_time: # Motor burning # Retrieve important motor quantities # Inertias - motor_I_33_at_t = flight.rocket.motor.I_33.get_value_opt(t) - motor_I_11_at_t = flight.rocket.motor.I_11.get_value_opt(t) - motor_I_33_derivative_at_t = flight.rocket.motor.I_33.differentiate(t, dx=1e-6) - motor_I_11_derivative_at_t = flight.rocket.motor.I_11.differentiate(t, dx=1e-6) + motor_I_33_at_t = motor.I_33.get_value_opt(t) + motor_I_11_at_t = motor.I_11.get_value_opt(t) + motor_I_33_derivative_at_t = motor.I_33.differentiate(t, dx=1e-6) + motor_I_11_derivative_at_t = motor.I_11.differentiate(t, dx=1e-6) # Mass - mass_flow_rate_at_t = flight.rocket.motor.mass_flow_rate.get_value_opt(t) - propellant_mass_at_t = flight.rocket.motor.propellant_mass.get_value_opt(t) + mass_flow_rate_at_t = motor.mass_flow_rate.get_value_opt(t) + propellant_mass_at_t = motor.propellant_mass.get_value_opt(t) # Thrust net_thrust = max( - flight.rocket.motor.thrust.get_value_opt(t) - + flight.rocket.motor.pressure_thrust(pressure), + motor.thrust.get_value_opt(t) + motor.pressure_thrust(pressure), 0, ) - # Off center moment - M1 += flight.rocket.thrust_eccentricity_y * net_thrust - M2 -= flight.rocket.thrust_eccentricity_x * net_thrust else: # Motor stopped # Inertias @@ -286,6 +448,20 @@ def u_dot(flight, t, u, post_processing=False): # thrust net_thrust = 0 + # Forces besides the aerodynamic ones and the axial thrust: the sideways + # thrust of thrust effectors and the force effectors + extra_x, extra_y = 0.0, 0.0 + if net_thrust != 0 or flight.rocket._thrust_effectors: + # The jet damping below takes the exhaust along the axis, so a nozzle + # off the axis changes only the thrust's moment here + thrust_force, thrust_moment, _ = _effector_thrust( + flight, conditions, net_thrust, controls + ) + extra_x, extra_y, net_thrust = thrust_force + M1 += thrust_moment.x + M2 += thrust_moment.y + M3 += thrust_moment.z + # Retrieve important quantities # Inertias rocket_dry_I_33 = flight.rocket.dry_I_33 @@ -358,40 +534,9 @@ def u_dot(flight, t, u, post_processing=False): # Calculate lift and moment for each component of the rocket velocity_in_body_frame = Vector([vx_b, vy_b, vz_b]) w = Vector([omega1, omega2, omega3]) - for aero_surface, _ in flight.rocket.aerodynamic_surfaces: - if not aero_surface.is_active(t, flight): - continue - # Component cp relative to CDM in body frame - comp_cp = flight.rocket.surfaces_cp_to_cdm[aero_surface] - # Component absolute velocity in body frame - comp_vb = velocity_in_body_frame + (w ^ comp_cp) - # Wind velocity at component altitude - comp_z = z + (K @ comp_cp).z - comp_wind_vx = flight.env.wind_velocity_x.get_value_opt(comp_z) - comp_wind_vy = flight.env.wind_velocity_y.get_value_opt(comp_z) - # Component freestream velocity in body frame - comp_wind_vb = Kt @ Vector([comp_wind_vx, comp_wind_vy, 0]) - comp_stream_velocity = comp_wind_vb - comp_vb - comp_stream_speed = abs(comp_stream_velocity) - comp_stream_mach = comp_stream_speed / speed_of_sound - # Forces and moments - X, Y, Z, M, N, L = aero_surface.compute_forces_and_moments( - comp_stream_velocity, - comp_stream_speed, - comp_stream_mach, - rho, - comp_cp, - w, - flight.env.density, - flight.env.dynamic_viscosity, - comp_z, - ) - R1 += X - R2 += Y - R3 += Z - M1 += M - M2 += N - M3 += L + R1, R2, R3, M1, M2, M3 = _surface_forces( + flight, t, z, K, Kt, velocity_in_body_frame, w, controls, R1, R2, R3, M1, M2, M3 + ) # Off center moment M3 += flight.rocket.cp_eccentricity_x * R2 - flight.rocket.cp_eccentricity_y * R1 @@ -402,8 +547,15 @@ def u_dot(flight, t, u, post_processing=False): # The reported M1, M2 stay about the center of dry mass, as in the # generalized equations. a = b * mu / rocket_dry_mass # = b * m_prop / m_total - M1_cm = M1 - a * R2 - M2_cm = M2 + a * R1 + effector_force, effector_moment = _effector_force_and_moment( + flight, conditions, controls + ) + extra_x += effector_force.x + extra_y += effector_force.y + extra_z = effector_force.z + M1_cm = M1 + effector_moment.x - a * (R2 + extra_y) + M2_cm = M2 + effector_moment.y + a * (R1 + extra_x) + M3_total = M3 + effector_moment.z # Calculate derivatives # Angular acceleration @@ -458,7 +610,7 @@ def u_dot(flight, t, u, post_processing=False): ) ) / (rocket_dry_I_11 + motor_I_11_at_t + mu * b**2) alpha3 = ( - M3 + M3_total - omega3 * (motor_I_33_derivative_at_t - mass_flow_rate_at_t * (nozzle_radius**2) / 2) ) / (rocket_dry_I_33 + motor_I_33_at_t) @@ -471,17 +623,24 @@ def u_dot(flight, t, u, post_processing=False): L = [ ( R1 + + extra_x - b * propellant_mass_at_t * (omega2**2 + omega3**2) - 2 * c * mass_flow_rate_at_t * omega2 ) / total_mass_at_t, ( R2 + + extra_y + b * propellant_mass_at_t * (alpha3 + omega1 * omega2) + 2 * c * mass_flow_rate_at_t * omega1 ) / total_mass_at_t, - (R3 - b * propellant_mass_at_t * (alpha2 - omega1 * omega3) + net_thrust) + ( + R3 + + extra_z + - b * propellant_mass_at_t * (alpha2 - omega1 * omega3) + + net_thrust + ) / total_mass_at_t, ] ax, ay, az = K @ Vector(L) @@ -529,7 +688,9 @@ def u_dot(flight, t, u, post_processing=False): return u_dot -def u_dot_generalized_3dof(flight, t, u, post_processing=False): +def u_dot_generalized_3dof( + flight, t, u, controls, *, post_processing=False, conditions=None +): """Compute the 3DOF free-flight derivative with weathercocking. The model advances translational motion with variable mass while using a kinematic @@ -544,9 +705,17 @@ def u_dot_generalized_3dof(flight, t, u, post_processing=False): Time in seconds. u : list State vector ``[x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3]``. + controls : dict + The flight's control inputs, name to value. During the flight + it is the live dictionary; when a stored row is worked out again, the + copy stored with that row. post_processing : bool, optional If ``True``, return this phase's post-process variables instead of the state derivative. Default is ``False``. + conditions : FlightConditions, optional + The flight at this moment, handed on to the rocket's effectors. The + equations do not read it themselves. ``None`` for a rocket without + effectors, continuous laws or parts with states. Returns ------- @@ -560,12 +729,11 @@ def u_dot_generalized_3dof(flight, t, u, post_processing=False): # Define vectors v = Vector([vx, vy, vz]) - e = [e0, e1, e2, e3] w = Vector([omega1, omega2, omega3]) # Mass and transformation total_mass = flight.rocket.total_mass.get_value_opt(t) - K = Matrix.transformation(e) + K = Matrix.transformation([e0, e1, e2, e3]) Kt = K.transpose # Atmospheric and wind data @@ -581,7 +749,7 @@ def u_dot_generalized_3dof(flight, t, u, post_processing=False): stream_velocity_body = Kt @ free_stream_velocity dynamic_viscosity = flight.env.dynamic_viscosity.get_value_opt(z) - # Drag (rocket body drag + air brakes). A 3-DOF phase does not model the + # Drag of the rocket body. A 3-DOF phase does not model the # rocket's attitude, so the drag acts against the velocity of the rocket # relative to the air instead of along the body axis. drag_area = _compute_drag_area( @@ -596,38 +764,10 @@ def u_dot_generalized_3dof(flight, t, u, post_processing=False): ) R1, R2, R3 = stream_velocity_body * (0.5 * rho * free_stream_speed * drag_area) - # Velocity in body frame - vb_body = Kt @ v - - for surface, _ in flight.rocket.aerodynamic_surfaces: - if not surface.is_active(t, flight): - continue - cp = flight.rocket.surfaces_cp_to_cdm[surface] - vb_component = vb_body + (w ^ cp) - - comp_z = z + (K @ cp).z - wind_cx = flight.env.wind_velocity_x.get_value_opt(comp_z) - wind_cy = flight.env.wind_velocity_y.get_value_opt(comp_z) - wind_body = Kt @ Vector([wind_cx, wind_cy, 0]) - - rel_velocity = wind_body - vb_component - rel_speed = abs(rel_velocity) - rel_mach = rel_speed / speed_of_sound - - fx, fy, fz, *_ = surface.compute_forces_and_moments( - rel_velocity, - rel_speed, - rel_mach, - rho, - cp, - w, - flight.env.density, - flight.env.dynamic_viscosity, - comp_z, - ) - R1 += fx - R2 += fy - R3 += fz + # The surfaces' forces; a 3-DOF phase models no moments + R1, R2, R3, _, _, _ = _surface_forces( + flight, t, z, K, Kt, Kt @ v, w, controls, R1, R2, R3, 0.0, 0.0, 0.0 + ) # Thrust and weight # Calculate net thrust including pressure thrust correction if motor is burning @@ -643,7 +783,16 @@ def u_dot_generalized_3dof(flight, t, u, post_processing=False): gravity = flight.env.gravity.get_value_opt(z) weight_body = Kt @ Vector([0, 0, -total_mass * gravity]) - total_force = Vector([0, 0, net_thrust]) + weight_body + Vector([R1, R2, R3]) + # A 3-DOF phase takes the forces of the thrust and of the force + # effectors, not their moments + thrust_force, _, _ = _effector_thrust(flight, conditions, net_thrust, controls) + net_thrust = thrust_force.z + total_force = ( + thrust_force + + weight_body + + Vector([R1, R2, R3]) + + _effector_force_and_moment(flight, conditions, controls)[0] + ) # Dynamics v_dot = K @ (total_force / total_mass) @@ -738,12 +887,14 @@ def u_dot_generalized_3dof(flight, t, u, post_processing=False): return u_dot -def u_dot_generalized(flight, t, u, post_processing=False): +def u_dot_generalized( + flight, t, u, controls, *, post_processing=False, conditions=None +): """Compute the full 6DOF generalized flight derivative. - This is the highest-fidelity rigid-body flight solver in this module. It accounts - for variable mass, changing inertia, aerodynamic surface loads, thrust eccentricity, - and Earth-rotation effects. + This is the highest-fidelity rigid-body flight solver in this module. It + accounts for variable mass, changing inertia, aerodynamic surface loads, + thrust eccentricity, and Earth-rotation effects. Parameters ---------- @@ -753,9 +904,17 @@ def u_dot_generalized(flight, t, u, post_processing=False): Time in seconds. u : list State vector ``[x, y, z, vx, vy, vz, e0, e1, e2, e3, omega1, omega2, omega3]``. + controls : dict + The flight's control inputs, name to value. During the flight + it is the live dictionary; when a stored row is worked out again, the + copy stored with that row. post_processing : bool, optional If ``True``, return this phase's post-process variables instead of the state derivative. Default is ``False``. + conditions : FlightConditions, optional + The flight at this moment, handed on to the rocket's effectors. The + equations do not read it themselves. ``None`` for a rocket without + effectors, continuous laws or parts with states. Returns ------- @@ -770,7 +929,6 @@ def u_dot_generalized(flight, t, u, post_processing=False): # Create necessary vectors # r = Vector([x, y, z]) # CDM position vector v = Vector([vx, vy, vz]) # CDM velocity vector - e = [e0, e1, e2, e3] # Euler parameters/quaternions w = Vector([omega1, omega2, omega3]) # Angular velocity vector # Retrieve necessary quantities @@ -789,11 +947,6 @@ def u_dot_generalized(flight, t, u, post_processing=False): r_CM = Vector([0, 0, r_CM_t]) r_CM_dot = Vector([0, 0, -r_CM_z.differentiate_complex_step(t)]) r_CM_ddot = Vector([0, 0, -r_CM_z.differentiate(t, order=2)]) - ## Nozzle exit position vector relative to CDM in body frame - ## (``nozzle_to_cdm`` runs from the nozzle exit to the center of dry mass) - r_NOZ = Vector([0, 0, -flight.rocket.nozzle_to_cdm]) - ## Nozzle gyration tensor - S_nozzle = flight.rocket.nozzle_gyration_tensor ## Inertia tensor inertia_tensor = flight.rocket.get_inertia_tensor_at_time(t) ## Inertia tensor time derivative in the body frame @@ -804,7 +957,7 @@ def u_dot_generalized(flight, t, u, post_processing=False): I_CM = inertia_tensor - H # Prepare transformation matrices - K = Matrix.transformation(e) + K = Matrix.transformation([e0, e1, e2, e3]) Kt = K.transpose # Compute aerodynamic forces and moments @@ -844,53 +997,31 @@ def u_dot_generalized(flight, t, u, post_processing=False): # The drag curve is the axial force coefficient, so the drag follows the # air moving along the rocket's axis: zero sideways, reversed tail first R3 = 0.5 * rho * free_stream_speed * stream_velocity_body[2] * drag_area - # Get rocket velocity in body frame - velocity_in_body_frame = Kt @ v # Calculate lift and moment for each component of the rocket - for aero_surface, _ in flight.rocket.aerodynamic_surfaces: - if not aero_surface.is_active(t, flight): - continue - # Component cp relative to CDM in body frame - comp_cp = flight.rocket.surfaces_cp_to_cdm[aero_surface] - # Component absolute velocity in body frame - comp_vb = velocity_in_body_frame + (w ^ comp_cp) - # Wind velocity at component altitude - comp_z = z + (K @ comp_cp).z - comp_wind_vx = flight.env.wind_velocity_x.get_value_opt(comp_z) - comp_wind_vy = flight.env.wind_velocity_y.get_value_opt(comp_z) - # Component freestream velocity in body frame - comp_wind_vb = Kt @ Vector([comp_wind_vx, comp_wind_vy, 0]) - comp_stream_velocity = comp_wind_vb - comp_vb - comp_stream_speed = abs(comp_stream_velocity) - comp_stream_mach = comp_stream_speed / speed_of_sound - # Forces and moments - X, Y, Z, M, N, L = aero_surface.compute_forces_and_moments( - comp_stream_velocity, - comp_stream_speed, - comp_stream_mach, - rho, - comp_cp, - w, - flight.env.density, - flight.env.dynamic_viscosity, - comp_z, - ) - R1 += X - R2 += Y - R3 += Z - M1 += M - M2 += N - M3 += L - - # Off center moment - M1 += ( - flight.rocket.cp_eccentricity_y * R3 - + flight.rocket.thrust_eccentricity_y * net_thrust + R1, R2, R3, M1, M2, M3 = _surface_forces( + flight, t, z, K, Kt, Kt @ v, w, controls, R1, R2, R3, M1, M2, M3 ) - M2 -= ( - flight.rocket.cp_eccentricity_x * R3 - + flight.rocket.thrust_eccentricity_x * net_thrust + + # Off center moment. The exhaust leaves at the nozzle exit (``r_NOZ``, + # from the center of dry mass, in the body frame), which the mass flow + # terms (jet damping) below read + thrust_force, thrust_moment, r_NOZ = _effector_thrust( + flight, conditions, net_thrust, controls ) + net_thrust = thrust_force.z + ## Nozzle gyration tensor: the rocket's, moved with the nozzle exit when a + ## thrust effector moved it + S_nozzle = flight.rocket.nozzle_gyration_tensor + nozzle_exit = flight.rocket.nozzle_exit + if r_NOZ is not nozzle_exit: + S_nozzle = ( + S_nozzle + + (r_NOZ.cross_matrix @ -r_NOZ.cross_matrix) + - (nozzle_exit.cross_matrix @ -nozzle_exit.cross_matrix) + ) + M1 += flight.rocket.cp_eccentricity_y * R3 + thrust_moment.x + M2 += thrust_moment.y - flight.rocket.cp_eccentricity_x * R3 + M3 += thrust_moment.z M3 += flight.rocket.cp_eccentricity_x * R2 - flight.rocket.cp_eccentricity_y * R1 weight_in_body_frame = Kt @ Vector( @@ -900,7 +1031,7 @@ def u_dot_generalized(flight, t, u, post_processing=False): T00 = total_mass * r_CM T03 = 2 * total_mass_dot * (r_NOZ - r_CM) - 2 * total_mass * r_CM_dot T04 = ( - Vector([0, 0, net_thrust]) + thrust_force - total_mass * r_CM_ddot - 2 * total_mass_dot * r_CM_dot + total_mass_ddot * (r_NOZ - r_CM) @@ -917,6 +1048,11 @@ def u_dot_generalized(flight, t, u, post_processing=False): - (weight_in_body_frame ^ r_CM) + Vector([M1, M2, M3]) ) + effector_force, effector_moment = _effector_force_and_moment( + flight, conditions, controls + ) + T20 = T20 + effector_force + T21 = T21 + effector_moment # Angular velocity derivative w_dot = I_CM.inverse @ (T21 + (T20 ^ r_CM)) @@ -948,7 +1084,7 @@ def u_dot_generalized(flight, t, u, post_processing=False): return u_dot -def u_dot_parachute(flight, t, u, post_processing=False, *, parachute): # pylint: disable=unused-argument +def u_dot_parachute(flight, t, u, controls, *, post_processing=False, parachute): # pylint: disable=unused-argument """Compute the parachute descent derivative. Only position and velocity actually move under a parachute. The attitude and @@ -966,6 +1102,8 @@ def u_dot_parachute(flight, t, u, post_processing=False, *, parachute): # pylin State vector ``[x, y, z, vx, vy, vz, e0, e1, e2, e3, w1, w2, w3]``. Only the position and velocity are read; the attitude and angular rates come along unchanged. + controls : dict + The flight's control inputs. A parachute descent reads none of them. post_processing : bool, optional If ``True``, return this phase's post-process variables instead of the state derivative. Default is ``False``. diff --git a/rocketpy/simulation/helpers/flight_phase.py b/rocketpy/simulation/helpers/flight_phase.py index 78b92d172..31ca90fe3 100644 --- a/rocketpy/simulation/helpers/flight_phase.py +++ b/rocketpy/simulation/helpers/flight_phase.py @@ -483,7 +483,7 @@ def add_discrete_events(self, events, t_init, t_end): # `enable_on` cannot become enabled again and are therefore # skipped here to avoid scheduling unnecessary checks. if ( - not event.enabled and event.enable_on is None + not event._enabled and event.enable_on is None ) or event.sampling_rate is None: continue @@ -514,7 +514,7 @@ def add_event(self, event, t_init, t_end): """ # Register the event only when it's present and either enabled or # able to re-enable itself via `enable_on`. - if not event.enabled and event.enable_on is None: + if not event._enabled and event.enable_on is None: return if event.sampling_rate is None: diff --git a/rocketpy/simulation/events/state.py b/rocketpy/simulation/helpers/state.py similarity index 95% rename from rocketpy/simulation/events/state.py rename to rocketpy/simulation/helpers/state.py index ffe1f930e..1974dd4fc 100644 --- a/rocketpy/simulation/events/state.py +++ b/rocketpy/simulation/helpers/state.py @@ -1,6 +1,27 @@ +"""The rocket's state read by name: ``context.state`` in an event and +``conditions.state`` in a controller or an effector, and the names of the 13 +standard states every flight phase reports.""" + import numpy as np -from ..helpers.dynamics import CANONICAL_INDEX +# The 13 states of RocketPy's full flight state, in order. +CANONICAL_STATE_NAMES = ( + "x", + "y", + "z", + "vx", + "vy", + "vz", + "e0", + "e1", + "e2", + "e3", + "w1", + "w2", + "w3", +) +# Each canonical state's position in that order. +CANONICAL_INDEX = {name: index for index, name in enumerate(CANONICAL_STATE_NAMES)} class _StateView: diff --git a/rocketpy/simulation/solution.py b/rocketpy/simulation/solution.py index d9a8b66ed..d3c66b028 100644 --- a/rocketpy/simulation/solution.py +++ b/rocketpy/simulation/solution.py @@ -2,6 +2,7 @@ import numpy as np +from ..tools import snake_case_key from .helpers.dynamics import ( BUILT_IN_DYNAMICS, CANONICAL_INDEX, @@ -17,9 +18,6 @@ "Solution", ] -# Time plus the 13 canonical states: the width of every canonical row. -CANONICAL_WIDTH = len(CANONICAL_STATE_NAMES) + 1 - def _nearest_time_index(times, t, atol, where): """Return the position of the stored time closest to ``t``. @@ -52,6 +50,51 @@ def _nearest_time_index(times, t, atol, where): return index +class _ResultsDict(dict): + """A dictionary of results by name, also read as attributes in snake_case. + + ``results["Canards"]["deflection"]`` is the value as a plain dictionary + gives it; ``results.canards.deflection`` is the same value, by each name + in snake_case, and so is ``results["canards"]``: a name is found by its + snake_case form when it is not there as given. Everything else is the + dictionary: ``list(results)`` gives the names as given, ``results.items()`` + the pairs. + + A name that is also a method of a dictionary (``items``, ``keys``, + ``values``, ``get``, ``copy``, ``update``, ``pop``, ``clear``) is read with + brackets only: ``results["values"]``, since ``results.values`` is the + method. + """ + + def __init__(self, data): + # A value that is a dictionary is a group of its own + super().__init__( + (name, _ResultsDict(value) if isinstance(value, dict) else value) + for name, value in data.items() + ) + + def __missing__(self, key): + wanted = snake_case_key(key) + for name in self: + if snake_case_key(name) == wanted: + return self[name] + raise KeyError( + f"Nothing here is named {key!r}. The names are: " + f"{', '.join(self) or 'none'}." + ) + + def __getattr__(self, key): + if key.startswith("_"): + raise AttributeError(key) + try: + return self[key] + except KeyError as error: + raise AttributeError(error.args[0]) from None + + def __dir__(self): + return [*super().__dir__(), *(snake_case_key(name) for name in self)] + + class _PhaseSolution: """One phase of a flight: what it was flown with, and where it starts. @@ -260,7 +303,19 @@ def from_dict(cls, data): # The dynamics is code, so it was saved by name. A built-in one is # used again, so the canonical states it rebuilds are rebuilt here too. dynamics = BUILT_IN_DYNAMICS.get(data.get("dynamics")) - if dynamics is None or list(dynamics.states) != data["state_names"]: + names = list(data["state_names"]) + if dynamics is not None and names[: dynamics.width] == list(dynamics.states): + if len(names) > dynamics.width: + # Flown with the states of the rocket's controllables after its own + dynamics = _PhaseDynamics( + dynamics.name, + None, + names, + dynamics.post_process_vars, + dynamics.to_canonical, + dynamics.to_canonical_dot, + ) + else: # Unknown, or changed since the flight was saved: its own states # can still be read by name, and every other canonical state is # held at its start-of-phase value. @@ -277,18 +332,21 @@ def from_dict(cls, data): class Solution: - """The state history of a whole flight. - - A ``Solution`` answers queries by state name. ``solution["vz"]`` returns the - ``[t, value]`` history of the vertical velocity across the whole flight; - ``solution.at(t)`` returns the whole state at the nearest stored time as a - name-to-value dictionary. ``solution.phases`` gives the individual flight - phases, each a :class:`_PhaseSolution`; :meth:`phase_span` says which rows - belong to one, so ``solution[start:stop]`` reads them. - - The variables the flight computed without integrating them, such as the - accelerations and the aerodynamic forces, are read through - ``solution.post``: see :class:`PostProcessSolution`. + """Everything a flight produced over time, as raw numbers. + + A ``Solution`` answers queries by name. ``solution.vz`` or + ``solution["vz"]`` is the ``[t, value]`` history of the vertical velocity + across the whole flight; so are ``solution.ax`` for a variable the flight + worked out without integrating it (accelerations, forces, moments, thrust) + and ``solution.controls.canards.deflection`` for a control input. + :attr:`names` lists them all; ``solution.at(t)`` returns every one of them + at the nearest stored time as a name-to-value dictionary. + ``solution.sensors.barometer.pressure`` is what a sensor read, at its own + sampling times. + + ``solution.phases`` gives the individual flight phases, each a + :class:`_PhaseSolution`; :meth:`phase_span` says which rows belong to one, + so ``solution[start:stop]`` reads them. It also reads like a plain list of rows: ``len(solution)``, iteration, ``solution[-1]``, slicing and ``numpy.array(solution)`` all give 14-value @@ -322,28 +380,31 @@ def __init__(self, phases=None, rows=None): # The flight's phases, in the order they were flown. self.phases = list(phases) if phases else [] self._rows = list(rows) if rows else [] - # Post-process values, one entry per row and in the same order, so a row - # and its values can never drift apart. They carry no time of their own: - # the row they sit beside supplies it. ``None`` where nothing was - # recorded. Not saved to file: a solution read back has no live flight - # to post-process against. - self._post_values = [None] * len(self._rows) - # Set by a flight that records its post-process values as it runs. Such - # a flight changes the rocket mid-flight, so working the values out - # again afterwards would read the rocket in the configuration it ended - # in. Once this is on, recorded values are the only acceptable answer. - self.records_post_values = False - self.post = PostProcessSolution(self) + # The control inputs in force from each row's time on (a dictionary of + # name to value), one entry per row, kept beside the rows the + # same way. A row worked out again after the flight is given its own. + # ``None`` where nothing was stored. Saved with the rows. + self._controls = [None] * len(self._rows) + # What the sensors read, at their own sampling times: sensor position + # name to channel name to ``[(time, reading), ...]``. Saved with the + # rows, and cut with them when the flight goes back in time. + self._sensors = {} # Bumped by every change to the rows. The canonical table and the # histories of non-canonical states are cached against it. self._version = 0 - # Bumped whenever a recorded post-process value changes, so - # ``post`` can tell its own answers are stale without the row caches - # having to be thrown away too. + # Bumped whenever a row's control inputs change, so the post-process + # values and the control histories can tell they are stale without + # the row caches having to be thrown away too. self._post_version = 0 self._canonical_cache = None self._canonical_version = -1 self._series_cache = {} + self._control_cache = {} + self._control_names_cache = (None, ()) + # The post-process values of every phase, worked out on the first read + # and kept until the rows or their control inputs change + self._post_tables = None + self._post_key = None self._validate_starts() def __repr__(self): @@ -446,16 +507,6 @@ def _start_phase(self, dynamics, start_canonical, t_start=None, name=None): # -- Row access -------------------------------------------------------- - def _last_row_phase(self): - """Return the phase owning the most recent row. - - A phase that has only just begun holds no rows, so this skips it and - gives the phase before it. Raises ``IndexError`` if there are no rows. - """ - if not self._rows: - raise IndexError("this solution has no stored rows") - return self._phase_at(len(self._rows) - 1) - def _normalize(self, index): """Return ``index`` counted from the start, checking it is in range. @@ -630,47 +681,6 @@ def canonical_row(self, index): return list(row) return [row[0], *phase.canonical_state(row[1:])] - # -- Per-phase reads --------------------------------------------------- - - def _phase_series_or_none(self, phase, start, stop, name): - """Return a phase's ``[t, value]`` history, or ``None`` if undefined. - - Lets :meth:`series` skip the phases that do not define a state while - gathering its history across the whole flight. - - Parameters - ---------- - phase : _PhaseSolution - The phase to read. - start, stop : int - The phase's rows in the flight's row list, as a slice would bound - them. - name : str - The state name (for example ``"vz"``). - - Returns - ------- - numpy.ndarray or None - An ``(n, 2)`` array whose columns are time and value, or ``None`` - if the phase cannot report the state or holds no rows. - """ - if start == stop: - return None - rows = self._rows[start:stop] - times = np.array([row[0] for row in rows]) - # A state the phase integrates is a plain column of its rows; any other - # canonical state comes from the phase's canonical view. - index = phase.dynamics.state_index.get(name) - if index is not None: - return np.column_stack([times, [row[index + 1] for row in rows]]) - slot = CANONICAL_INDEX.get(name) - if slot is None: - return None - canonical_state = phase.canonical_state - return np.column_stack( - [times, [canonical_state(row[1:])[slot] for row in rows]] - ) - # -- Mutation ---------------------------------------------------------- def _shift_starts_after(self, position, delta): @@ -700,42 +710,30 @@ def _append(self, row): ---------- row : sequence of float Time followed by the states the current phase integrates, in the - order that phase integrates them. - - Raises - ------ - IndexError - If no phase has been started yet. + order that phase integrates them. A phase must have been started + first (see :meth:`_start_phase`): this is not checked. """ self._rows.append(row) - self._post_values.append(None) + self._controls.append(None) self._version += 1 - def _set_post_values(self, index, values): - """Record the post-process values of one row. - - Called as the simulation runs, right after the row is written, so the - values are the ones the rocket really had at that state. They are kept - beside the row and move with it, so a rollback cannot leave the two out - of step. + def _set_controls(self, index, controls): + """Store the control inputs in force from one row's time on. Parameters ---------- index : int Row position across the whole flight. Negative values count from the end. - values : sequence of float - The values in that row's phase ``post_process_vars`` order. + controls : dict + Name to value, a copy of the flight's control inputs. Raises ------ IndexError If ``index`` is outside the flight's rows. """ - # Deliberately does not count as a change to the flight: the states are - # untouched, so the cached times and tables stay valid. Only ``post`` - # needs to know, and it watches its own counter. - self._post_values[self._normalize(int(index))] = values + self._controls[self._normalize(int(index))] = controls self._post_version += 1 def _replace_last(self, row): @@ -753,7 +751,7 @@ def _replace_last(self, row): If the flight has no rows yet. """ self._rows[-1] = row - self._post_values[-1] = None + self._controls[-1] = None self._version += 1 def _insert_before_last(self, row): @@ -775,7 +773,7 @@ def _insert_before_last(self, row): """ position = len(self._rows) - 1 self._rows.insert(position, row) - self._post_values.insert(position, None) + self._controls.insert(position, None) self._shift_starts_after(position, 1) self._version += 1 @@ -795,60 +793,11 @@ def _drop_last(self): if not self._rows: raise IndexError("this solution has no stored rows") row = self._rows.pop() - self._post_values.pop() + self._controls.pop() self._shift_starts_after(len(self._rows), -1) self._version += 1 return row - def _insert(self, index, row): - """Insert a raw state row before the row at ``index``. - - Parameters - ---------- - index : int - Row position across the whole flight to insert before. Negative - values count from the end. - row : sequence of float - Time followed by the states the phase at ``index`` integrates, in - the order that phase integrates them. - - Raises - ------ - IndexError - If ``index`` is outside the flight's rows. - """ - position = self._normalize(int(index)) - self._rows.insert(position, row) - self._post_values.insert(position, None) - self._shift_starts_after(position, 1) - self._version += 1 - - def _pop(self, index=-1): - """Remove and return the raw state row at ``index``. - - Parameters - ---------- - index : int, optional - Row position across the whole flight. Negative values count from - the end. Default is ``-1``, the most recent row. - - Returns - ------- - list of float - The removed row, ``[t, *state]``, as it was stored. - - Raises - ------ - IndexError - If ``index`` is outside the flight's rows. - """ - position = self._normalize(int(index)) - row = self._rows.pop(position) - self._post_values.pop(position) - self._shift_starts_after(position, -1) - self._version += 1 - return row - # -- List-like reads (canonical rows) ---------------------------------- def __len__(self): @@ -908,28 +857,6 @@ def __getitem__(self, key): f"not {type(key).__name__}." ) - def _set_row(self, index, row): - """Overwrite the row at ``index`` with a raw state row ``[t, *state]``. - - Parameters - ---------- - index : int - Row position across the whole flight. Negative values count from - the end. - row : sequence of float - Time followed by the states the phase at ``index`` integrates, in - the order that phase integrates them. - - Raises - ------ - IndexError - If ``index`` is outside the flight's rows. - """ - position = self._normalize(int(index)) - self._rows[position] = row - self._post_values[position] = None - self._version += 1 - def __array__(self, dtype=None, copy=None): # pylint: disable=unused-argument """Return the whole flight as the ``(n, 14)`` canonical table. @@ -969,21 +896,149 @@ def __array__(self, dtype=None, copy=None): # pylint: disable=unused-argument # above is the flight's cache, shared by every later read of it. return array.astype(dtype) if dtype is not None else array.copy() + @property + def time(self): + """The time column of the whole flight, in seconds, as a 1-D array.""" + return self.canonical_array[:, 0] + + @property + def canonical_array(self): + """The whole flight as a rectangular ``(n, 14)`` canonical table. + + Each row is ``[t, x, y, z, vx, vy, vz, e0, e1, e2, e3, w1, w2, w3]``. + States a phase does not integrate are rebuilt or held. + + The table belongs to the flight and cannot be written to. For a table + of your own to edit, use ``numpy.array(solution)``. + """ + if self._canonical_cache is None or self._canonical_version != self._version: + spans = list(self._spans()) + if not spans: + result = np.empty((0, len(CANONICAL_STATE_NAMES) + 1)) + elif all(phase.dynamics.is_canonical for _, phase, _, _ in spans): + # Every phase already stores the 14 canonical values, so the + # stored rows are the table. Guarded on all of them, since a + # phase storing fewer values would make the rows uneven. + result = np.array(self._rows) + else: + result = np.array(list(self)) + # Read-only so that a caller writing to the table it was handed + # is told, rather than silently rewriting every later read of it. + result.flags.writeable = False + self._canonical_cache = result + self._canonical_version = self._version + return self._canonical_cache + # -- Queries by name --------------------------------------------------- + @property + def names(self): + """Every quantity this flight holds per row, by name. + + The 13 canonical states first, then the states only some phases + integrate (a controllable's own states, for example), then the + post-process variables (accelerations, forces, moments, thrust) and + the control inputs. Each is read as ``solution.`` or + ``solution[""]``. + + Returns + ------- + tuple of str + """ + names = list(CANONICAL_STATE_NAMES) + for phase in self.phases: + for name in phase.dynamics.states: + if name not in names: + names.append(name) + for name in self.post_process_names: + if name not in names: + names.append(name) + names.extend(self.control_names) + return tuple(names) + + @property + def post_process_names(self): + """Names of every post-process variable this flight computes. + + The phases of a flight need not all compute the same variables: a + parachute descent reports no moments and no thrust. This lists every + name any phase computes, in the order the phases first introduce them. + A phase that does not compute one of them reports zero for it, which is + the physically right answer for the variables RocketPy defines. + + Returns + ------- + tuple of str + """ + names = [] + for phase in self.phases: + for name in phase.dynamics.post_process_vars: + # What a continuous controller's law wrote to each control + # input is kept with the post-process values, but it is read + # as the control input itself + if name not in names and not name.startswith("controls."): + names.append(name) + return tuple(names) + + @property + def control_names(self): + """Names of the control inputs stored with the rows, in order. + + Returns + ------- + tuple of str + """ + # Kept until the rows or their control inputs change: looking for the + # first row with controls is a pass over the rows + key = (self._version, self._post_version) + if self._control_names_cache[0] != key: + names = next( + ( + tuple(controls) + for controls in self._controls + if controls is not None + ), + (), + ) + self._control_names_cache = (key, names) + return self._control_names_cache[1] + + def __contains__(self, name): + """Return whether ``name`` is one of :attr:`names`.""" + return isinstance(name, str) and name in self.names + + def __getattr__(self, name): + """Read a quantity by name: ``solution.vz``, ``solution.ax``.""" + # Only names that are not attributes get here. Dunder and private + # names are asked for by copying and pickling before __init__ ran + if name.startswith("_"): + raise AttributeError(name) + try: + return self.series(name) + except KeyError as error: + raise AttributeError(error.args[0]) from None + + def __dir__(self): + return [*super().__dir__(), *self.names] + def series(self, name): - """Return the ``[t, value]`` history of one state over the flight. + """Return the ``[t, value]`` history of one quantity over the flight. - The history spans only the phases that define the state. A canonical + The same as ``solution[name]`` and ``solution.``. A canonical state is defined in every phase (rebuilt or held where a phase does not - integrate it), so its history covers the whole flight. A phase-specific - state's history covers only the phases that integrate it, and a warning - names the phases left out. + integrate it), so its history covers the whole flight. A state only + some phases integrate covers those phases, and a warning names the + ones left out. A post-process variable covers the phases that can be + worked out: all of them on a live flight, none on a flight read back + from a file. A control input covers every row, with the value in + force from that row's time on, or what a continuous controller's law + left at that row. Parameters ---------- name : str - The state name (for example ``"vz"``). + One of :attr:`names`, for example ``"vz"``, ``"ax"`` or + ``"canards.deflection"``. Returns ------- @@ -993,32 +1048,46 @@ def series(self, name): Raises ------ KeyError - If no phase defines the state. + If the flight has nothing by that name, or a post-process + variable cannot be worked out. Warns ----- UserWarning - If some phases do not define the state, so its history has a gap. + If some phases do not define a state, so its history has a gap. """ slot = CANONICAL_INDEX.get(name) if slot is not None: # Every phase reports the canonical states, so the history is two # columns of the canonical table. return self.canonical_array[:, [0, slot + 1]] + if name in self.control_names: + return self._control_history(name)[0] + if name in self.post_process_names: + return self._post_series(name) + return self._state_series(name) + + def _state_series(self, name): + """The history of a state only some phases integrate.""" cached = self._series_cache.get(name) if cached is not None and cached[0] == self._version: return cached[1] parts = [] missing = [] for index, phase, start, stop in self._spans(): - part = self._phase_series_or_none(phase, start, stop, name) - if part is None: + # A state the phase integrates is a column of its rows + column = phase.dynamics.state_index.get(name) + if column is None: missing.append(phase.name or f"phase {index}") - else: - parts.append(part) + continue + rows = self._rows[start:stop] + parts.append( + np.array([(row[0], row[column + 1]) for row in rows], dtype=float) + ) if not parts: raise KeyError( - f"State '{name}' is not defined in any flight phase of this solution." + f"This flight has nothing named '{name}'. It has: " + f"{', '.join(self.names)}." ) if missing: warnings.warn( @@ -1031,8 +1100,53 @@ def series(self, name): self._series_cache[name] = (self._version, result) return result + def _control_history(self, name): + """The history of one control input, and whether a continuous + controller's law wrote it. + + The history is the value in force at each row (``nan`` for a row + stored without controls) or, where a law wrote it, the value the law + left at each row. A law's value changes between the rows; a sampled + value holds until the next write.""" + key = (self._version, self._post_version) + cached = self._control_cache.get(name) + if cached is not None and cached[0] == key: + return cached[1] + values = [ + np.nan if controls is None else controls[name] + for controls in self._controls + ] + result = np.column_stack([self.time, values]) + written = self._post_series_or_none(f"controls.{name}") + by_law = written is not None and not np.array_equal(written[:, 1], result[:, 1]) + history = (written if by_law else result, by_law) + self._control_cache[name] = (key, history) + return history + + @property + def controls(self): + """The control inputs over the flight, by controllable. + + ``solution.controls.canards.deflection`` is an ``(n, 2)`` array of time + and value, one entry per row: the value in force from that row's time + on, or what a continuous controller's law left at that row. The same + array is ``solution["canards.deflection"]``; + ``flight.controls.canards.deflection`` is it as a Function of time. + + Returns + ------- + dict + Controllable to its control inputs. Empty for a flight without + controls. + """ + grouped = {} + for name in self.control_names: + owner, _, control = name.partition(".") + grouped.setdefault(owner, {})[control] = self._control_history(name)[0] + return _ResultsDict(grouped) + def at(self, t, atol=1e-3): - """Return the flight state at the stored time nearest ``t``. + """Return everything the flight knows at the stored time nearest ``t``. Parameters ---------- @@ -1045,16 +1159,19 @@ def at(self, t, atol=1e-3): Returns ------- dict - State name to value, for example ``state["vz"]``. Holds the 13 - canonical states (reconstructed or held at their value when the - phase began, where the phase does not integrate them) plus any - state the phase integrates that is not one of them. + Name to value: the states (see :meth:`at_index`), the control + inputs in force at that row, and the post-process variables the + phase that time falls in computes, when the flight can work them + out. Phases do not all compute the same variables, so a parachute + descent reports fewer names than a powered ascent. """ index = _nearest_time_index(self.time, t, atol, "solution") - return self.at_index(index) + values = self.at_index(index) + values.update(self._post_at_index(index)) + return values def at_index(self, index): - """Return the state stored at row ``index`` as a name to value map. + """Return the state and control inputs stored at row ``index``. Reads a single row, so it stays cheap no matter how long the flight is. Use it instead of ``solution["vz"][index, 1]`` when only one row is @@ -1069,7 +1186,11 @@ def at_index(self, index): Returns ------- dict - State name to value, as described in :meth:`at`. + Name to value, for example ``values["vz"]``. Holds the 13 + canonical states (reconstructed or held at their value when the + phase began, where the phase does not integrate them), any state + the phase integrates that is not one of them, and the control + inputs in force at that row. Raises ------ @@ -1078,7 +1199,11 @@ def at_index(self, index): """ position = self._normalize(int(index)) phase = self._phase_at(position) - return phase.state_dict(self._rows[position][1:]) + values = phase.state_dict(self._rows[position][1:]) + controls = self._controls[position] + if controls: + values.update(controls) + return values def value_at(self, index, name): """Return one state's value at row ``index``. @@ -1123,264 +1248,101 @@ def value_at(self, index, name): f"It integrates {', '.join(phase.dynamics.states)}." ) - @property - def time(self): - """The time column of the whole flight, in seconds, as a 1-D array.""" - return self.canonical_array[:, 0] + # -- Sensor readings --------------------------------------------------- @property - def canonical_array(self): - """The whole flight as a rectangular ``(n, 14)`` canonical table. - - Each row is ``[t, x, y, z, vx, vy, vz, e0, e1, e2, e3, w1, w2, w3]``. - States a phase does not integrate are rebuilt or held. - - The table belongs to the flight and cannot be written to. For a table - of your own to edit, use ``numpy.array(solution)``. - """ - if self._canonical_cache is None or self._canonical_version != self._version: - spans = list(self._spans()) - if not spans: - result = np.empty((0, CANONICAL_WIDTH)) - elif all(phase.dynamics.is_canonical for _, phase, _, _ in spans): - # Every phase already stores the 14 canonical values, so the - # stored rows are the table. Guarded on all of them, since a - # phase storing fewer values would make the rows uneven. - result = np.array(self._rows) - else: - result = np.array(list(self)) - # Read-only so that a caller writing to the table it was handed - # is told, rather than silently rewriting every later read of it. - result.flags.writeable = False - self._canonical_cache = result - self._canonical_version = self._version - return self._canonical_cache - - # -- Serialization ----------------------------------------------------- - - def to_dict(self, **kwargs): # pylint: disable=unused-argument - """Return a serializable description of the whole solution. + def sensors(self): + """What the sensors read over the flight, by sensor. - Parameters - ---------- - **kwargs - The options RocketPy passes to every object it saves, such as - ``include_outputs``. A solution is plain numbers, so none of them - change what is written here. + ``solution.sensors.barometer.pressure`` is an ``(n, 2)`` array of time + and reading, one entry per sampling time of that sensor, with its + noise and resolution. A sensor added in several positions is numbered + from 2 at the positions after the first: ``"Accelerometer"``, + ``"Accelerometer 2"``, read as ``accelerometer`` and + ``accelerometer_2``. ``flight.sensor_history.barometer.pressure`` is + the same reading as a Function of time. Returns ------- dict - The flight's rows and one entry per phase as produced by - :meth:`_PhaseSolution.to_dict`. Pass it to :meth:`from_dict` to - rebuild the solution. - """ - return { - "phases": [phase.to_dict() for phase in self.phases], - "rows": self._rows, - } - - @classmethod - def from_dict(cls, data): - """Rebuild a solution from its serialized form. - - Parameters - ---------- - data : dict - A description produced by :meth:`to_dict`. - - Returns - ------- - Solution - The rebuilt solution. Its phases cannot be post-processed again, - since that needs a running simulation. + Sensor to its channels. Empty for a flight without sensors. """ - phases = [_PhaseSolution.from_dict(entry) for entry in data.get("phases", [])] - rows = [list(row) for row in data.get("rows", [])] - return cls(phases, rows) - - @classmethod - def from_legacy_list(cls, rows): - """Rebuild a solution from the old flat list of canonical rows. - - Older saved flights stored the solution as a single list of - 14-value rows. This wraps that list as one canonical phase so old - files keep loading. - - Parameters - ---------- - rows : sequence of sequence of float - The stored rows, each ``[t, x, y, z, vx, vy, vz, e0, e1, e2, e3, - w1, w2, w3]``. May be empty. - - Returns - ------- - Solution - A solution holding one six-degree-of-freedom phase, anchored at the - first row's time and state. - """ - rows = [list(row) for row in rows] - phase = _PhaseSolution( - SIX_DOF_DYNAMICS, - tuple(rows[0][1:]) if rows else None, - t_start=rows[0][0] if rows else None, - start=0, + return _ResultsDict( + { + name: { + channel: np.array(points, dtype=float) + for channel, points in channels.items() + } + for name, channels in self._sensors.items() + } ) - return cls([phase], rows) - - -class PostProcessSolution: - """The variables a flight computes besides the states it integrates. - - On its way to each state derivative, a flight phase works out quantities it - never integrates: the accelerations, the aerodynamic forces and moments, and - the net thrust. This class is how you read them. Reach it as - ``flight.solution.post``. - - Read one variable over the whole flight with ``post["ax"]``, which gives an - ``(n, 2)`` array of time and value, the same shape ``solution["vz"]`` gives - for a state. Read every variable at one instant with ``post.at(t)``, which - gives a name-to-value dictionary. :attr:`names` lists what this flight - computes. - - Where the values come from depends on the flight. A flight whose controllers - move an air brake records them as it runs, since replaying the stored states - afterwards would read the rocket in the configuration it ended the flight - in. Any other flight works them out from its stored states the first time - you ask, and keeps the answer. Either way the values are not saved to file, - so a flight read back from a saved file cannot report them: recomputing them - needs the equations of motion, which are code and cannot be written out. - - Examples - -------- - >>> flight.solution.post.names # doctest: +SKIP - ('ax', 'ay', 'az', 'alpha1', ..., 'net_thrust') - >>> flight.solution.post["az"] # doctest: +SKIP - array([[0. , 0. ], - [0.001, 9.81 ], - ... - >>> flight.solution.post.at(3.0)["net_thrust"] # doctest: +SKIP - 1834.2 - """ - - # This is Solution's own reading layer, so it works with Solution's - # internals on purpose. The values themselves stay in the Solution, next to - # the rows they were computed from, so a rollback cannot leave the two out - # of step. - # pylint: disable=protected-access - - def __init__(self, solution): - """Attach a reading layer to ``solution``. - - Parameters - ---------- - solution : Solution - The flight whose post-process variables this reads. - """ - self._solution = solution - self._tables = None - self._key = None - - def __repr__(self): - """Return which variables this flight computes.""" - return f"PostProcessSolution(names={self.names!r})" - - @property - def names(self): - """Names of every post-process variable this flight computes. - - The phases of a flight need not all compute the same variables: a - parachute descent reports no moments and no thrust. This lists every - name any phase computes, in the order the phases first introduce them. - A phase that does not compute one of them reports zero for it, which is - the physically right answer for the variables RocketPy defines. - """ - names = [] - for phase in self._solution.phases: - for name in phase.dynamics.post_process_vars: - if name not in names: - names.append(name) - return tuple(names) - - def __contains__(self, name): - """Return whether any phase of this flight computes ``name``.""" - return name in self.names - - def __iter__(self): - """Iterate over :attr:`names`.""" - return iter(self.names) - - def _phase_table(self, phase_index, phase): - """Return one phase's values as an ``(n_rows, n_variables)`` array. - Values recorded while the simulation ran are used as they are. A phase - with none is worked out again from its stored states, which gives the - same answer for a flight whose rocket did not change mid-flight. - - Parameters - ---------- - phase_index : int - Position of the phase in the solution's phases. - phase : _PhaseSolution - That same phase. - - Returns - ------- - numpy.ndarray or None - One row of values per row of the phase, or ``None`` if the phase - holds no rows or can neither be read back nor worked out again. - """ - start, stop = self._solution.phase_span(phase_index) - rows = self._solution._rows[start:stop] - if not rows: - return None - recorded = self._solution._post_values[start:stop] - if self._solution.records_post_values: - # This flight changes the rocket as it flies, so the values it - # recorded are the only right answer. Working them out again would - # read the rocket in the configuration it ended the flight in and - # report, for the whole flight, the air brake deflection it landed - # with. A row with nothing recorded is a bug, not a reason to fall - # back on that. - missing = [index for index, values in enumerate(recorded) if values is None] - if missing: - raise ValueError( - f"This flight recorded its post-process variables as it " - f"ran, because one of its events changes the rocket " - f"mid-flight, but row {start + missing[0]} has none. They " - f"cannot be worked out now: the rocket is no longer in the " - f"configuration it had at that moment. This is a bug in " - f"RocketPy, not something a flight can cause." - ) - return np.array(recorded, dtype=float) + def _add_reading(self, name, time, readings): + """Store what the sensor position ``name`` read at ``time``: channel + name to value.""" + channels = self._sensors.setdefault(name, {}) + for channel, value in readings.items(): + channels.setdefault(channel, []).append((time, value)) + + def _latest_reading(self, name, channel): + """The last value the sensor position ``name`` read on ``channel``, + with its time, or ``None`` before its first reading.""" + points = self._sensors.get(name, {}).get(channel) + return points[-1] if points else None + + def _drop_readings_after(self, time): + """Forget every reading made after ``time``, when the flight goes back + to it.""" + for channels in self._sensors.values(): + for points in channels.values(): + while points and points[-1][0] > time: + points.pop() + + # -- Post-process variables -------------------------------------------- + # On its way to each state derivative, a flight phase works out quantities + # it never integrates: the accelerations, the aerodynamic forces and + # moments, the net thrust. They are worked out again after the flight + # from the stored rows, each with its control inputs and with the surface + # switches replayed by time, the first time one is read, and kept until + # the rows or their control inputs change. They are not saved to file: a + # flight read back from one cannot report them, since that needs the + # equations of motion. + + def _phase_table(self, phase, start, stop): + """Return the post-process values of a phase holding rows ``start`` to + ``stop``, as an ``(n_rows, n_variables)`` array, or ``None`` if the + phase cannot be worked out again (a phase read back from a saved + flight).""" if phase.bound_dynamics is None: - # A phase read back from a saved flight cannot be worked out again, - # since that needs the equations of motion of a live flight. return None + rows = self._rows[start:stop] + # A row with no controls of its own was written since the flight last + # stored them, and is worked out with the flight's controls as they + # are now + controls = self._controls[start:stop] return np.array( [ phase.dynamics.post_process_values( - phase.bound_dynamics.post_process_at(row[0], row[1:]) + phase.bound_dynamics.post_process_at(row[0], row[1:], row_controls) ) - for row in rows + for row, row_controls in zip(rows, controls) ], dtype=float, ) def _phase_tables(self): - """Return every phase's values, working out the ones not recorded. - - The answer is kept until the flight's rows or its recorded values - change, so asking for a second variable costs nothing. - """ - key = (self._solution._version, self._solution._post_version) - if self._tables is None or self._key != key: - self._tables = [ - self._phase_table(index, phase) - for index, phase in enumerate(self._solution.phases) - ] - self._key = key - return self._tables + """Return every phase's post-process values, worked out once and kept + until the rows or their control inputs change, so reading a second + variable costs nothing.""" + key = (self._version, self._post_version) + if self._post_tables is None or self._post_key != key: + # ``None`` for a phase with no rows + tables = [None] * len(self.phases) + for index, phase, start, stop in self._spans(): + tables[index] = self._phase_table(phase, start, stop) + self._post_tables = tables + self._post_key = key + return self._post_tables def phase_values(self, phase_index): """Return one phase's post-process values, one row per row of the phase. @@ -1403,129 +1365,172 @@ def phase_values(self, phase_index): IndexError If ``phase_index`` is outside this flight's phases. """ - tables = self._phase_tables() - return tables[phase_index] - - def __getitem__(self, name): - """Return the ``[t, value]`` history of one variable over the flight. - - Parameters - ---------- - name : str - The variable name, for example ``"az"`` or ``"net_thrust"``. - - Returns - ------- - numpy.ndarray - An ``(n, 2)`` array whose columns are time and value. + return self._phase_tables()[phase_index] - Raises - ------ - KeyError - If no phase of this flight computes the variable, or if the flight - has no stored rows, or if it was read back from a saved file and so - cannot compute it. - """ - names = self.names - if name not in names: - raise KeyError( - f"No flight phase computed the post-process variable '{name}'. " - f"This flight computes: {', '.join(names) or '(none)'}." - ) + def _post_series_or_none(self, name): + """The history of one post-process variable over the phases that can + be worked out, or ``None`` when none can.""" + if not any(name in phase.dynamics.post_process_index for phase in self.phases): + return None tables = self._phase_tables() parts = [] - for index, phase in enumerate(self._solution.phases): + for index, phase, start, stop in self._spans(): table = tables[index] if table is None: continue - start, stop = self._solution.phase_span(index) - times = self._solution.time[start:stop] + times = self.time[start:stop] column = phase.dynamics.post_process_index.get(name) values = np.zeros(len(times)) if column is None else table[:, column] parts.append(np.column_stack([times, values])) if not parts: + return None + return parts[0] if len(parts) == 1 else np.concatenate(parts, axis=0) + + def _post_series(self, name): + """The history of one post-process variable, or a ``KeyError`` when + the flight cannot work it out.""" + result = self._post_series_or_none(name) + if result is None: raise KeyError( f"The post-process variable '{name}' cannot be worked out for " f"this flight. Either it has no stored states yet, or it was " f"read back from a saved file, which does not carry the " f"equations of motion needed to work the variable out again." ) - return parts[0] if len(parts) == 1 else np.concatenate(parts, axis=0) + return result - def at(self, t, atol=1e-3): - """Return every post-process variable at the stored time nearest ``t``. + def _post_at_index(self, index): + """The post-process variables at row ``index``, worked out for that + row alone, and the control inputs as a continuous controller's law + left them there. Empty when the phase computes none or cannot be + worked out.""" + position = self._normalize(int(index)) + phase = self._phase_at(position) + if not phase.dynamics.post_process_vars or phase.bound_dynamics is None: + return {} + row = self._rows[position] + values = phase.dynamics.post_process_values( + phase.bound_dynamics.post_process_at( + row[0], row[1:], self._controls[position] + ) + ) + return { + name.removeprefix("controls."): value + for name, value in zip(phase.dynamics.post_process_vars, values) + } + + # -- Serialization ----------------------------------------------------- + + def to_dict(self, **kwargs): # pylint: disable=unused-argument + """Return a serializable description of the whole solution. Parameters ---------- - t : float - Time in seconds. - atol : float, optional - If the nearest stored time differs from ``t`` by more than this, a - warning is raised. Default is ``1e-3``. + **kwargs + The options RocketPy passes to every object it saves, such as + ``include_outputs``. A solution is plain numbers, so none of them + change what is written here. Returns ------- dict - Variable name to value, holding the variables the phase that time - falls in computes. Phases do not all compute the same variables, so - a parachute descent reports fewer names than a powered ascent. + The flight's rows, one entry per phase as produced by + :meth:`_PhaseSolution.to_dict`, for a flight with controls the + control values stored with each row, and for a flight with + sensors what they read. Pass it to :meth:`from_dict` to rebuild + the solution. """ - index = _nearest_time_index(self._solution.time, t, atol, "solution") - return self.at_index(index) - - def at_index(self, index): - """Return every post-process variable at row ``index``. + data = { + "phases": [phase.to_dict() for phase in self.phases], + "rows": self._rows, + } + if any(self._controls): + # Control input names once, then one list of values per row. A + # control input a continuous controller's law wrote is saved as + # the law left it, since that is not worked out again on loading + names = self.control_names + histories = {name: self._control_history(name) for name in names} + data["control_names"] = list(names) + data["controls"] = [ + None + if controls is None + else [ + float(histories[name][0][position, 1]) + if histories[name][1] + else controls[name] + for name in names + ] + for position, controls in enumerate(self._controls) + ] + if self._sensors: + data["sensors"] = { + name: { + channel: [[float(t), float(value)] for t, value in points] + for channel, points in channels.items() + } + for name, channels in self._sensors.items() + } + return data - Reads a single row, so it stays cheap no matter how long the flight is. - Use it instead of ``post["az"][index, 1]`` when only one row is needed, - since that works out the variable's whole history first. + @classmethod + def from_dict(cls, data): + """Rebuild a solution from its serialized form. Parameters ---------- - index : int - Row position across the whole flight. Negative values count from - the end. + data : dict + A description produced by :meth:`to_dict`. Returns ------- - dict - Variable name to value, as described in :meth:`at`. Empty for a row - of a phase that computes no post-process variables. + Solution + The rebuilt solution. Its phases cannot be post-processed again, + since that needs a running simulation. + """ + phases = [_PhaseSolution.from_dict(entry) for entry in data.get("phases", [])] + rows = [list(row) for row in data.get("rows", [])] + solution = cls(phases, rows) + names = data.get("control_names") + if names: + solution._controls = [ + None if values is None else dict(zip(names, values)) + for values in data["controls"] + ] + solution._post_version += 1 + solution._sensors = { + name: { + channel: [tuple(point) for point in points] + for channel, points in channels.items() + } + for name, channels in data.get("sensors", {}).items() + } + return solution - Raises - ------ - IndexError - If ``index`` is outside the flight's rows. - KeyError - If the row's values were not recorded and the phase was read back - from a saved file, so they cannot be worked out again. + @classmethod + def from_legacy_list(cls, rows): + """Rebuild a solution from the old flat list of canonical rows. + + Older saved flights stored the solution as a single list of + 14-value rows. This wraps that list as one canonical phase so old + files keep loading. + + Parameters + ---------- + rows : sequence of sequence of float + The stored rows, each ``[t, x, y, z, vx, vy, vz, e0, e1, e2, e3, + w1, w2, w3]``. May be empty. + + Returns + ------- + Solution + A solution holding one six-degree-of-freedom phase, anchored at the + first row's time and state. """ - solution = self._solution - position = solution._normalize(int(index)) - phase_index = solution.phase_index_at(position) - phase = solution.phases[phase_index] - if not phase.dynamics.post_process_vars: - return {} - values = solution._post_values[position] - if values is None: - if solution.records_post_values: - raise ValueError( - f"This flight recorded its post-process variables as it " - f"ran, because one of its events changes the rocket " - f"mid-flight, but row {position} has none. They cannot be " - f"worked out now: the rocket is no longer in the " - f"configuration it had at that moment. This is a bug in " - f"RocketPy, not something a flight can cause." - ) - if phase.bound_dynamics is None: - raise KeyError( - "This flight phase was read back from a saved file, so its " - "post-process variables were not recorded and cannot be " - "worked out again: that needs the equations of motion, " - "which are code and are not saved with a flight." - ) - row = solution.raw_row(position) - values = phase.dynamics.post_process_values( - phase.bound_dynamics.post_process_at(row[0], row[1:]) - ) - return dict(zip(phase.dynamics.post_process_vars, values)) + rows = [list(row) for row in rows] + phase = _PhaseSolution( + SIX_DOF_DYNAMICS, + tuple(rows[0][1:]) if rows else None, + t_start=rows[0][0] if rows else None, + start=0, + ) + return cls([phase], rows) diff --git a/rocketpy/stochastic/stochastic_aero_surfaces.py b/rocketpy/stochastic/stochastic_aero_surfaces.py index 07c50f8ee..72270639c 100644 --- a/rocketpy/stochastic/stochastic_aero_surfaces.py +++ b/rocketpy/stochastic/stochastic_aero_surfaces.py @@ -459,15 +459,12 @@ class StochasticAirBrakes(StochasticModel): reference_area : tuple, list, int, float Reference area used to non-dimensionalize the drag coefficients. clamp : bool - If True, the simulation will clamp the deployment level to 0 or 1 if - the deployment level is out of bounds. If False, the simulation will - not clamp the deployment level and will instead raise a warning if - the deployment level is out of bounds. + Whether the deployment level is kept between 0 and 1. Can't be randomized. override_rocket_drag : bool - If False, the air brakes drag coefficient will be added to the - rocket's power off drag coefficient curve. If True, during the - simulation, the rocket's power off drag will be ignored and the air - brakes drag coefficient will be used for the entire rocket instead. + If False, the drag coefficient curve is of the air brakes alone, + added to the rocket's drag. If True, the curve is of the whole + rocket at each deployment level, and the air brakes add the + difference between the curve and its value at deployment level 0. deployment_level : tuple, list, int, float Initial deployment level, ranging from 0 to 1. name : list[str] @@ -504,15 +501,13 @@ def __init__( reference_area : tuple, list, int, float, optional Reference area used to non-dimensionalize the drag coefficients. clamp : bool, optional - If True, the simulation will clamp the deployment level to 0 or 1 if - the deployment level is out of bounds. If False, the simulation will - not clamp the deployment level and will instead raise a warning if - the deployment level is out of bounds. + Whether the deployment level is kept between 0 and 1. Can't be + randomized. override_rocket_drag : bool, optional - If False, the air brakes drag coefficient will be added to the - rocket's power off drag coefficient curve. If True, during the - simulation, the rocket's power off drag will be ignored and the air - brakes drag coefficient will be used for the entire rocket instead. + If False, the drag coefficient curve is of the air brakes alone, + added to the rocket's drag. If True, the curve is of the whole + rocket at each deployment level, and the air brakes add the + difference between the curve and its value at deployment level 0. deployment_level : tuple, list, int, float, optional Initial deployment level, ranging from 0 to 1. """ @@ -542,7 +537,11 @@ def create_object(self): reference_area=generated_dict["reference_area"], clamp=generated_dict["clamp"], override_rocket_drag=generated_dict["override_rocket_drag"], - deployment_level=generated_dict["deployment_level"], + initial_deployment_level=generated_dict["deployment_level"], + # The name sets the names of its control inputs + name=self.obj.name, + active_during=self.obj.active_during, + active=self.obj.active, ) air_brakes.drag_coefficient *= generated_dict["drag_coefficient_curve_factor"] return air_brakes diff --git a/rocketpy/stochastic/stochastic_rocket.py b/rocketpy/stochastic/stochastic_rocket.py index 909b006b4..a1be4ef70 100644 --- a/rocketpy/stochastic/stochastic_rocket.py +++ b/rocketpy/stochastic/stochastic_rocket.py @@ -1,9 +1,9 @@ """Defines the StochasticRocket class.""" import warnings +from copy import deepcopy from random import choice -from rocketpy.control import _Controller from rocketpy.mathutils.vector_matrix import Vector from rocketpy.motors.empty_motor import EmptyMotor from rocketpy.motors.motor import GenericMotor, Motor @@ -99,7 +99,9 @@ class StochasticRocket(StochasticModel): Surfaces with no stochastic version yet, the ones built from their own coefficients (``GenericSurface`` and its linear and controllable versions), the free-form fins and the individual fins, are added to every generated - rocket unchanged, at their position. + rocket unchanged, at their position. So are the rocket's effectors, and a + copy of each of its controllers and sensors: every generated rocket flies + the same control loop, with its own measurements. """ def __init__( @@ -293,7 +295,10 @@ def _add_surfaces(self, surfaces, positions, type_, stochastic_type, error_messa if not isinstance(surfaces, (type_, stochastic_type)): raise AssertionError(error_message) if isinstance(surfaces, type_): - surfaces = stochastic_type(component=surfaces) + # Positionally: the stochastic classes each name this first + # parameter after their own surface (`nosecone`, `tail`, ...), so + # there is no one keyword that reaches all of them. + surfaces = stochastic_type(surfaces) self.__components_map[surfaces] = positions self.aerodynamic_surfaces.add( surfaces, self._validate_position(surfaces, positions) @@ -419,9 +424,13 @@ def add_air_brakes(self, air_brakes, controller): Parameters ---------- air_brakes : StochasticAirBrakes or Airbrakes - The air brake to be added to the stochastic rocket. - controller : _Controller - Deterministic air brake controller. + The air brake to be added to the stochastic rocket. Without this + call, every sampled rocket flies the rocket's air brakes as they + are, not dispersed. + controller : Controller + No longer used: every sampled rocket flies a copy of each + controller of the rocket, the one of the air brakes among them. + Kept so that existing scripts keep working. """ if not isinstance(air_brakes, (AirBrakes, StochasticAirBrakes)): raise TypeError( @@ -717,6 +726,15 @@ def _create_rail_buttons(self, component_stochastic_rail_buttons): ) return rail_buttons, lower_button_position_rnd, upper_button_position_rnd + def _air_brake_position(self, air_brakes): + """Return where ``air_brakes`` sit on the base rocket, or its center of + dry mass when they are not on it.""" + for surface, position in self.obj.aerodynamic_surfaces: + if surface is air_brakes: + at_center = self.obj._is_at_center_of_dry_mass(surface) + return None if at_center else position + return None + def _create_air_brake(self, stochastic_air_brake): air_brake = stochastic_air_brake.create_object() self.last_rnd_dict["air_brakes"].append(stochastic_air_brake.last_rnd_dict) @@ -792,24 +810,52 @@ def create_object(self): surface, position_rnd = self._create_surface(component_surface) rocket.add_surfaces(surface, position_rnd) - # Surfaces with no stochastic version are carried over as they are + # Surfaces with no stochastic version are carried over as they are. + # Air brakes have one, added with add_air_brakes; when none was added, + # the rocket's air brakes are carried over as they are too, so that + # their controller, which is carried, finds them + dispersed = _DISPERSED_SURFACES + if self.air_brakes: + dispersed = (*dispersed, AirBrakes) for surface, position in self.obj.aerodynamic_surfaces: - if not isinstance(surface, _DISPERSED_SURFACES): - rocket.add_surfaces(surface, position) + if not isinstance(surface, dispersed): + at_center = self.obj._is_at_center_of_dry_mass(surface) + with warnings.catch_warnings(): + # The rocket was already warned when its air brakes were + # added, if their curve and its drag disagree + warnings.simplefilter("ignore", UserWarning) + rocket.add_surfaces(surface, None if at_center else position) for air_brake in self.air_brakes: - air_brake = self._create_air_brake(air_brake) - base_controller = self.air_brake_controller - _controller = _Controller( - controller_function=base_controller.controller_function, - controlled_objects=air_brake, - controlled_objects_name=base_controller.controlled_objects_name, - sampling_rate=base_controller.sampling_rate, - memory=base_controller.memory.copy(), - name=base_controller.name, - ) - rocket.air_brakes.append(air_brake) - rocket._add_controllers(_controller) + created = self._create_air_brake(air_brake) + with warnings.catch_warnings(): + # The rocket these are sampled from was warned when its air + # brakes were added, if their curve and its drag disagree: no + # need to say it again at every sample + warnings.simplefilter("ignore", UserWarning) + rocket.add_surfaces(created, self._air_brake_position(air_brake.obj)) + + # Thrust effectors and force effectors have no stochastic + # version: they are carried over as they are, holding no state + for effector, position in self.obj.effectors: + rocket.add_effector(effector, position) + for controller in self.obj.continuous_controllers: + rocket.add_controller(controller) + + # A controller sets its controls by name and points at no object, so + # each sampled rocket flies a copy of every controller of the rocket, + # in the order they were added + for controller in self.obj.controllers: + rocket.add_controller(deepcopy(controller)) + + # The sensors, each sampled rocket with its own copies. A sensor + # added in more than one position stays one sensor + sensor_copies = {} + for sensor, position in self.obj.sensors: + if sensor not in sensor_copies: + # pylint: disable-next=protected-access + sensor_copies[sensor] = sensor._detached_copy() + rocket.add_sensor(sensor_copies[sensor], position) for component_rail_buttons in self.rail_buttons: ( diff --git a/rocketpy/tools.py b/rocketpy/tools.py index 68f4a54bd..e95577324 100644 --- a/rocketpy/tools.py +++ b/rocketpy/tools.py @@ -16,6 +16,8 @@ import time import warnings from bisect import bisect_left +from copy import deepcopy +from numbers import Real import dill import matplotlib.pyplot as plt @@ -1328,6 +1330,38 @@ def parallel_axis_theorem_from_com(com_inertia_moment, mass, distance): return com_inertia_moment + mass * distance**2 +def point_around(position, angular_position, radius, csys=1): + """Find the point placed around the rocket's axis. + + This is where a fin, a rail button or an effector sits when it is given by + its position along the rocket, its distance from the rocket's axis and its + angle around the rocket. + + Parameters + ---------- + position : float + Position of the point along the rocket's axis, in meters, in the + rocket's user coordinate system. + angular_position : float + Angle of the point around the rocket's axis, in degrees, measured + from the y axis. See :ref:`Angular Position Inputs `. + radius : float + Distance from the rocket's axis to the point, in meters. + csys : int, optional + Orientation of the rocket's coordinate system: ``1`` for + ``"tail_to_nose"`` and ``-1`` for ``"nose_to_tail"``. The x coordinate + changes sign with it, the y coordinate does not. Default is ``1``. + + Returns + ------- + tuple of float + The ``(x, y, z)`` coordinates of the point, in meters, in the rocket's + user coordinate system. + """ + angle = math.radians(angular_position) + return (-radius * math.sin(angle) * csys, radius * math.cos(angle), position) + + # Flight def quaternions_to_precession(e0, e1, e2, e3): """Calculates the Precession angle @@ -1553,6 +1587,98 @@ def find_obj_from_hash(obj, hash_, depth_limit=None): return None +# Name boundaries in a CamelCase name: "AirBrakes" -> "Air_Brakes", +# "TVCGimbal" -> "TVC_Gimbal" +_LOWER_TO_UPPER = re.compile(r"(?<=[a-z0-9])(?=[A-Z])") +_ACRONYM_END = re.compile(r"(?<=[A-Z])(?=[A-Z][a-z])") +_NOT_ALPHANUMERIC = re.compile(r"[^0-9a-zA-Z]+") + + +def snake_case_key(name): + """Return ``name`` in snake_case, as the control inputs of a controllable, + the readings of a sensor and the records of an event are named: + ``"Canards"`` gives + ``canards``, ``"AirBrakes"`` gives ``air_brakes``, ``"Nose IMU"`` gives + ``nose_imu`` and ``"calisto_nose_cone"`` stays as it is. + + Parameters + ---------- + name : str + The name of the controllable, sensor or event. + + Returns + ------- + str + """ + text = _ACRONYM_END.sub("_", _LOWER_TO_UPPER.sub("_", str(name))) + key = _NOT_ALPHANUMERIC.sub("_", text).strip("_").lower() + if not key: + key = "controllable" + if key[0].isdigit(): + key = f"controllable_{key}" + return key + + +def unique_names(names): + """Return ``names`` with repeats numbered from 2, so that no two give the + same name in snake_case: ``["Event", "Event"]`` gives ``["Event", "Event + 2"]``.""" + used = set() + unique = [] + for name in names: + candidate, number = name, 1 + while snake_case_key(candidate) in used: + number += 1 + candidate = f"{name} {number}" + used.add(snake_case_key(candidate)) + unique.append(candidate) + return unique + + +def history_function(points, name): + """Return a sampled history as a Function of time that holds each value + until the next sample. + + Parameters + ---------- + points : sequence of (float, float) + ``(time, value)`` pairs, in time order. A later pair at the same time + replaces an earlier one, since it is what held from that time on. + name : str + Name of the value, for the Function's output. + + Returns + ------- + Function + """ + # Imported here: the function module imports this one + # pylint: disable-next=import-outside-toplevel,cyclic-import + from rocketpy.mathutils.function import Function + + held = {} + for t, value in points: + held[float(t)] = float(value) + return Function( + [[t, value] for t, value in held.items()], + inputs="Time (s)", + outputs=name, + interpolation="previous", + extrapolation="constant", + ) + + +def copied_value(value): + """Return a number as it is and anything else as a copy, so a later change + to the object does not change the value kept. An object that cannot be + copied is returned as it is.""" + if isinstance(value, Real): + return value + try: + return deepcopy(value) + except Exception: # pylint: disable=broad-exception-caught + return value + + if __name__ == "__main__": # pragma: no cover import doctest diff --git a/tests/conftest.py b/tests/conftest.py index a12c683e2..ee3e247f3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,6 +12,7 @@ "tests.fixtures.flight.flight_fixtures", "tests.fixtures.function.function_fixtures", "tests.fixtures.controller.controller_fixtures", + "tests.fixtures.effectors.effector_fixtures", "tests.fixtures.motor.liquid_fixtures", "tests.fixtures.motor.hybrid_fixtures", "tests.fixtures.motor.solid_motor_fixtures", diff --git a/tests/fixtures/controller/controller_fixtures.py b/tests/fixtures/controller/controller_fixtures.py index e7fbcf8ca..f1573d933 100644 --- a/tests/fixtures/controller/controller_fixtures.py +++ b/tests/fixtures/controller/controller_fixtures.py @@ -18,27 +18,24 @@ def controller_function(): def controller_function(context): time = context.time sampling_rate = context.sampling_rate - air_brakes = context.controlled.air_brakes + air_brakes = context.controls["AirBrakes"] z = context.state.z vz = context.state.vz previous_state = context.previous_state previous_vz = previous_state.vz if previous_state is not None else vz if time < 3.9: return None + deployment_level = air_brakes.deployment_level if z < 1500: air_brakes.deployment_level = 0 else: - new_deployment_level = ( - air_brakes.deployment_level + 0.1 * vz + 0.01 * previous_vz**2 - ) - if new_deployment_level > air_brakes.deployment_level + 0.2 / sampling_rate: - new_deployment_level = air_brakes.deployment_level + 0.2 / sampling_rate - elif ( - new_deployment_level < air_brakes.deployment_level - 0.2 / sampling_rate - ): - new_deployment_level = air_brakes.deployment_level - 0.2 / sampling_rate + new_deployment_level = deployment_level + 0.1 * vz + 0.01 * previous_vz**2 + if new_deployment_level > deployment_level + 0.2 / sampling_rate: + new_deployment_level = deployment_level + 0.2 / sampling_rate + elif new_deployment_level < deployment_level - 0.2 / sampling_rate: + new_deployment_level = deployment_level - 0.2 / sampling_rate else: - new_deployment_level = air_brakes.deployment_level + new_deployment_level = deployment_level air_brakes.deployment_level = new_deployment_level return controller_function @@ -60,6 +57,7 @@ def controller_function( # pylint: disable=unused-argument time, sampling_rate, state, + state_history, observed_variables, air_brakes, sensors, diff --git a/tests/fixtures/effectors/__init__.py b/tests/fixtures/effectors/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/fixtures/effectors/effector_fixtures.py b/tests/fixtures/effectors/effector_fixtures.py new file mode 100644 index 000000000..0b33201d8 --- /dev/null +++ b/tests/fixtures/effectors/effector_fixtures.py @@ -0,0 +1,68 @@ +"""Test effectors for the hooks in the equations of motion: a gimbal that +turns the thrust, and effectors that push or turn the rocket. +They are the smallest classes that satisfy each hook, not models of real +hardware.""" + +import math + +import pytest + +from rocketpy import ForceEffector, ThrustEffector + + +class Gimbal(ThrustEffector): + """Turns the thrust by ``pitch`` radians about the body y axis, at the + nozzle exit: the exit itself stays where it is.""" + + def __init__(self, name="Gimbal"): + super().__init__( + controls=("pitch",), control_limits={"pitch": (-0.2, 0.2)}, name=name + ) + + def thrust_and_nozzle(self, thrust, nozzle, controls, conditions): # pylint: disable=unused-argument + angle = controls[0] + turned = [ + thrust[0] * math.cos(angle) + thrust[2] * math.sin(angle), + thrust[1], + -thrust[0] * math.sin(angle) + thrust[2] * math.cos(angle), + ] + return turned, nozzle + + +class PassThrough(ThrustEffector): + """A thrust effector that leaves the thrust as it is.""" + + def __init__(self): + super().__init__(name="Pass Through") + + def thrust_and_nozzle(self, thrust, nozzle, controls, conditions): # pylint: disable=unused-argument + return thrust, nozzle + + +@pytest.fixture +def gimbal(): + return Gimbal() + + +def _push(on, conditions): # pylint: disable=unused-argument + """10 N along the rocket's axis and 0.5 N m about it, when on.""" + return [0.0, 0.0, 10.0 * on], [0.0, 0.0, 0.5 * on] + + +def _side_push(on, conditions): # pylint: disable=unused-argument + """10 N sideways, through the center of dry mass, when on.""" + return [10.0 * on, 0.0, 0.0], [0.0, 0.0, 0.0] + + +@pytest.fixture +def push_effector(): + return ForceEffector( + _push, controls=("on",), control_limits={"on": (0, 1)}, name="Push" + ) + + +@pytest.fixture +def side_effector(): + return ForceEffector( + _side_push, controls=("on",), control_limits={"on": (0, 1)}, name="Side" + ) diff --git a/tests/integration/simulation/test_controls.py b/tests/integration/simulation/test_controls.py new file mode 100644 index 000000000..b49e5f9fb --- /dev/null +++ b/tests/integration/simulation/test_controls.py @@ -0,0 +1,234 @@ +"""Flights with controls: the control inputs stored with the rows, read back +after the flight, recorded values, and saving.""" + +import json +from unittest.mock import patch + +import numpy as np +import pytest + +from rocketpy import ContinuousController, Controller, Event, Flight, GenericSurface +from rocketpy._encoders import RocketPyDecoder, RocketPyEncoder + + +def _roll_damped_flight(rocket, environment, **event_options): + """Calisto with canards whose deflection a 50 Hz event sets against the + roll rate, and records.""" + canards = GenericSurface( + rocket.area, + 2 * rocket.radius, + {"cl": lambda mach, deflection: 2.0 * deflection}, + name="Canards", + controls=("deflection",), + control_limits={"deflection": (-0.15, 0.15)}, + ) + rocket.add_surfaces(canards, 0.7) + + def damper(context): + context.controls.canards.deflection = -0.05 * context.state.w3 + context.record(roll_rate=context.state.w3) + + damper_event = Event( + callback=damper, sampling_rate=50, name="Roll damper", **event_options + ) + flight = Flight( + rocket=rocket, + environment=environment, + rail_length=5.2, + inclination=85, + heading=0, + terminate_on_apogee=True, + custom_events=[damper_event], + ) + return flight, damper_event + + +@pytest.fixture +def damped_flight(calisto_robust, example_plain_env): + calisto_robust.parachutes = [] + return _roll_damped_flight(calisto_robust, example_plain_env) + + +def test_the_controls_hold_each_value(damped_flight): + flight, damper_event = damped_flight + history = flight.controls["Canards"].deflection + stored = flight.solution.controls.canards.deflection + + assert list(flight.controls) == ["Canards"] + assert stored.tolist() == flight.solution["canards.deflection"].tolist() + assert stored.shape == (len(flight.solution), 2) + # between two rows the value in force is the earlier row's + t0, t1 = stored[100, 0], stored[101, 0] + assert history((t0 + t1) / 2) == stored[100, 1] + # the deflection only ever changes at a time the damper ran + changes = stored[1:, 1] != stored[:-1, 1] + sampled = set(np.round(damper_event.triggered_times, 9)) + assert set(np.round(stored[1:, 0][changes], 9)) <= sampled + # the canards damp the roll: the deflection stays inside its limits + assert np.all(np.abs(stored[:, 1]) <= 0.15) + + +def test_a_write_inside_a_step_acts_from_the_event_time(damped_flight): + """The damper runs on interpolated states inside solver steps; each write + cuts the step there, so the row at the sampling time carries the value.""" + flight, damper_event = damped_flight + stored = flight.solution.controls.canards.deflection + # the first row whose deflection differs from the one before it + row = int(np.argmax(stored[1:, 1] != stored[:-1, 1])) + 1 + assert stored[row - 1, 1] == 0.0 != stored[row, 1] + # it sits exactly at a time the damper ran, not at a solver step's end + assert stored[row, 0] in damper_event.triggered_times + + +def test_records_are_read_after_the_flight(damped_flight): + flight, damper_event = damped_flight + roll_rate = flight.records.roll_damper.roll_rate + assert roll_rate == damper_event.records["roll_rate"] + # one record per time the damper ran: the times it ran again after the + # flight went back to rail exit replaced what it had recorded then + assert len(roll_rate) == len(set(damper_event.triggered_times)) + # the recorded roll rate is the flight's, at the recorded times + t, recorded = roll_rate[len(roll_rate) // 2] + assert recorded == pytest.approx(flight.w3(t), rel=1e-3, abs=1e-6) + + +def test_controls_and_records_are_saved_with_the_flight(damped_flight): + flight, _ = damped_flight + loaded = json.loads(json.dumps(flight, cls=RocketPyEncoder), cls=RocketPyDecoder) + + assert loaded.solution.control_names == ("canards.deflection",) + for t in (2.0, 5.0, 10.0): + assert loaded.controls["Canards"].deflection(t) == ( + flight.controls["Canards"].deflection(t) + ) + assert list(loaded.records) == ["Roll damper"] + assert list(loaded.records["Roll damper"]) == ["roll_rate"] + + +@patch("matplotlib.pyplot.show") +def test_controls_are_plotted_and_printed(mock_show, damped_flight, capsys): # pylint: disable=unused-argument + flight, _ = damped_flight + assert flight.plots.controls() is None + assert flight.plots.records() is None + flight.prints.controls() + # named as ``flight.controls`` reads it: the name as given, then the control + assert "Canards.deflection" in capsys.readouterr().out + + +def _integrate_roll(states, controls, conditions): # pylint: disable=unused-argument + return [conditions.state.w3] + + +def _write_level(context): + context.outputs.sampled.level = 0.1 + + +@patch("matplotlib.pyplot.show") +def test_every_kind_of_controller_is_printed_and_plotted( + mock_show, # pylint: disable=unused-argument + calisto_robust, + example_plain_env, + capsys, +): + """A sampled controller with an output and a continuous controller with a + state are all in the flight's prints and plots.""" + calisto_robust.parachutes = [] + calisto_robust.add_controller( + Controller(_write_level, 10, outputs=("level",), name="Sampled") + ) + calisto_robust.add_controller( + ContinuousController( + states=("roll",), state_derivative=_integrate_roll, name="Observer" + ) + ) + flight = _fly(calisto_robust, example_plain_env) + + flight.prints.controllers() + out = capsys.readouterr().out + assert "Sampling Rate: 10.000 Hz" in out + assert "Continuous Controller: Observer" in out and "State roll" in out + assert flight.plots.state_history() is None + assert flight.plots.event_outputs() is None + assert flight.all_info() is None + + +def _canards(rocket): + canards = GenericSurface( + rocket.area, + 2 * rocket.radius, + {"cl": lambda mach, deflection: 2.0 * deflection}, + name="Canards", + controls=("deflection",), + control_limits={"deflection": (-0.15, 0.15)}, + ) + rocket.add_surfaces(canards, 0.7) + return canards + + +def _fly(rocket, environment, **options): + return Flight( + rocket=rocket, + environment=environment, + rail_length=5.2, + inclination=85, + heading=0, + terminate_on_apogee=True, + **options, + ) + + +def _profile_deflection(time): + return 0.01 * time + + +def _follow_profile(context): + context.controls.canards.deflection = _profile_deflection(context.time) + + +def test_an_open_loop_profile_is_flown_at_the_sampling_times( + calisto_robust, example_plain_env +): + calisto_robust.parachutes = [] + _canards(calisto_robust) + controller = Controller(_follow_profile, sampling_rate=10) + calisto_robust.add_controller(controller) + flight = _fly(calisto_robust, example_plain_env) + + assert flight.controllers == [controller] + history = flight.controls["Canards"].deflection + times = sorted(set(controller.triggered_times)) + assert times[:2] == pytest.approx([0.1, 0.2]) + for t in times[:30]: + # the value flown from each sampling time on, and held until the next + assert history(t) == _profile_deflection(t) + assert history(t + 0.05) == _profile_deflection(t) + + +def test_a_rocket_with_a_controller_flies_the_same_after_saving( + calisto_robust, example_plain_env +): + calisto_robust.parachutes = [] + _canards(calisto_robust) + calisto_robust.add_controller( + Controller(_follow_profile, sampling_rate=10, name="Profile") + ) + flight = _fly(calisto_robust, example_plain_env) + loaded = json.loads( + json.dumps(calisto_robust, cls=RocketPyEncoder), cls=RocketPyDecoder + ) + again = _fly(loaded, example_plain_env) + + assert [c.name for c in loaded.controllers] == ["Profile"] + assert again.apogee == flight.apogee + assert np.array_equal( + again.solution.controls.canards.deflection, + flight.solution.controls.canards.deflection, + ) + + +def test_records_stay_with_the_flight_that_made_them(damped_flight, example_plain_env): + flight, damper_event = damped_flight + first = flight.records.roll_damper.roll_rate + # the same event flies again in a second flight + _fly(flight.rocket, example_plain_env, custom_events=[damper_event]) + assert flight.records.roll_damper.roll_rate == first diff --git a/tests/integration/simulation/test_effector_hooks.py b/tests/integration/simulation/test_effector_hooks.py new file mode 100644 index 000000000..2ece53ce9 --- /dev/null +++ b/tests/integration/simulation/test_effector_hooks.py @@ -0,0 +1,328 @@ +"""The hooks that bring thrust and force effectors into the equations of +motion, checked on Calisto flights.""" + +import numpy as np +import pytest + +from rocketpy import Controller, Event, Flight +from rocketpy.control import FlightConditions, ForceEffector +from rocketpy.simulation.helpers.dynamics import _PhaseDynamics +from rocketpy.simulation.helpers.flight_derivatives import _effector_thrust +from tests.fixtures.effectors.effector_fixtures import Gimbal, PassThrough + + +def _fly(rocket, environment, **options): + rocket.parachutes = [] + options.setdefault("terminate_on_apogee", True) + return Flight( + rocket=rocket, + environment=environment, + rail_length=5.2, + inclination=85, + heading=0, + **options, + ) + + +def _row_at(flight, time): + """Return the time and canonical state of the first row at or after + ``time``.""" + rows = np.array(flight.solution, dtype=float) + row = rows[np.searchsorted(rows[:, 0], time)] + return row[0], list(row[1:]) + + +def _equivalent(fx, fy, fz, mx, my, mz, conditions): # pylint: disable=unused-argument + return [fx, fy, fz], [mx, my, mz] + + +_DERIVATIVES = { + "standard": "u_dot_generalized", + "solid_propulsion": "u_dot", + "3 DOF": "u_dot_generalized_3dof", +} + + +def test_a_thrust_effector_that_changes_nothing_flies_the_same( + calisto_robust, example_plain_env +): + plain = _fly(calisto_robust, example_plain_env) + calisto_robust.add_effector(PassThrough()) + passed = _fly(calisto_robust, example_plain_env) + assert passed.apogee == pytest.approx(plain.apogee, rel=1e-9) + assert passed.apogee_time == pytest.approx(plain.apogee_time, rel=1e-9) + + +@pytest.mark.parametrize("model", ["standard", "solid_propulsion", "3 DOF"]) +def test_a_turned_thrust_acts_as_the_force_and_moment_it_adds( + calisto_robust, example_plain_env, gimbal, model +): + """Turning the thrust changes the derivative exactly as an effector + pushing with the difference in force and moment would.""" + calisto_robust.add_effector(gimbal) + calisto_robust.add_effector( + ForceEffector( + _equivalent, + controls=("fx", "fy", "fz", "mx", "my", "mz"), + name="Equivalent", + ) + ) + options = ( + {"simulation_mode": "3 DOF"} + if model == "3 DOF" + else {"equations_of_motion": model} + ) + flight = _fly(calisto_robust, example_plain_env, **options) + dynamics = getattr(flight, _DERIVATIVES[model]) + t, u = _row_at(flight, 2.0) # the motor burns + controls = dict(flight._controls) + controls.update(dict.fromkeys(controls, 0.0)) + + net_thrust = flight.net_thrust(t) + straight, straight_moment, _ = _effector_thrust( + flight, + FlightConditions(flight.rocket, flight.env, t, u), + net_thrust, + controls, + ) + turned_controls = {**controls, "gimbal.pitch": 0.1} + turned, turned_moment, _ = _effector_thrust( + flight, + FlightConditions(flight.rocket, flight.env, t, u), + net_thrust, + turned_controls, + ) + force, moment = turned - straight, turned_moment - straight_moment + pushed_controls = { + **controls, + **dict(zip(("equivalent.fx", "equivalent.fy", "equivalent.fz"), force)), + **dict(zip(("equivalent.mx", "equivalent.my", "equivalent.mz"), moment)), + } + + by_thrust = dynamics.derivative_at(t, u, turned_controls) + by_effector = dynamics.derivative_at(t, u, pushed_controls) + assert by_thrust == pytest.approx(by_effector, rel=1e-9, abs=1e-12) + assert by_thrust != pytest.approx(dynamics.derivative_at(t, u, controls)) + if model != "3 DOF": + # tipped toward +x behind the center of mass, the nose turns to -x + assert by_thrust[11] < dynamics.derivative_at(t, u, controls)[11] + + +def test_an_effector_reaches_the_accelerations( + calisto_robust, example_plain_env, push_effector +): + calisto_robust.add_effector(push_effector) + flight = _fly(calisto_robust, example_plain_env) + t, u = _row_at(flight, 6.0) # coasting + off = flight.u_dot_generalized.derivative_at(t, u, {"push.on": 0.0}) + on = flight.u_dot_generalized.derivative_at(t, u, {"push.on": 1.0}) + + # 10 N along the axis: the axis, in the Earth frame, times 10 N / mass + e0, e1, e2, e3 = u[6:10] + axis = [2 * (e1 * e3 + e0 * e2), 2 * (e2 * e3 - e0 * e1), 1 - 2 * (e1**2 + e2**2)] + mass = calisto_robust.total_mass(t) + assert [a - b for a, b in zip(on[3:6], off[3:6])] == pytest.approx( + # the attitude matrix normalizes the quaternion, which this does not + [10.0 * component / mass for component in axis], + rel=1e-6, + ) + # 0.5 N m about the axis turns the rocket about it + assert on[12] - off[12] == pytest.approx(0.5 / calisto_robust.I_33(t), rel=1e-9) + + +def test_on_the_rail_only_the_axial_force_counts( + calisto_robust, example_plain_env, push_effector, side_effector +): + calisto_robust.add_effector(push_effector) + calisto_robust.add_effector(side_effector) + flight = _fly(calisto_robust, example_plain_env) + t, u = _row_at(flight, 0.1) + controls = {"push.on": 0.0, "side.on": 0.0} + rail = flight.udot_rail1 + still = rail.derivative_at(t, u, controls) + assert rail.derivative_at(t, u, {**controls, "side.on": 1.0}) == still + + pushed = rail.derivative_at(t, u, {**controls, "push.on": 1.0}) + along = np.linalg.norm(pushed[3:6]) - np.linalg.norm(still[3:6]) + assert along == pytest.approx(10.0 / calisto_robust.total_mass(t), rel=1e-9) + + +def _spin_up(context): + """Roll the rocket with the thrusters once the motor is out.""" + context.controls.push.on = 1.0 if context.time > 4.0 else 0.0 + + +def test_a_controller_drives_an_effector( + calisto_robust, example_plain_env, push_effector +): + calisto_robust.add_effector(push_effector) + calisto_robust.add_controller(Controller(_spin_up, sampling_rate=10)) + flight = _fly(calisto_robust, example_plain_env) + + history = flight.controls.push.on + assert history(3.0) == 0.0 and history(6.0) == 1.0 + # 0.5 N m about the axis, from 4 s on: the roll rate keeps growing + assert abs(flight.w3(10.0)) > abs(flight.w3(5.0)) > abs(flight.w3(3.9)) + + +class _Canopy(ForceEffector): + """The brake of a steerable canopy: nothing to the free-flight phases, + read only by the glide phase below. (A canopy gets its own registration + with the parafoil model; until then it is an effector that does nothing.)""" + + def __init__(self): + super().__init__( + controls=("brake",), control_limits={"brake": (0.0, 1.0)}, name="Canopy" + ) + + def force_and_moment(self, controls, conditions): + return [0.0, 0.0, 0.0], [0.0, 0.0, 0.0] + + +def _glide_derivative(_flight, _t, u, controls, post_processing=False): + """Fall, and turn at the rate the brake sets, in rad/s.""" + if post_processing: + return () + return [u[3], u[4], u[5], 0.0, 0.0, -9.80665, controls["canopy.brake"]] + + +GLIDE_DYNAMICS = _PhaseDynamics( + "test_glide", + _glide_derivative, + ("x", "y", "z", "vx", "vy", "vz", "heading"), + initial_state=lambda _flight, _t, canonical, _previous: [*canonical[:6], 0.0], +) + + +def _open_canopy(context): + context["event"].commands.set_dynamics(GLIDE_DYNAMICS) + context["event"].commands.start_flight_phase("glide") + + +def _brake(context): + context.controls.canopy.brake = 1.0 if context.time >= 6.0 else 0.0 + + +def _glide_flight(rocket, environment, open_at): + rocket.add_effector(_Canopy()) + rocket.add_controller(Controller(_brake, sampling_rate=10)) + opening = Event( + callback=_open_canopy, + trigger=lambda context: context["time"] >= open_at, + sampling_rate=10, + trigger_only_once=True, + name="Open canopy", + ) + # No max_time: with a short one and no max_time_step, the solver can step + # over the whole burn while the rocket waits on the pad + return _fly(rocket, environment, custom_events=[opening], terminate_on_apogee=False) + + +def test_a_phase_of_its_own_reads_a_part(calisto_robust, example_plain_env): + """A controllable only a custom phase reads gets its channel like any other, and + the phase reads it by name from the control inputs.""" + flight = _glide_flight(calisto_robust, example_plain_env, open_at=5.05) + + assert [phase.name for phase in flight.solution.phases][-1] == "glide" + # the control inputs carry the brake for the whole flight + brake = flight.solution.controls.canopy.brake + assert brake[0, 0] == 0.0 and brake[-1, 1] == 1.0 + # the glide phase turns at the rate the brake sets: 1 rad/s from 6 s + with pytest.warns(UserWarning, match="not defined during"): + heading = flight.solution["heading"] + late = heading[heading[:, 0] >= 6.5] + rate = (late[-1, 1] - late[0, 1]) / (late[-1, 0] - late[0, 0]) + assert rate == pytest.approx(1.0, rel=1e-6) + + +class _LaggingGimbal(Gimbal): + """A gimbal whose angle follows the command with a first-order lag of + ``time_constant`` seconds; with ``None`` its state follows nothing and it + turns the thrust by the command at once.""" + + states = ("angle",) + + def __init__(self, time_constant): + super().__init__("Gimbal") + self.time_constant = time_constant + + def state_derivative(self, states, commands, conditions): + if self.time_constant is None: + return [0.0] + return [(commands[0] - states[0]) / self.time_constant] + + def actual_controls(self, states, commands, conditions): + return commands if self.time_constant is None else [states[0]] + + +def _command_pitch_after(time, pitch): + def controller(context): + if context.time >= time: + context.controls.gimbal.pitch = pitch + + return Controller(controller, sampling_rate=20) + + +def test_controllable_states_that_change_nothing_fly_the_same( + calisto_robust, example_plain_env +): + """A controllable with a state the physics never reads flies as the same + controllable without it, on the rail and off it. Not to the last digit: the solver + weighs its error over one more state, so its steps differ slightly.""" + calisto_robust.add_effector(Gimbal()) + calisto_robust.add_controller(_command_pitch_after(1.0, 0.05)) + plain = _fly(calisto_robust, example_plain_env) + calisto_robust.effectors._components[0] = calisto_robust.effectors.component_tuple( + _LaggingGimbal(None), None + ) + stated = _fly(calisto_robust, example_plain_env) + assert stated.apogee == pytest.approx(plain.apogee, rel=1e-5) + assert stated.apogee_time == pytest.approx(plain.apogee_time, rel=1e-5) + assert stated.solution.ax[-1][1] == pytest.approx( + plain.solution.ax[-1][1], rel=1e-5 + ) + + +def test_a_part_state_follows_its_command_through_the_phases( + calisto_robust, example_plain_env +): + """The gimbal's angle starts at its initial value, carries over when the + rocket leaves the rail, and lags the command it is given at 1 s.""" + calisto_robust.add_effector(_LaggingGimbal(time_constant=0.1)) + calisto_robust.add_controller(_command_pitch_after(1.0, 0.05)) + flight = _fly(calisto_robust, example_plain_env) + assert len(flight.solution.phases) > 1 + angle = np.array(flight.solution["gimbal_angle"], dtype=float) + times, values = angle[:, 0], angle[:, 1] + assert np.all(values[times < 1.0] == 0.0) + # One time constant after the command, about 63% of the way there + assert np.interp(1.1, times, values) == pytest.approx( + 0.05 * (1 - np.exp(-1)), rel=0.05 + ) + assert values[-1] == pytest.approx(0.05, rel=1e-3) + + +def test_a_continued_flight_keeps_the_controls_and_the_part_states( + calisto_robust, example_plain_env +): + """A flight started from another one goes on with that flight's last control + inputs and controllables' states, so the two halves fly as the whole.""" + calisto_robust.add_effector(_LaggingGimbal(time_constant=0.1)) + calisto_robust.add_controller(_command_pitch_after(1.0, 0.05)) + whole = _fly(calisto_robust, example_plain_env) + # Cut while the gimbal is still swinging toward its command + first = _fly(calisto_robust, example_plain_env, max_time=1.05) + second = _fly(calisto_robust, example_plain_env, initial_solution=first) + + assert second.t_initial == first.t_final + assert second.solution.controls.gimbal.pitch[0, 1] == 0.05 + before = np.array(first.solution["gimbal_angle"], dtype=float) + after = np.array(second.solution["gimbal_angle"], dtype=float) + assert 0.0 < before[-1, 1] < 0.05 + assert after[0, 1] == before[-1, 1] + angle = np.array(whole.solution["gimbal_angle"], dtype=float) + for t in (1.1, 1.5, 3.0): + assert np.interp(t, after[:, 0], after[:, 1]) == pytest.approx( + np.interp(t, angle[:, 0], angle[:, 1]), rel=1e-3 + ) + assert second.apogee == pytest.approx(whole.apogee, rel=1e-4) diff --git a/tests/integration/simulation/test_event.py b/tests/integration/simulation/test_event.py index 28586dbcc..90e1e7937 100644 --- a/tests/integration/simulation/test_event.py +++ b/tests/integration/simulation/test_event.py @@ -38,7 +38,7 @@ def _callback_return_time(context): - return {"time": context["time"]} + context.record(time=context["time"]) def _docs_root(): @@ -312,8 +312,6 @@ def test_commands_api_records_expected_payloads(): def test_core_event_builders_update_flight_state_and_commands(): """The built-in event builders should mutate the flight state as expected.""" - out_of_rail_event, apogee_event, impact_event = build_core_events() - flight = SimpleNamespace( env=SimpleNamespace(elevation=0.0), effective_1rl=1.0, @@ -335,19 +333,18 @@ def test_core_event_builders_update_flight_state_and_commands(): solution=_canonical_solution(_sample_state(0.0, 1.0), _sample_state(1.0, -1.0)), u_dot_generalized=lambda *_args, **_kwargs: "new-derivative", ) + out_of_rail_event, apogee_event, impact_event = build_core_events(flight) out_of_rail_state = _sample_state(0.5, 1.0) out_of_rail_state[1] = 1.0 - assert out_of_rail_trigger( - {"flight": flight, "canonical_state": out_of_rail_state[1:]} - ) + assert out_of_rail_trigger(flight, {"canonical_state": out_of_rail_state[1:]}) out_of_rail_callback( + flight, { - "flight": flight, "event": out_of_rail_event, "time": 0.5, "canonical_state": out_of_rail_state[1:], - } + }, ) assert flight.out_of_rail_time == pytest.approx(0.5) assert flight.out_of_rail_time_index == 1 @@ -357,16 +354,14 @@ def test_core_event_builders_update_flight_state_and_commands(): assert out_of_rail_event.commands.new_flight_phase is True assert out_of_rail_event.commands.new_flight_phase_name == "free_flight" - assert apogee_trigger( - {"flight": flight, "canonical_state": _sample_state(1.0, -1.0)[1:]} - ) + assert apogee_trigger(flight, {"canonical_state": _sample_state(1.0, -1.0)[1:]}) apogee_result = apogee_callback( + flight, { - "flight": flight, "event": apogee_event, "time": 1.0, "canonical_state": _sample_state(1.0, -1.0)[1:], - } + }, ) assert apogee_result is False assert flight.apogee_time == pytest.approx(1.0) @@ -380,14 +375,14 @@ def test_core_event_builders_update_flight_state_and_commands(): impact_state[2] = -3.0 impact_state[3] = -4.0 impact_state[6] = -4.0 - assert impact_trigger({"flight": flight, "canonical_state": impact_state[1:]}) + assert impact_trigger({"height_agl": impact_state[3]}) impact_callback( + flight, { - "flight": flight, "event": impact_event, "time": 2.0, "canonical_state": impact_state[1:], - } + }, ) assert flight.impact_time == pytest.approx(2.0) assert flight.x_impact == pytest.approx(2.0) @@ -397,17 +392,17 @@ def test_core_event_builders_update_flight_state_and_commands(): assert impact_event.commands._terminate is True assert out_of_rail_exact_time_function( - {"canonical_state": out_of_rail_state[1:], "flight": flight} + flight, {"canonical_state": out_of_rail_state[1:]} ) == pytest.approx(0.0) assert out_of_rail_exact_time_derivative( - {"canonical_state": out_of_rail_state[1:], "flight": flight} + flight, {"canonical_state": out_of_rail_state[1:]} ) == pytest.approx(0.0) assert apogee_event_exact_time_function( {"canonical_state": _sample_state(1.0, -1.0)[1:]} ) == pytest.approx(-1.0) assert impact_event_exact_time_function({"height_agl": -4.0}) == pytest.approx(-4.0) assert impact_event_exact_time_derivative( - {"canonical_state": impact_state[1:], "flight": flight} + {"canonical_state": impact_state[1:]} ) == pytest.approx(-4.0) @@ -427,9 +422,7 @@ def test_apogee_trigger_returns_false_without_complete_history( flight = SimpleNamespace(apogee_state=apogee_state, solution=solution) assert ( - apogee_trigger( - {"flight": flight, "canonical_state": _sample_state(1.0, -1.0)[1:]} - ) + apogee_trigger(flight, {"canonical_state": _sample_state(1.0, -1.0)[1:]}) is False ) @@ -438,7 +431,7 @@ def test_flight_with_disable_and_enable_examples_from_docs(): """The docs-style disable_on and enable_on examples should work in Flight.""" def my_callback(context): - return {"time": context["time"]} + context.record(time=context["time"]) def disable_above_altitude(context): return context["height_agl"] > 700.0 @@ -506,10 +499,8 @@ def test_flight_with_exact_time_example_from_docs(): """The docs-style exact-time event should be more precise than sampling.""" def altitude_trigger(context): - state = context["state"] - flight = context["flight"] target_altitude = context["event"].memory["target_altitude"] - return state[2] - flight.env.elevation > target_altitude + return context["height_agl"] > target_altitude def altitude_exact_time_function(context): return context["height_agl"] @@ -562,18 +553,18 @@ def altitude_exact_time_function(context): BALLISTIC_STATES = ("x", "y", "z", "vx", "vy", "vz") -def _ballistic_derivative(_flight, _t, u, post_processing=False): +def _ballistic_derivative(_flight, _t, x, _u, post_processing=False): """Free fall: position follows velocity, velocity follows gravity.""" if post_processing: return () - return [u[3], u[4], u[5], 0.0, 0.0, -GRAVITY] + return [x[3], x[4], x[5], 0.0, 0.0, -GRAVITY] -def _parafoil_derivative(_flight, _t, u, post_processing=False): +def _parafoil_derivative(_flight, _t, x, _u, post_processing=False): """Free fall that also turns, carrying a heading the canonical state lacks.""" if post_processing: return () - return [u[3], u[4], u[5], 0.0, 0.0, -GRAVITY, 0.5] + return [x[3], x[4], x[5], 0.0, 0.0, -GRAVITY, 0.5] BALLISTIC_DYNAMICS = _PhaseDynamics( @@ -586,7 +577,7 @@ def _parafoil_derivative(_flight, _t, u, post_processing=False): (*BALLISTIC_STATES, "heading"), # A heading is not a canonical state, so it cannot be picked out of the # state that ended the previous phase. The phase says where it starts. - initial_state=lambda _flight, _t, canonical: [*canonical[:6], 0.0], + initial_state=lambda _flight, _t, canonical, _previous: [*canonical[:6], 0.0], ) @@ -604,7 +595,6 @@ def switch(context): name=f"Switch to {phase_name}", sampling_rate=10, trigger_only_once=True, - changes_dynamics=True, ) return _docs_style_flight([switch_event]), switch_event @@ -616,7 +606,7 @@ def test_a_phase_narrower_than_the_canonical_state_flies(): ) solution = flight.solution - assert switch_event.callback_log, "the flight never switched dynamics" + assert switch_event.triggered_times, "the flight never switched dynamics" ballistic = solution.phases[-1] assert ballistic.name == "ballistic" assert ballistic.dynamics.states == BALLISTIC_STATES @@ -650,7 +640,7 @@ def test_a_phase_wider_than_the_canonical_state_flies(): ) solution = flight.solution - assert switch_event.callback_log, "the flight never switched dynamics" + assert switch_event.triggered_times, "the flight never switched dynamics" parafoil = solution.phases[-1] assert parafoil.dynamics.states == (*BALLISTIC_STATES, "heading") @@ -747,6 +737,104 @@ def fly(events): assert switched.az(fired + 0.5) < plain.az(fired + 0.5) - 1.0 +def _fly_calisto(rocket, environment, events, **options): + return Flight( + rocket=rocket, + environment=environment, + rail_length=5.2, + inclination=85, + heading=0, + custom_events=events, + **options, + ) + + +def _cutting_callback(calls): + """A callback that logs its time and cuts the solver step there, with a + command that changes nothing: switching on a surface that is already on.""" + + def callback(context): + calls.append(context["time"]) + surface = context.rocket.aerodynamic_surfaces.get_components()[0] + context.commands.activate_surface(surface) + + return callback + + +def test_an_event_that_cuts_every_step_flies_to_max_time( + calisto_robust, example_plain_env +): + """A solver step that runs to max_time and is cut back to the event's + sampling time goes on from the cut to max_time. + + On the pad the solver sees no motion until the thrust beats the weight, so + with max_time=8 and no max_time_step its first long step runs straight to + 8 s and the event cuts it back to 0.1 s. That flight used to end at 0.1 s. + """ + calls = [] + event = Event( + callback=_cutting_callback(calls), + sampling_rate=10, + name="Cuts every step", + ) + flight = _fly_calisto(calisto_robust, example_plain_env, [event], max_time=8) + + assert flight.t_final == pytest.approx(8.0) + assert flight.solution.raw_row(-1)[0] == pytest.approx(8.0) + assert len(calls) == pytest.approx(80, abs=1) + assert flight.z(8.0) - example_plain_env.elevation > 1000 + + +@pytest.mark.parametrize("time_overshoot", [True, False]) +def test_events_that_cut_the_step_at_the_same_time_all_run( + calisto_robust, example_plain_env, time_overshoot +): + calls = {"First": [], "Second": []} + + def cutting(name): + return Event( + callback=_cutting_callback(calls[name]), + trigger=lambda context: context["time"] > 2.0, + sampling_rate=10, + name=name, + ) + + _fly_calisto( + calisto_robust, + example_plain_env, + [cutting("First"), cutting("Second")], + time_overshoot=time_overshoot, + max_time=6, + ) + assert len(calls["First"]) == pytest.approx(40, abs=1) + assert calls["Second"] == calls["First"] + + +def test_an_event_checked_at_every_step_never_runs_past_the_flight( + calisto_robust, example_plain_env +): + """An event that happens at an exact time inside a solver step, such as + leaving the rail or the impact, takes the flight back to that time. The + events checked after it in the same step run there, not at the end of the + step that was cut, so their times never go backwards.""" + times, steps = [], [] + + def callback(context): + times.append(context["time"]) + steps.append(context.dt) + context.record(time=context["time"]) + + event = Event(callback=callback, name="Every step") + flight = _fly_calisto(calisto_robust, example_plain_env, [event], max_time=3) + + assert flight.out_of_rail_time in times + assert times == sorted(times) + assert all(step > 0 for step in steps if step is not None) + recorded = [time for time, _ in flight.records["Every step"].time] + assert recorded == times + assert times[-1] <= flight.t_final + + def _event_adding_a_follow_up(): """An event that, when it fires, adds a second event to the flight.""" @@ -816,19 +904,19 @@ def _flight_on_the_rail(*rows): def test_out_of_rail_index_is_the_row_of_the_exact_exit_time(exit_time, rows_left): """``out_of_rail_time_index`` is the row stored at the rail exit time, also when the exit is found at the start of the step and no row is added.""" - out_of_rail_event = build_core_events()[0] flight = _flight_on_the_rail( _sample_state(0.0, 1.0), _sample_state(1.0, 1.0), _sample_state(2.0, 1.0) ) + out_of_rail_event = build_core_events(flight)[0] exit_state = _sample_state(exit_time, 1.0)[1:] out_of_rail_callback( + flight, { - "flight": flight, "event": out_of_rail_event, "time": exit_time, "canonical_state": exit_state, - } + }, ) commands = out_of_rail_event.commands commands.exact_time = exit_time diff --git a/tests/integration/simulation/test_flight.py b/tests/integration/simulation/test_flight.py index 3865e0a86..181eae413 100644 --- a/tests/integration/simulation/test_flight.py +++ b/tests/integration/simulation/test_flight.py @@ -4,7 +4,7 @@ import numpy as np import pytest -from rocketpy import Flight, Rocket, SolidMotor +from rocketpy import AirBrakes, Flight, Rocket, SolidMotor from rocketpy.simulation.helpers.dynamics import FULL_POST_PROCESS_VARS plt.rcParams.update({"figure.max_open_warning": 0}) @@ -357,6 +357,29 @@ def test_flight_with_delayed_burn_leaves_rail(example_plain_env): assert flight.apogee - example_plain_env.elevation > 1000.0 +@pytest.mark.parametrize("options", [{"max_time": 8}, {"rtol": 1e-11}]) +def test_flight_leaves_the_rail_whatever_the_first_solver_steps( + calisto_robust, example_plain_env, options +): + """A rocket whose thrust starts from zero sits still at first, so the + solver's steps grow freely: with a short ``max_time`` or a tight ``rtol`` + one step used to go over the whole burn, and the rocket never left the + pad. The solver now stops at the time of maximum thrust.""" + flight = Flight( + rocket=calisto_robust, + environment=example_plain_env, + rail_length=5.2, + inclination=85, + heading=0, + terminate_on_apogee=True, + **options, + ) + + assert calisto_robust.motor.max_thrust_time in flight.time + assert 0 < flight.out_of_rail_time < 1 + assert flight.z(4.0) - example_plain_env.elevation > 500 + + @patch("matplotlib.pyplot.show") def test_rolling_flight( # pylint: disable=unused-argument mock_show, @@ -536,7 +559,7 @@ def test_the_rail_phase_reports_forces_but_no_angular_acceleration( heading=0, terminate_on_apogee=True, ) - rail = flight.solution.post.phase_values(0) + rail = flight.solution.phase_values(0) column = FULL_POST_PROCESS_VARS.index assert flight.solution.phases[0].dynamics.name == "rail" @@ -665,9 +688,11 @@ def test_freestream_speed_at_apogee(example_plain_env, calisto): atol=13 * [hard_atol], ) + # The value moves in its fifth digit with the solver's choice of steps assert np.isclose( test_flight.stream_velocity_x(test_flight.apogee_time), 0.463944387965394, + rtol=1e-4, atol=hard_atol, ) assert np.isclose( @@ -680,10 +705,14 @@ def test_freestream_speed_at_apogee(example_plain_env, calisto): assert np.isclose( test_flight.free_stream_speed(test_flight.apogee_time), 0.4639443879653988, + rtol=1e-4, atol=hard_atol, ) assert np.isclose( - test_flight.apogee_freestream_speed, 0.4639443879653988, atol=hard_atol + test_flight.apogee_freestream_speed, + 0.4639443879653988, + rtol=1e-4, + atol=hard_atol, ) @@ -769,19 +798,21 @@ def test_air_brakes_with_environment_parameter( # Verify controller was called and observed variables were stored # Controller is attached to the rocket, not the air brakes object - controllers = [c for c in calisto_robust._controllers if "AirBrakes" in c.name] + controllers = [c for c in flight.controllers if "AirBrakes" in c.name] assert len(controllers) > 0 controller = controllers[0] - assert len(controller.log) > 0 + # A positional controller keeps what it returns, other than None, in its + # observed_variables, on the wrapper that runs it + observed_variables = controller.controller_function.observed_variables + assert len(observed_variables) > 0 # Verify observed variables contain expected data (time, deployment_level, mach_number) - for observed in controller.log: - if observed is not None: - assert len(observed) == 3 - time, deployment_level, mach_number = observed - assert time >= 0 - assert 0 <= deployment_level <= 1 # Should be clamped - assert mach_number >= 0 + for observed in observed_variables: + assert len(observed) == 3 + time, deployment_level, mach_number = observed + assert time >= 0 + assert 0 <= deployment_level <= 1 # Should be clamped + assert mach_number >= 0 def test_air_brakes_serialization_with_environment( @@ -813,9 +844,11 @@ def test_air_brakes_serialization_with_environment( # Serialize the rocket rocket_dict = calisto_robust.to_dict() - # Verify serialization succeeded and contains air brakes data - assert "air_brakes" in rocket_dict - assert len(rocket_dict["air_brakes"]) > 0 + # Verify serialization succeeded and the air brakes are among the surfaces + assert any( + isinstance(surface, AirBrakes) + for surface, _ in rocket_dict["aerodynamic_surfaces"] + ) # Run a flight with the original rocket flight_original = Flight( @@ -832,10 +865,11 @@ def test_air_brakes_serialization_with_environment( assert flight_original.apogee > 0 -def test_backward_compatibility_5_parameter_controller( +def test_backward_compatibility_6_parameter_controller( calisto_robust, example_plain_env ): - """Test that old 5-parameter controllers still work (backward compatibility). + """Test that the 6-parameter controllers of v1.13 still work (backward + compatibility). Parameters ---------- @@ -845,8 +879,8 @@ def test_backward_compatibility_5_parameter_controller( Environment object for the simulation """ - def controller_5_params( # pylint: disable=unused-argument - time, sampling_rate, state, observed_variables, air_brakes + def controller_6_params( # pylint: disable=unused-argument + time, sampling_rate, state, state_history, observed_variables, air_brakes ): """Controller with the shortest supported positional signature.""" altitude = state[2] @@ -861,11 +895,11 @@ def controller_5_params( # pylint: disable=unused-argument air_brakes.deployment_level = min(0.5, max(0, vz / 100)) return None - # Add air brakes with old-style 5-parameter controller + # Add air brakes with old-style 6-parameter controller calisto_robust.parachutes = [] calisto_robust.add_air_brakes( drag_coefficient_curve="data/rockets/calisto/air_brakes_cd.csv", - controller_function=controller_5_params, + controller_function=controller_6_params, sampling_rate=10, clamp=True, ) @@ -885,12 +919,12 @@ def controller_5_params( # pylint: disable=unused-argument assert flight.apogee > 0 # Verify controller exists - controllers = [c for c in calisto_robust._controllers if "AirBrakes" in c.name] + controllers = [c for c in flight.controllers if "AirBrakes" in c.name] assert len(controllers) > 0 -def test_6_parameter_controller_with_sensors(calisto_robust, example_plain_env): - """Test that 6-parameter controllers (with sensors, no environment) work correctly. +def test_7_parameter_controller_with_sensors(calisto_robust, example_plain_env): + """Test that 7-parameter controllers (with sensors, no environment) work correctly. Parameters ---------- @@ -900,16 +934,17 @@ def test_6_parameter_controller_with_sensors(calisto_robust, example_plain_env): Environment object for the simulation """ - # Define a 6-parameter controller - def controller_6_params( # pylint: disable=unused-argument + # Define a 7-parameter controller + def controller_7_params( # pylint: disable=unused-argument time, sampling_rate, state, + state_history, observed_variables, air_brakes, sensors, ): - """Controller with 6 parameters (includes sensors, but not environment).""" + """Controller with 7 parameters (includes sensors, but not environment).""" altitude = state[2] vz = state[5] @@ -924,11 +959,11 @@ def controller_6_params( # pylint: disable=unused-argument return (time, air_brakes.deployment_level) - # Add air brakes with 6-parameter controller + # Add air brakes with 7-parameter controller calisto_robust.parachutes = [] calisto_robust.add_air_brakes( drag_coefficient_curve="data/rockets/calisto/air_brakes_cd.csv", - controller_function=controller_6_params, + controller_function=controller_7_params, sampling_rate=10, clamp=True, ) @@ -948,7 +983,7 @@ def controller_6_params( # pylint: disable=unused-argument assert flight.apogee > 0 -@pytest.mark.parametrize("param_count", [4, 8]) +@pytest.mark.parametrize("param_count", [5, 9]) def test_invalid_controller_parameter_count(calisto_robust, param_count): """Test that positional controllers with an invalid parameter count raise ValueError. Only 6, 7 or 8 positional arguments are supported. @@ -964,6 +999,7 @@ def test_invalid_controller_parameter_count(calisto_robust, param_count): "time", "sampling_rate", "state", + "state_history", "observed_variables", "air_brakes", "sensors", @@ -979,7 +1015,7 @@ def test_invalid_controller_parameter_count(calisto_robust, param_count): calisto_robust.parachutes = [] - with pytest.raises(ValueError, match="must have 5, 6, or 7"): + with pytest.raises(ValueError, match="must have 6, 7"): calisto_robust.add_air_brakes( drag_coefficient_curve="data/rockets/calisto/air_brakes_cd.csv", controller_function=invalid_controller, @@ -988,7 +1024,7 @@ def test_invalid_controller_parameter_count(calisto_robust, param_count): ) -@pytest.mark.parametrize("param_count", [5, 6, 7]) +@pytest.mark.parametrize("param_count", [6, 7, 8]) def test_deprecated_positional_controller(calisto_robust, param_count): """Test that positional controllers with a valid parameter count (6, 7 or 8) are accepted but emit a DeprecationWarning. @@ -1004,6 +1040,7 @@ def test_deprecated_positional_controller(calisto_robust, param_count): "time", "sampling_rate", "state", + "state_history", "observed_variables", "air_brakes", "sensors", @@ -1049,6 +1086,7 @@ def context_controller(context): # pylint: disable=unused-argument controller_function=context_controller, sampling_rate=10, clamp=True, + position=0.0, ) assert not any(issubclass(w.category, DeprecationWarning) for w in recwarn.list) @@ -1073,6 +1111,7 @@ def controller( # pylint: disable=unused-argument time, sampling_rate, state, + state_history, observed_variables, air_brakes, sensors, @@ -1165,7 +1204,7 @@ def controller_function(context): sampling_rate = context.sampling_rate state = context.state previous_state = context.previous_state - air_brakes = context.controlled.air_brakes + controls = context.controls environment = context.environment altitude_agl = context.height_agl @@ -1180,19 +1219,19 @@ def controller_function(context): if time < 3.9: return None + air_brakes = controls["AirBrakes"] + level = air_brakes.deployment_level previous_vz = previous_state.vz if previous_state is not None else vz if altitude_agl < 1500: air_brakes.deployment_level = 0 else: - new_level = air_brakes.deployment_level + 0.1 * vz + 0.01 * previous_vz**2 + new_level = level + 0.1 * vz + 0.01 * previous_vz**2 max_change = 0.2 / sampling_rate - new_level = max( - air_brakes.deployment_level - max_change, - min(air_brakes.deployment_level + max_change, new_level), + air_brakes.deployment_level = max( + level - max_change, min(level + max_change, new_level) ) - air_brakes.deployment_level = new_level - return (time, air_brakes.deployment_level, mach_number) + context.record(mach_number=mach_number) calisto_robust.parachutes = [] calisto_robust.add_air_brakes( @@ -1213,6 +1252,10 @@ def controller_function(context): assert flight.t_final > 0 assert flight.apogee > 0 + # the returned dict is recorded, from burnout on + mach = flight.records["AirBrakes Controller"].mach_number + assert mach[0][0] == pytest.approx(3.9, abs=0.1) + assert max(flight.solution.controls.air_brakes.deployment_level[:, 1]) > 0 def test_the_deprecated_stability_plot_saves_one_file_per_plot( diff --git a/tests/integration/test_rocket.py b/tests/integration/test_rocket.py index 194439322..338ad479c 100644 --- a/tests/integration/test_rocket.py +++ b/tests/integration/test_rocket.py @@ -51,7 +51,7 @@ def test_airfoil( @patch("matplotlib.pyplot.show") def test_air_brakes_clamp_on(mock_show, calisto_air_brakes_clamp_on): # pylint: disable=unused-argument """Test the air brakes class with clamp on configuration. This test checks - the basic attributes and the deployment_level setter. It also checks the + the basic attributes and the initial_deployment_level setter. It also checks the all_info method. Parameters @@ -70,14 +70,14 @@ def test_air_brakes_clamp_on(mock_show, calisto_air_brakes_clamp_on): # pylint: air_brakes_clamp_on.reference_area == calisto_air_brakes_clamp_on.radius**2 * np.pi ) - air_brakes_clamp_on.deployment_level = 0.5 - assert air_brakes_clamp_on.deployment_level == 0.5 - air_brakes_clamp_on.deployment_level = 1.5 - assert air_brakes_clamp_on.deployment_level == 1 - air_brakes_clamp_on.deployment_level = -1 - assert air_brakes_clamp_on.deployment_level == 0 - air_brakes_clamp_on.deployment_level = 0 - assert air_brakes_clamp_on.deployment_level == 0 + air_brakes_clamp_on.initial_deployment_level = 0.5 + assert air_brakes_clamp_on.initial_deployment_level == 0.5 + air_brakes_clamp_on.initial_deployment_level = 1.5 + assert air_brakes_clamp_on.initial_deployment_level == 1 + air_brakes_clamp_on.initial_deployment_level = -1 + assert air_brakes_clamp_on.initial_deployment_level == 0 + air_brakes_clamp_on.initial_deployment_level = 0 + assert air_brakes_clamp_on.initial_deployment_level == 0 assert air_brakes_clamp_on.all_info() is None @@ -87,7 +87,7 @@ def test_air_brakes_clamp_off( # pylint: disable=unused-argument mock_show, calisto_air_brakes_clamp_off ): """Test the air brakes class with clamp off configuration. This test checks - the basic attributes and the deployment_level setter. It also checks the + the basic attributes and the initial_deployment_level setter. It also checks the all_info method. Parameters @@ -107,14 +107,14 @@ def test_air_brakes_clamp_off( # pylint: disable=unused-argument == calisto_air_brakes_clamp_off.radius**2 * np.pi ) - air_brakes_clamp_off.deployment_level = 0.5 - assert air_brakes_clamp_off.deployment_level == 0.5 - air_brakes_clamp_off.deployment_level = 1.5 - assert air_brakes_clamp_off.deployment_level == 1.5 - air_brakes_clamp_off.deployment_level = -1 - assert air_brakes_clamp_off.deployment_level == -1 - air_brakes_clamp_off.deployment_level = 0 - assert air_brakes_clamp_off.deployment_level == 0 + air_brakes_clamp_off.initial_deployment_level = 0.5 + assert air_brakes_clamp_off.initial_deployment_level == 0.5 + air_brakes_clamp_off.initial_deployment_level = 1.5 + assert air_brakes_clamp_off.initial_deployment_level == 1.5 + air_brakes_clamp_off.initial_deployment_level = -1 + assert air_brakes_clamp_off.initial_deployment_level == -1 + air_brakes_clamp_off.initial_deployment_level = 0 + assert air_brakes_clamp_off.initial_deployment_level == 0 assert air_brakes_clamp_off.all_info() is None diff --git a/tests/unit/control/test_continuous_controller.py b/tests/unit/control/test_continuous_controller.py new file mode 100644 index 000000000..b09a2458c --- /dev/null +++ b/tests/unit/control/test_continuous_controller.py @@ -0,0 +1,533 @@ +"""Continuous controllers: control laws evaluated inside the equations of +motion, at every instant. They use stand-ins for the rocket and the flight, +so no simulation is run.""" + +import json +from types import SimpleNamespace + +import pytest + +from rocketpy import ContinuousController, GenericSurface +from rocketpy._encoders import RocketPyDecoder, RocketPyEncoder +from rocketpy.control import FlightConditions +from rocketpy.control.controllable import ForceEffector, ThrustEffector +from rocketpy.simulation.events.views import ControlsView +from rocketpy.simulation.helpers.dynamics import ( + CANONICAL_STATE_NAMES, + PARACHUTE_DYNAMICS, + SIX_DOF_DYNAMICS, + _PhaseDynamics, + _with_controllables, +) + +# What FlightConditions reads of a flight +_FLIGHT = SimpleNamespace(rocket=None, env=None) + + +def _canards(limits=(-0.2, 0.2)): + return GenericSurface( + 0.01, + 0.1, + {"cl": lambda mach, deflection: deflection}, + name="Canards", + controls=("deflection",), + control_limits={"deflection": limits}, + ) + + +def _rocket(*controllables): + """A rocket with these controllables, sorted as Rocket sorts them.""" + laws = tuple(c for c in controllables if isinstance(c, ContinuousController)) + parts = tuple(c for c in controllables if c not in laws) + return SimpleNamespace( + _parts_with_states=tuple(p for p in parts if p._acts_on_its_own()), + _continuous_controllers=laws, + effectors=SimpleNamespace( + get_components=lambda: [ + p for p in parts if isinstance(p, (ThrustEffector, ForceEffector)) + ] + ), + controllables=controllables, + ) + + +def _reads(flight, t, u, controls, post_processing=False): # pylint: disable=unused-argument + """A phase whose derivative and post-process value are the deflection + it read.""" + if post_processing: + return [controls["canards.deflection"]] + return [controls["canards.deflection"], *[0.0] * 12] + + +_PHASE = _PhaseDynamics("toy", _reads, CANONICAL_STATE_NAMES, post_process_vars=("d",)) + + +def _roll_law(states, controls, conditions): # pylint: disable=unused-argument + controls.canards.deflection = -0.05 * conditions.state.w3 + + +def _state(roll_rate): + return [0.0] * 12 + [roll_rate] + + +def test_a_law_writes_the_controls_the_physics_reads(): + canards = _canards() + extended = _with_controllables( + _PHASE, _rocket(canards, ContinuousController(_roll_law)) + ) + assert extended.states == CANONICAL_STATE_NAMES + controls = {"canards.deflection": 0.0} + assert extended.derivative(_FLIGHT, 0.0, _state(2.0), controls)[0] == -0.1 + # In the post-processed values too, and what the law wrote is recorded + # with them, as ``controls..`` + assert extended.post_process_vars == ("d", "controls.canards.deflection") + assert extended.derivative( + _FLIGHT, 0.0, _state(2.0), controls, post_processing=True + ) == [-0.1, -0.1] + # The flight's own control inputs are left as they were + assert controls == {"canards.deflection": 0.0} + + +def test_a_parachute_descent_reads_the_controls_only_through_an_added_state(): + """Its equations read no control input, so a write to one does not stop + the solver, unless the rocket has a state that follows the controls.""" + assert SIX_DOF_DYNAMICS.reads_controls + assert not PARACHUTE_DYNAMICS.reads_controls + bare = _PhaseDynamics("bare", _reads, CANONICAL_STATE_NAMES, reads_controls=False) + # A law without states adds nothing that is integrated + law_only = _with_controllables( + bare, _rocket(_canards(), ContinuousController(_roll_law)) + ) + assert not law_only.reads_controls + # A part with a state of its own, like a servo's angle, follows them + assert _with_controllables(bare, _rocket(_servo())).reads_controls + + +def test_what_a_law_wrote_is_recorded_even_by_a_phase_with_no_post_values(): + bare = _PhaseDynamics("bare", _reads, CANONICAL_STATE_NAMES) + extended = _with_controllables( + bare, _rocket(_canards(), ContinuousController(_roll_law)) + ) + assert extended.post_process_vars == ("controls.canards.deflection",) + assert extended.post_process_at( + _FLIGHT, 0.0, _state(2.0), {"canards.deflection": 0.0} + ) == [-0.1] + # Without a law nothing is recorded: the sampled values stand + assert _with_controllables(_PHASE, _rocket(_canards())).post_process_vars == ("d",) + + +def test_a_law_write_is_kept_inside_the_limits(): + clamped = _with_controllables( + _PHASE, _rocket(_canards(), ContinuousController(_roll_law)) + ) + assert ( + clamped.derivative(_FLIGHT, 0.0, _state(10.0), {"canards.deflection": 0})[0] + == -0.2 + ) + free = _with_controllables( + _PHASE, _rocket(_canards(limits=None), ContinuousController(_roll_law)) + ) + assert ( + free.derivative(_FLIGHT, 0.0, _state(10.0), {"canards.deflection": 0})[0] + == -0.5 + ) + + +@pytest.mark.parametrize("limits", [(-0.2, 0.2), None]) +def test_a_law_that_writes_a_nan_is_refused(limits): + """With limits or without, the error names the control and the + controller, where the value was written.""" + + def divides_by_zero(states, controls, conditions): # pylint: disable=unused-argument + controls.canards.deflection = float("nan") + + extended = _with_controllables( + _PHASE, + _rocket( + _canards(limits=limits), + ContinuousController(divides_by_zero, name="Roll law"), + ), + ) + with pytest.raises( + ValueError, + match="'canards.deflection' was set to nan by the continuous " + "controller 'Roll law'", + ): + extended.derivative(_FLIGHT, 0.0, _state(1.0), {"canards.deflection": 0}) + + +def test_a_law_that_writes_an_infinite_value_is_limited_or_refused(): + def runs_away(states, controls, conditions): # pylint: disable=unused-argument + controls.canards.deflection = float("inf") + + def derivative(limits): + extended = _with_controllables( + _PHASE, _rocket(_canards(limits=limits), ContinuousController(runs_away)) + ) + return extended.derivative(_FLIGHT, 0.0, _state(1.0), {"canards.deflection": 0}) + + assert derivative((-0.2, 0.2))[0] == 0.2 + with pytest.raises(ValueError, match="'canards.deflection' was set to inf"): + derivative(None) + + +def test_a_law_cannot_invent_a_control_input(): + def wrong(states, controls, conditions): # pylint: disable=unused-argument + controls.canards.deflexion = 0.1 + + extended = _with_controllables( + _PHASE, _rocket(_canards(), ContinuousController(wrong)) + ) + with pytest.raises(AttributeError, match="no control named 'deflexion'"): + extended.derivative(_FLIGHT, 0.0, _state(0.0), {"canards.deflection": 0}) + + +def test_a_law_sees_the_control_inputs_and_not_the_states(): + def reads(states, controls, conditions): # pylint: disable=unused-argument + assert list(controls) == ["Canards"] + assert "roll_pi_integral" not in controls + assert "roll_pi" not in controls + + extended = _with_controllables( + _PHASE, + _rocket(_canards(), _RollPI(name="Roll PI"), ContinuousController(reads)), + ) + extended.derivative(_FLIGHT, 0.0, [*_state(0.0), 0.0], {"canards.deflection": 0}) + + +def test_a_law_reads_what_a_sampled_controller_wrote(): + """The law sees every channel, including another controller's output, + and a law that leaves a channel alone leaves the sampled value in force.""" + + def tracking(states, controls, conditions): # pylint: disable=unused-argument + controls.canards.deflection = ( + controls.guidance.rate_setpoint - conditions.state.w3 + ) + + setpoint = ContinuousController.__mro__[1]("Guidance", ("rate_setpoint",)) + extended = _with_controllables( + _PHASE, + _rocket(_canards(limits=(-1, 1)), setpoint, ContinuousController(tracking)), + ) + controls = {"canards.deflection": 0.0, "guidance.rate_setpoint": 0.5} + assert extended.derivative(_FLIGHT, 0.0, _state(0.2), controls)[0] == pytest.approx( + 0.3 + ) + + +class _RollPI(ContinuousController): + states = ("integral",) + + def state_derivative(self, states, commands, conditions): + return [0.5 - conditions.state.w3] + + def law(self, states, controls, conditions): + controls.canards.deflection = 0.1 * (0.5 - conditions.state.w3) + states[0] + + +def _roll_pi(): + """The same PI law as ``_RollPI``, built from functions.""" + + def law(states, controls, conditions): + controls.canards.deflection = 0.1 * (0.5 - conditions.state.w3) + states[0] + + return ContinuousController( + law, + states=("integral",), + state_derivative=lambda states, controls, conditions: [ + 0.5 - conditions.state.w3 + ], + name="Roll PI", + ) + + +@pytest.mark.parametrize("build", [_roll_pi, lambda: _RollPI(name="Roll PI")]) +def test_a_law_with_states_is_integrated_with_the_flight(build): + extended = _with_controllables(SIX_DOF_DYNAMICS, _rocket(_canards(), build())) + assert extended.states[-1] == "roll_pi_integral" + toy = _with_controllables(_PHASE, _rocket(_canards(), build())) + u = [*_state(0.2), 0.04] # the integral so far + derivative = toy.derivative(_FLIGHT, 0.0, u, {"canards.deflection": 0.0}) + assert derivative[0] == pytest.approx(0.1 * 0.3 + 0.04) + assert derivative[-1] == pytest.approx(0.3) + + +class _Servo(GenericSurface): + """Canards that reach the commanded deflection with a first-order lag.""" + + states = ("angle",) + + def state_derivative(self, states, commands, conditions): + return [(commands[0] - states[0]) / 0.05] + + def actual_controls(self, states, commands, conditions): + return [states[0]] + + +def _servo(): + return _Servo( + 0.01, + 0.1, + {}, + name="Canards", + controls=("deflection",), + control_limits={"deflection": (-0.2, 0.2)}, + ) + + +def test_a_law_runs_before_the_parts_map_their_commands(): + """A servo lag reads the command the law wrote, not the sampled value.""" + extended = _with_controllables( + _PHASE, _rocket(_servo(), ContinuousController(_roll_law)) + ) + u = [*_state(2.0), 0.03] # the servo's angle + derivative = extended.derivative(_FLIGHT, 0.0, u, {"canards.deflection": 0.0}) + assert derivative[0] == 0.03 # the physics acts with the angle reached + assert derivative[-1] == pytest.approx( + (-0.1 - 0.03) / 0.05 + ) # toward the law's command + + +def test_a_controller_state_follows_the_commands_and_not_the_angle_reached(): + """The derivative of a controller's state reads the control inputs as the + laws left them, kept inside their limits: a servo's angle does not + replace them. The controllers' states come before the other + controllables', in the order the two are worked out.""" + seen = [] + + def law(states, controls, conditions): # pylint: disable=unused-argument + controls.canards.deflection = -0.5 # beyond the limit of -0.2 + + def rate(states, commands, conditions): # pylint: disable=unused-argument + seen.append(commands.canards.deflection) + return [1.5] + + controller = ContinuousController( + law, states=("integral",), state_derivative=rate, name="Roll PI" + ) + extended = _with_controllables(_PHASE, _rocket(_servo(), controller)) + assert extended.states[13:] == ("roll_pi_integral", "canards_angle") + u = [*_state(0.0), 0.0, 0.03] # the integral, then the servo's angle + derivative = extended.derivative(_FLIGHT, 0.0, u, {"canards.deflection": 0.0}) + assert seen == [-0.2] + assert derivative[0] == 0.03 # the physics acts with the angle reached + assert derivative[13:] == [1.5, pytest.approx((-0.2 - 0.03) / 0.05)] + # Seeded in the same order, each from its controllable + assert extended.initial_state(None, 0.0, list(range(13)))[13:] == [0.0, 0.0] + + +def _still(flight, t, u, controls, post_processing=False): # pylint: disable=unused-argument + """A phase whose states do not change, and that reports one value.""" + return [0.0] if post_processing else [0.0] * len(u) + + +def _watching(phase_states): + """Return the dynamics of a phase with ``phase_states`` flown with a law, + and the list of what the law read of the conditions at each call.""" + seen = [] + + def law(states, controls, conditions): # pylint: disable=unused-argument + state = conditions.state + seen.append((state.z, state.vz, state.w3, conditions.height_agl)) + + phase = _PhaseDynamics("other", _still, phase_states, post_process_vars=("d",)) + return _with_controllables(phase, _rocket(ContinuousController(law))), seen + + +# Stands for a flight on ground 100 m above sea level +_GROUND = SimpleNamespace(elevation=100.0) + + +@pytest.mark.parametrize( + "phase_states", + [(*CANONICAL_STATE_NAMES, "fuel"), ("fuel", *reversed(CANONICAL_STATE_NAMES))], +) +def test_a_law_reads_the_standard_states_in_a_phase_with_more_states(phase_states): + seen = [] + + def law(states, controls, conditions): # pylint: disable=unused-argument + state = conditions.state + seen.append((state.z, state.vz, state.w3, state.fuel, conditions.height_agl)) + + phase = _PhaseDynamics("more", _still, phase_states) + extended = _with_controllables(phase, _rocket(ContinuousController(law))) + values = {"z": 350.0, "vz": 3.0, "w3": 0.5, "fuel": 7.0} + u = [values.get(name, 0.0) for name in phase_states] + flight = SimpleNamespace(rocket=None, env=_GROUND) + assert extended.derivative(flight, 0.0, u, {}) == [0.0] * 14 + assert seen == [(350.0, 3.0, 0.5, 7.0, 250.0)] + + +def test_a_law_reads_the_standard_states_in_a_phase_with_fewer_states(): + """The states the phase does not follow are the ones it began with, + which the bound dynamics carry for the phase.""" + extended, seen = _watching(("x", "y", "z", "vx", "vy", "vz")) + flight = SimpleNamespace(rocket=None, env=_GROUND, _controls={}) + u = [0.0, 0.0, 350.0, 0.0, 0.0, 3.0] + bound = extended.bind(flight) + with pytest.raises(ValueError, match="Pass start_canonical"): + bound(0.0, u) + began = bound.started_from([0.0] * 12 + [0.5]) + assert began(0.0, u) == [0.0] * 6 + assert began.post_process_at(0.0, u, {}) == [0.0] + # Another phase of the same dynamics starts from its own state + later = bound.started_from([0.0] * 12 + [0.25]) + assert later.derivative_at(0.0, u, {}) == [0.0] * 6 + assert seen == [(350.0, 3.0, 0.5, 250.0)] * 2 + [(350.0, 3.0, 0.25, 250.0)] + + +def test_a_phase_that_was_not_extended_is_not_given_where_it_began(): + phase = _PhaseDynamics("bare", _still, ("x", "y", "z"), post_process_vars=("d",)) + bound = phase.bind(SimpleNamespace(rocket=_rocket())) + assert bound.started_from([0.0] * 13) is bound + assert bound.post_process_at(0.0, [0.0] * 3, {}) == [0.0] + + +def test_the_equations_are_handed_the_conditions_when_the_rocket_has_effectors(): + """A derivative that names ``conditions`` gets the same object the laws + and the controllables were given; one that does not is called as before.""" + handed = [] + + def with_conditions(flight, t, u, controls, conditions=None): # pylint: disable=unused-argument + handed.append(conditions) + return [0.0] * 13 + + def without(flight, t, u, controls): # pylint: disable=unused-argument + return [0.0] * 13 + + class Pusher(ForceEffector): + """An effector that pushes with no force.""" + + def force_and_moment(self, controls, conditions): + return [0, 0, 0], [0, 0, 0] + + rocket = _rocket(Pusher(name="Pusher")) + flight = SimpleNamespace(rocket=None, env=_GROUND) + extended = _with_controllables( + _PhaseDynamics("c", with_conditions, CANONICAL_STATE_NAMES), rocket + ) + assert extended.derivative(flight, 0.0, _state(0.5), {}) == [0.0] * 13 + assert handed[0].state.w3 == 0.5 + plain = _with_controllables( + _PhaseDynamics("p", without, CANONICAL_STATE_NAMES), rocket + ) + assert plain.derivative(flight, 0.0, _state(0.5), {}) == [0.0] * 13 + # A rocket with nothing to add is flown by the phase as it is + bare = _PhaseDynamics("b", with_conditions, CANONICAL_STATE_NAMES) + assert _with_controllables(bare, _rocket()) is bare + + +def test_a_continuous_controller_with_states_needs_no_law(): + """An observer only integrates its states and writes no controls.""" + observer = ContinuousController( + states=("w3_hat",), + state_derivative=lambda states, controls, conditions: [ + 20.0 * (conditions.state.w3 - states[0]) + ], + name="Observer", + ) + assert observer.law_function is None + extended = _with_controllables(_PHASE, _rocket(_canards(), observer)) + controls = {"canards.deflection": 0.1} + derivative = extended.derivative(_FLIGHT, 0.0, [*_state(2.0), 0.5], controls) + assert derivative[-1] == pytest.approx(20.0 * (2.0 - 0.5)) + assert controls == {"canards.deflection": 0.1} + + +def test_a_continuous_controller_checks_its_law(): + with pytest.raises(TypeError, match="needs a law"): + ContinuousController() + with pytest.raises(TypeError, match="callable"): + ContinuousController("not a function") + with pytest.raises( + TypeError, match="law of 'Continuous Controller' must take 3 arguments" + ): + ContinuousController(lambda states, controls: None) + with pytest.raises(TypeError, match="needs a state_derivative"): + ContinuousController(_roll_law, states=("integral",)) + with pytest.raises( + TypeError, match="state_derivative of 'Continuous Controller' must take" + ): + ContinuousController(_roll_law, states=("x",), state_derivative=lambda c: [0]) + with pytest.raises(ValueError, match="letters, digits and underscores"): + ContinuousController( + _roll_law, states=("bad name",), state_derivative=_roll_law + ) + assert ContinuousController(_roll_law).controls == () + assert ContinuousController(_roll_law).states == () + assert _RollPI(name="Roll PI").states == ("integral",) + + +def test_two_parts_cannot_share_a_state_name(calisto): + calisto.add_controller(_RollPI(name="Roll PI")) + with pytest.raises(ValueError, match="state named 'roll_pi_integral'"): + calisto.add_controller(_RollPI(name="Roll PI")) + + +def test_a_rocket_keeps_its_continuous_controllers(calisto): + law = ContinuousController(_roll_law, name="Roll Law") + calisto.add_controller(law) + assert calisto.continuous_controllers == (law,) + assert calisto.controllers == () + assert calisto.control_names == () + assert law not in calisto.controllables + with pytest.raises(TypeError, match="ThrustEffector or ForceEffector"): + calisto.add_effector(ContinuousController(_roll_law)) + + +def test_a_continuous_controller_is_saved_and_loaded(calisto): + calisto.add_controller(ContinuousController(_roll_law, name="Roll Law")) + loaded = json.loads(json.dumps(calisto, cls=RocketPyEncoder), cls=RocketPyDecoder) + (law,) = loaded.continuous_controllers + assert isinstance(law, ContinuousController) and law.name == "Roll Law" + controls = {"canards.deflection": 0.0} + view = ControlsView(controls) + law.law((), view, FlightConditions(None, None, 0.0, _state(2.0))) + assert controls == {"canards.deflection": -0.1} + text = json.dumps(calisto, cls=RocketPyEncoder, allow_pickle=False) + with pytest.warns(UserWarning, match="'Roll Law' could not be loaded"): + loaded = json.loads(text, cls=RocketPyDecoder) + assert loaded.continuous_controllers == () + + +def test_one_state_name_given_alone_is_one_state(): + controller = ContinuousController( + states="integral", state_derivative=lambda s, c, f: [0.0] + ) + assert controller.states == ("integral",) + + +def test_a_state_derivative_without_states_is_refused(): + with pytest.raises(ValueError, match="no states"): + ContinuousController( + lambda s, c, f: None, state_derivative=lambda s, c, f: [0.0] + ) + + +def test_info_prints_the_functions_and_the_states(capsys): + def roll_law(states, controls, conditions): # pylint: disable=unused-argument + return None + + controller = ContinuousController( + roll_law, + states=("integral",), + state_derivative=lambda s, c, f: [0.0], + name="Roll Law", + ) + controller.info() + out = capsys.readouterr().out + assert "ContinuousController: Roll Law" in out + assert "Control law: roll_law" in out and "States: integral" in out + + +def test_an_effector_prints_its_controls_and_limits(capsys): + effector = ForceEffector( + lambda on, conditions: ([0, 0, on], [0, 0, 0]), + controls=("on",), + control_limits={"on": (0, 1)}, + name="Thruster", + ) + effector.all_info() + out = capsys.readouterr().out + assert "ForceEffector: Thruster" in out + assert "Control on: starts at 0.0, from 0 to 1" in out diff --git a/tests/unit/control/test_control_signal.py b/tests/unit/control/test_control_signal.py new file mode 100644 index 000000000..e9ce23f42 --- /dev/null +++ b/tests/unit/control/test_control_signal.py @@ -0,0 +1,833 @@ +"""Unit tests for a flight's control inputs: a dictionary from channel name to +value. They use stand-ins for the flight, so no simulation is run.""" + +from types import SimpleNamespace + +import numpy as np +import pytest + +from rocketpy import ForceEffector, GenericSurface +from rocketpy.control._helpers import check_writes, initial_controls, limited_value +from rocketpy.control.controllable import Controllable +from rocketpy.simulation.events import Event +from rocketpy.simulation.events.commands import Commands +from rocketpy.simulation.events.event_context import EventContext +from rocketpy.simulation.events.event_execution import ( + call_event, + rewind, + save_for_rollback, +) +from rocketpy.simulation.events.views import ControlsView +from rocketpy.simulation.helpers.dynamics import ( + PARACHUTE_DYNAMICS, + SIX_DOF_DYNAMICS, +) +from rocketpy.simulation.helpers.flight_derivatives import ( + u_dot_generalized, +) +from rocketpy.tools import snake_case_key + + +class Gimbal(Controllable): + """A minimal controllable with controls that is not a surface.""" + + def __init__(self, name="Gimbal"): + super().__init__( + name, + ("pitch", "yaw"), + control_defaults={"pitch": 0.0, "yaw": 0.01}, + control_limits={"pitch": (-0.1, 0.1)}, + ) + + +def _surface(name, **kwargs): + return GenericSurface(1.0, 1.0, {}, name=name, **kwargs) + + +def _canard(name="Canards", **kwargs): + return _surface( + name, + controls=("deflection",), + control_limits={"deflection": (-0.2, 0.2)}, + **kwargs, + ) + + +# --------------------------------------------------------------------------- +# Controllables with controls +# --------------------------------------------------------------------------- + + +def test_surfaces_and_effectors_are_controllable(): + effector = ForceEffector(lambda conditions: ([0, 0, 0], [0, 0, 0])) + for controllable in (_surface("Fins"), _canard(), Gimbal(), effector): + assert isinstance(controllable, Controllable) + controllable._check_controls() + + +def test_an_object_that_is_not_controllable_is_refused(calisto): + class LookAlike: # pylint: disable=too-few-public-methods + """Has what a controllable has, without being one.""" + + name = "Look Alike" + controls = () + control_defaults = {} + control_limits = {} + + for controllable in (object(), LookAlike()): + with pytest.raises(TypeError, match="not one of RocketPy's controllables"): + calisto._check_new_controllables(controllable) + + +def test_a_controllable_checks_its_controls_when_built(): + with pytest.raises(ValueError, match="more than once"): + Controllable("Gimbal", ("pitch", "pitch")) + with pytest.raises(ValueError, match="not among its controls"): + Controllable("Gimbal", ("pitch",), control_defaults={"yaw": 0}) + with pytest.raises(ValueError, match="must not be larger"): + Controllable("Gimbal", ("pitch",), control_limits={"pitch": (1, -1)}) + + +@pytest.mark.parametrize( + "change, error, match", + [ + ({"controls": ("pitch", "pitch")}, ValueError, "more than once"), + ({"controls": ("pitch", "yaw", "roll")}, ValueError, "'roll' .* no default"), + ({"controls": ("pitch", "2yaw")}, ValueError, "must be made of letters"), + ({"control_defaults": {"pitch": "up", "yaw": 0}}, TypeError, "a number"), + ( + {"control_limits": {"pitch": (0.1, -0.1), "yaw": None}}, + ValueError, + "must not be larger", + ), + ({"control_limits": {"pitch": 0.1, "yaw": None}}, ValueError, "low, high"), + ( + {"control_defaults": {"pitch": 0, "yaw": 0, "roll": 0}}, + ValueError, + "not among its controls", + ), + ], +) +def test_a_wrong_part_is_refused(change, error, match): + gimbal = Gimbal() + for name, value in change.items(): + setattr(gimbal, name, value) + with pytest.raises(error, match=match): + gimbal._check_controls() + + +# --------------------------------------------------------------------------- +# Channel names +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "name, key", + [ + ("Canards", "canards"), + ("AirBrakes", "air_brakes"), + ("calisto_nose_cone", "calisto_nose_cone"), + ("TVCGimbal", "tvc_gimbal"), + ("Fin #2 (left)", "fin_2_left"), + ("1st stage fins", "controllable_1st_stage_fins"), + ("", "controllable"), + ], +) +def test_a_key_is_the_name_in_snake_case(name, key): + assert snake_case_key(name) == key + + +def test_only_parts_with_controls_get_channels(): + canard, gimbal, fins = _canard(), Gimbal(), _surface("Fins") + _, channels, _ = initial_controls([canard, fins, gimbal]) + assert channels == { + canard: ("canards.deflection",), + gimbal: ("gimbal.pitch", "gimbal.yaw"), + } + + +def test_two_parts_with_controls_and_the_same_key_are_refused(): + with pytest.raises(ValueError, match="'Canards' and 'canards' both"): + initial_controls([_canard("Canards"), _canard("canards")]) + # surfaces without controls may share any name + initial_controls([_canard("Fins"), _surface("Fins"), _surface("Fins")]) + + +def test_a_flight_starts_with_every_channel_at_its_default(): + canard, gimbal = _canard(control_defaults={"deflection": 0.1}), Gimbal() + controls, channels, limits = initial_controls([canard, _surface("Fins"), gimbal]) + + assert controls == { + "canards.deflection": 0.1, + "gimbal.pitch": 0.0, + "gimbal.yaw": 0.01, + } + assert channels[gimbal] == ("gimbal.pitch", "gimbal.yaw") + assert limits["canards.deflection"] == (-0.2, 0.2) + assert limits["gimbal.yaw"] is None + # a rocket without controls flies with no channels + assert initial_controls([_surface("Fins")]) == ({}, {}, {}) + + +# --------------------------------------------------------------------------- +# Checking writes +# --------------------------------------------------------------------------- + + +def _controls(*controllables): + controls, _, limits = initial_controls(controllables) + return controls, limits + + +def test_a_write_outside_the_limits_is_clamped(): + controls, limits = _controls(_canard(), Gimbal()) + before = dict(controls) + + controls["canards.deflection"] = 0.5 + controls["gimbal.yaw"] = -3.0 # no limits + assert check_writes(controls, before, limits) == { + "canards.deflection": 0.2, + "gimbal.yaw": -3.0, + } + assert controls["canards.deflection"] == 0.2 + assert controls["gimbal.yaw"] == -3.0 + + before = dict(controls) + controls["gimbal.pitch"] = 0.5 + assert check_writes(controls, before, limits) == {"gimbal.pitch": 0.1} + assert controls["gimbal.pitch"] == 0.1 + + +def test_writing_the_same_value_changes_nothing(): + controls, limits = _controls(_canard()) + before = dict(controls) + controls["canards.deflection"] = 0.0 + assert check_writes(controls, before, limits) == {} + + +def test_a_write_beyond_the_limit_the_control_sits_at_changes_nothing(): + """A saturated controller keeps writing past the limit: the control stays + at the limit, so the trajectory does not change and no step is cut.""" + controls, limits = _controls(_canard()) + controls["canards.deflection"] = 0.2 + before = dict(controls) + controls["canards.deflection"] = 0.7 + assert check_writes(controls, before, limits) == {} + assert controls["canards.deflection"] == 0.2 + + +@pytest.mark.parametrize( + "value, limits", + [ + (float("nan"), (-0.2, 0.2)), + (float("nan"), None), + (float("inf"), None), + (float("-inf"), None), + ], +) +def test_a_value_that_is_not_a_finite_number_is_refused(value, limits): + with pytest.raises(ValueError, match="'canards.deflection' was set to"): + limited_value(value, limits, "canards.deflection") + + +def test_an_infinite_value_goes_to_the_limit_of_its_side(): + assert limited_value(float("inf"), (-0.2, 0.2)) == 0.2 + assert limited_value(float("-inf"), (-0.2, 0.2)) == -0.2 + + +@pytest.mark.parametrize("name", ["canards.deflection", "gimbal.yaw"]) +def test_a_nan_written_to_a_control_is_refused_and_undone(name): + """With limits or without, the error names the control and what wrote it, + and the controls are again what they were before the callback.""" + controls, limits = _controls(_canard(), Gimbal()) + before = dict(controls) + controls["gimbal.pitch"] = 0.05 + controls[name] = float("nan") + + with pytest.raises(ValueError, match=f"{name!r} was set to nan by 'Loop'"): + check_writes(controls, before, limits, "Loop") + + assert controls == before + + +def test_a_control_cannot_start_at_a_value_that_is_not_a_number(): + with pytest.raises(ValueError, match="'deflection' was set to nan"): + _canard(control_defaults={"deflection": float("nan")}) + + +def test_a_misspelled_channel_is_refused_and_undone(): + controls, limits = _controls(_canard()) + before = dict(controls) + controls["canard.deflection"] = 0.1 + with pytest.raises(KeyError, match="no control input 'canard.deflection'"): + check_writes(controls, before, limits) + assert controls == before + + del controls["canards.deflection"] + with pytest.raises(KeyError, match="cannot be removed"): + check_writes(controls, before, limits) + assert controls == before + + +def test_a_controllable_is_found_by_its_name_or_by_itself(): + canards, gimbal = _canard(), Gimbal(name="Main Gimbal") + controls, _ = _controls(canards, gimbal) + view = ControlsView(controls, (canards, gimbal)) + + view[canards].deflection = 0.1 + view["Main Gimbal"].yaw = 0.02 + assert controls["canards.deflection"] == 0.1 + assert controls["main_gimbal.yaw"] == 0.02 + assert view[gimbal].pitch == view.main_gimbal.pitch == 0.0 + assert list(view) == ["Canards", "Main Gimbal"] and len(view) == 2 + assert "Main Gimbal" in view and "main_gimbal" not in view + + with pytest.raises(TypeError, match="not the controllable itself"): + view["Canards"] = 0.1 + with pytest.raises(KeyError, match="named 'main_gimbal'.*'Canards', 'Main"): + _ = view["main_gimbal"] # the name as given, not in snake_case + with pytest.raises(KeyError, match="named 'Main Gimbal.yaw'"): + _ = view["Main Gimbal.yaw"] + with pytest.raises(KeyError, match="named 'Fins'"): + _ = view[_canard("Fins")] + + +# --------------------------------------------------------------------------- +# Writing from an event +# --------------------------------------------------------------------------- + + +def _run_callback(callback, controls, limits, **event_options): + """Run an event's callback once, as the flight does, and return it.""" + event = Event(callback=callback, name="Writer", **event_options) + flight = SimpleNamespace( + t=1.0, + _controls=controls, + _control_limits=limits, + rocket=SimpleNamespace(_refresh_aerodynamics=lambda: None), + ) + context = EventContext( + controls=controls, + time=1.0, + canonical_state=[0.0] * 13, + raw_state=[0.0] * 13, + phase_names=(), + ) + assert call_event(flight, event, context, None, 0, 0) + return event + + +def test_an_event_writes_the_controls_and_cuts_the_step(): + controls, limits = _controls(_canard()) + + def deploy(context): + context.controls.canards.deflection = 0.5 + + event = _run_callback(deploy, controls, limits) + + assert controls["canards.deflection"] == 0.2 # clamped + assert event.commands.control_changes == {"canards.deflection": 0.2} + assert event.commands.changes_trajectory is True + event.commands.reset() + assert event.commands.changes_trajectory is False + + +def test_an_event_that_reads_or_rewrites_a_value_cuts_nothing(): + controls, limits = _controls(_canard()) + seen = [] + + def hold(context): + seen.append(context.controls.canards.deflection) + context.controls.canards.deflection = 0.0 + + commands = _run_callback(hold, controls, limits).commands + assert commands.control_changes == {} + assert commands.changes_trajectory is False + assert seen == [0.0] + + +# --------------------------------------------------------------------------- +# The rocket's channels +# --------------------------------------------------------------------------- + + +def test_a_rocket_without_controls_has_no_channels(calisto_robust): + assert not calisto_robust.control_names + + +def test_air_brakes_and_controlled_surfaces_add_their_channels( + calisto_air_brakes_clamp_on, +): + rocket = calisto_air_brakes_clamp_on + rocket.add_surfaces(_canard(), 0.5) + # air brakes are surfaces: the channels follow the order they were added + assert rocket.control_names == ( + "air_brakes.deployment_level", + "canards.deflection", + ) + + +def test_a_failed_add_leaves_the_rocket_as_it_was(calisto_robust): + calisto_robust.add_surfaces(_canard("Canards"), 0.5) + before = calisto_robust.controllables + + with pytest.raises(ValueError, match="both have controls"): + calisto_robust.add_surfaces(_canard("canards"), 0.6) + with pytest.raises(ValueError, match="both have controls"): + calisto_robust.add_surfaces( + [_surface("Strake"), _canard("CANARDS")], [0.4, 0.6] + ) + with pytest.raises(TypeError, match="cannot be added to the rocket"): + calisto_robust.add_surfaces(object(), 0.6) + assert calisto_robust.controllables == before + + +# --------------------------------------------------------------------------- +# The equations of motion read the controls they are given +# --------------------------------------------------------------------------- + + +def _coasting_forces(rocket, environment, controls): + """The aerodynamic forces of a coasting state with some sideslip, + evaluated with a stand-in flight, so no simulation is run.""" + _, channels, _ = initial_controls(rocket.controllables) + flight = SimpleNamespace( + rocket=rocket, + env=environment, + _surface_switches={}, + _control_names=channels, + ) + upright = [1.0, 0.0, 0.0, 0.0] + state = [0.0, 0.0, 1500.0, 10.0, 0.0, 200.0, *upright, 0.0, 0.0, 0.0] + out = u_dot_generalized(flight, 10.0, state, controls, post_processing=True) + return np.array(out[6:9]) + + +def test_a_control_of_a_surface_moves_its_forces(calisto_robust, example_plain_env): + rocket = calisto_robust + canard = GenericSurface( + rocket.area, + 2 * rocket.radius, + {"cY": lambda deflection: 2.0 * deflection}, + name="Canards", + controls=("deflection",), + ) + rocket.add_surfaces(canard, 0.5) + controls, _, _ = initial_controls(rocket.controllables) + neutral = _coasting_forces(rocket, example_plain_env, controls) + + controls["canards.deflection"] = 0.1 + deflected = _coasting_forces(rocket, example_plain_env, controls) + assert deflected[0] != neutral[0] + # and the surface itself was not changed + assert canard.control_defaults == {"deflection": 0.0} + + +def test_the_air_brakes_drag_follows_their_channel( + calisto_air_brakes_clamp_on, example_plain_env +): + rocket = calisto_air_brakes_clamp_on + controls, _, _ = initial_controls(rocket.controllables) + retracted = _coasting_forces(rocket, example_plain_env, controls)[2] + + controls["air_brakes.deployment_level"] = 0.8 + deployed = _coasting_forces(rocket, example_plain_env, controls)[2] + assert deployed < retracted # more drag, toward the tail + assert rocket.air_brakes[0].deployment_level == 0 + + +# --------------------------------------------------------------------------- +# Rollbacks and records +# --------------------------------------------------------------------------- + + +def _flight_in_a_step(controls, events=(), t=2.0): + """A stand-in flight at the end of a solver step that began with + ``controls``, holding only what a rollback reads.""" + return SimpleNamespace( + t=t, + _controls=dict(controls), + _control_limits=dict.fromkeys(controls), + _step_log={}, + events=list(events), + ) + + +def _run(event, flight, time): + """Run ``event``'s callback at ``time`` in ``flight``'s step, as the flight + does, without applying its commands.""" + controls = flight._controls + before = dict(controls) + save_for_rollback(flight, event, time, before, None) + event(EventContext(time=time, controls=controls), callback_only=True) + changes = check_writes(controls, before, flight._control_limits) + event.commands.control_changes.update(changes) + + +def _writer(name, value, **kwargs): + key, channel = name.split(".") + + def callback(context): + setattr(getattr(context.controls, key), channel, value) + + return Event(callback=callback, name=f"Write {value}", **kwargs) + + +def test_an_event_that_writes_a_nan_is_named_in_the_error(): + """As after a division by zero in its callback. The flight stops there, + with the control as it was.""" + flight = _flight_in_a_step({"canards.deflection": 0.1}) + event = _writer("canards.deflection", float("nan")) + state = [0.0] * 13 + context = EventContext( + time=2.0, + controls=flight._controls, + canonical_state=state, + raw_state=state, + phase_names=(), + ) + + with pytest.raises(ValueError, match="set to nan by 'Write nan'"): + call_event(flight, event, context, None, 0, 0) + + assert flight._controls == {"canards.deflection": 0.1} + + +@pytest.mark.parametrize( + "dynamics, cuts", [(SIX_DOF_DYNAMICS, True), (PARACHUTE_DYNAMICS, False)] +) +def test_a_control_write_changes_the_trajectory_only_where_controls_are_read( + dynamics, cuts +): + """Under a parachute the air brakes, the control fins and the effectors do + nothing: a write is kept, and the solver step is not cut for it.""" + flight = _flight_in_a_step({"canards.deflection": 0.0}) + event = _writer("canards.deflection", 0.1) + state = [0.0] * 13 + context = EventContext( + time=flight.t, + controls=flight._controls, + canonical_state=state, + raw_state=state, + phase_names=(), + ) + phase = SimpleNamespace(dynamics=SimpleNamespace(dynamics=dynamics)) + + assert call_event(flight, event, context, phase, 0, 0) + + assert flight._controls == {"canards.deflection": 0.1} + assert event.commands.control_changes == {"canards.deflection": 0.1} + assert event.commands.changes_trajectory is cuts + + +def test_a_rollback_undoes_writes_made_after_the_time_it_goes_back_to(): + flight = _flight_in_a_step({"canards.deflection": 0.0}) + _run(_writer("canards.deflection", 0.1), flight, 2.0) # at the step end + + rewind(flight, 1.5) + + assert flight._controls == {"canards.deflection": 0.0} + + +def test_a_rollback_keeps_writes_made_before_the_time_it_goes_back_to(): + flight = _flight_in_a_step({"canards.deflection": 0.0}) + _run(_writer("canards.deflection", 0.1), flight, 1.0) + _run(_writer("canards.deflection", 0.2), flight, 2.0) + + rewind(flight, 1.5) + + assert flight._controls == {"canards.deflection": 0.1} + + +def test_a_rollback_keeps_the_writes_of_the_event_that_asks_for_it(): + """The event wrote at the time the flight goes back to, so its writes + stand.""" + flight = _flight_in_a_step({"canards.deflection": 0.0, "tab.trim": 0.0}) + _run(_writer("canards.deflection", 0.1), flight, 2.0) + cutter = _writer("tab.trim", 0.3) + _run(cutter, flight, 2.0) + + rewind(flight, 1.5, cutter.commands) + + assert flight._controls == {"canards.deflection": 0.0, "tab.trim": 0.3} + + +def test_going_back_to_the_current_time_cuts_nothing(): + flight = _flight_in_a_step({"canards.deflection": 0.0}) + _run(_writer("canards.deflection", 0.1), flight, 2.0) + + rewind(flight, flight.t) + + assert flight._controls == {"canards.deflection": 0.1} + + +def test_the_controls_object_is_kept_through_a_rollback(): + """``context.controls`` is the same dict before and after.""" + flight = _flight_in_a_step({"canards.deflection": 0.0}) + controls = flight._controls + _run(_writer("canards.deflection", 0.1), flight, 2.0) + rewind(flight, 1.0) + assert flight._controls is controls + + +def _counter(): + def callback(context): + memory = context.memory + memory["runs"] = memory.get("runs", 0) + 1 + memory.setdefault("times", []).append(context.time) + + return Event(callback=callback, name="Counter", memory={"runs": 0}) + + +def test_a_rollback_puts_the_memory_back_as_it_was_at_its_time(): + counter = _counter() + flight = _flight_in_a_step({}, events=[counter]) + for time in (0.5, 1.0, 1.8, 2.0): + _run(counter, flight, time) + memory = counter.memory + + rewind(flight, 1.5) + + assert counter.memory == {"runs": 2, "times": [0.5, 1.0]} + assert counter.memory is memory + + +def test_a_rollback_keeps_the_memory_of_the_event_that_asks_for_it(): + counter = _counter() + flight = _flight_in_a_step({}, events=[counter]) + _run(counter, flight, 2.0) + + rewind(flight, 1.5, counter.commands) + + assert counter.memory == {"runs": 1, "times": [2.0]} + + +def test_an_event_checked_twice_at_one_time_is_saved_once(): + """A trigger check and then the callback at the same time: the memory to + go back to is the one from before the check.""" + counter = _counter() + flight = _flight_in_a_step({}, events=[counter]) + _run(counter, flight, 2.0) + _run(counter, flight, 2.0) + + rewind(flight, 1.5) + + assert counter.memory == {"runs": 0} + + +def test_an_event_records_named_values_with_their_time(): + def callback(context): + context.record(error=context.time * 2, gain=1.0) + + event = Event(callback=callback, name="Recorder") + for time in (0.0, 0.5, 1.0): + event(EventContext(time=time), callback_only=True) + + assert event.records["error"] == [(0.0, 0.0), (0.5, 1.0), (1.0, 2.0)] + assert set(event.records) == {"error", "gain"} + + event.reset() + assert event.records == {} + + +def test_a_record_that_is_not_only_numbers_is_a_list_of_copies(): + command = [0.1, 0.2] + + def callback(context): + context.record(command=command, mode="coast" if context.time else 1.0) + + event = Event(callback=callback, name="Recorder") + for time in (0.0, 0.5): + event(EventContext(time=time), callback_only=True) + command[0] += 1.0 # changed after it was recorded + + assert event.records["command"] == [(0.0, [0.1, 0.2]), (0.5, [1.1, 0.2])] + assert event.records["mode"] == [(0.0, 1.0), (0.5, "coast")] + + +def test_a_record_keeps_a_number_as_it_was_given(): + def callback(context): + context.record(count=np.int64(3), flag=True, rate=np.float32(0.5)) + + event = Event(callback=callback, name="Recorder") + event(EventContext(time=0.0), callback_only=True) + + assert event.records["count"] == [(0.0, 3)] + assert event.records["flag"] == [(0.0, True)] + assert event.records["flag"][0][1] is True + assert event.records["rate"] == [(0.0, np.float32(0.5))] + + +def test_a_rollback_drops_the_records_made_after_its_time(): + event = Event(callback=lambda context: context.record(x=1.0), name="Recorder") + for time in (0.5, 1.0, 1.8): + event(EventContext(time=time), callback_only=True) + flight = _flight_in_a_step({}, events=[event]) + + rewind(flight, 1.5) + + assert event.records["x"] == [(0.5, 1.0), (1.0, 1.0)] + + +def test_an_event_keeps_what_its_callback_changed(): + controls, limits = _controls(_canard()) + + def deploy(context): + context.controls.canards.deflection = 0.1 + + event = _run_callback(deploy, controls, limits) + assert event.commands.control_changes == {"canards.deflection": 0.1} + event.commands.reset() + assert event.commands.control_changes == {} + + +def _view(): + controls = {"canards.fin_1": 0.0, "canards.fin_2": 0.0, "air_brakes.level": 0.5} + return controls, ControlsView(controls) + + +def test_a_view_shows_only_control_inputs_and_can_be_pointed_at_other_values(): + """What a continuous law reads: a dictionary that also holds the states + of the controllables, by names without a dot, through one view that is + pointed at the values of each evaluation of the equations of motion.""" + controls, view = _view() + controls["servo_angle"] = 0.3 + assert list(view) == ["canards", "air_brakes"] + assert "servo_angle" not in view + other = {**controls, "canards.fin_1": 0.7} + view._point_at(other) + assert view.canards.fin_1 == 0.7 + view.canards.fin_2 = 0.2 + assert other["canards.fin_2"] == 0.2 + assert controls["canards.fin_2"] == 0.0 + + +def test_a_channel_reads_and_writes_by_attribute(): + controls, view = _view() + view.canards.fin_1 = 0.1 + view["canards"].fin_2 = -0.1 # without its controllable, a key is its own name + + assert controls == { + "canards.fin_1": 0.1, + "canards.fin_2": -0.1, + "air_brakes.level": 0.5, + } + assert view.canards.fin_2 == -0.1 + assert view.air_brakes.level == 0.5 + + +def test_a_name_that_is_not_a_channel_says_which_exist(): + controls, view = _view() + with pytest.raises(AttributeError, match="canards, air_brakes|air_brakes, canards"): + view.canard.fin_1 = 0.1 + with pytest.raises(AttributeError, match="fin_1, fin_2"): + view.canards.fin_3 = 0.1 + with pytest.raises(AttributeError): + view.canards = 0.1 + assert len(controls) == 3 + + +def test_context_controls_writes_the_flight_controls(): + controls = {"canards.fin_1": 0.0} + context = EventContext(controls=controls) + context.controls.canards.fin_1 = 0.3 + assert controls == {"canards.fin_1": 0.3} + + +def test_the_context_does_not_hold_the_flight(): + """Users' functions get no way to the flight: its results read before it + ends would be kept, covering only part of it.""" + assert not hasattr(EventContext, "flight") + assert not hasattr(EventContext, "phase") + + +def test_context_memory_is_the_memory_of_the_event_being_checked(): + first = Event(callback=lambda context: None, memory={"a": 1}) + second = Event(callback=lambda context: None, memory={"b": 2}) + context = EventContext(time=0.0) + context.bind(first) + assert context.memory is first.memory + context.bind(second) + assert context.memory is second.memory + + +def test_context_commands_are_the_commands_of_the_event_being_checked(): + event = Event(callback=lambda context: context.commands.terminate_flight()) + context = EventContext(time=0.0) + assert event(context, callback_only=True) + assert context.commands is event.commands + assert event.commands._terminate + + +def test_a_control_is_also_read_and_written_by_name(): + """For a name built in a loop: ``controls.canards[fin]``.""" + controls, view = _view() + for fin in ("fin_1", "fin_2"): + view.canards[fin] = 0.1 + assert controls["canards.fin_1"] == 0.1 and controls["canards.fin_2"] == 0.1 + assert view["canards"]["fin_1"] == 0.1 + with pytest.raises(KeyError, match="no control named 'fin_9'"): + view.canards["fin_9"] = 0.1 + with pytest.raises(KeyError, match="no control named 'fin_9'"): + _ = view.canards["fin_9"] + + +def test_a_rollback_restores_the_previous_check_and_the_enabled_flag(): + """An event run in the part of the step that is cut is as it was before: + its next run does not see a check that never happened.""" + flight = _flight_in_a_step({"canards.deflection": 0.0}) + event = _writer("canards.deflection", 0.1, sampling_rate=10) + _run(event, flight, 2.0) + event._previous_time = 2.0 + event._enabled = False # as a flight turns it off + + rewind(flight, 1.5) + + assert event._previous_time is None + assert event.enabled is True + + +def test_a_control_named_as_a_method_of_the_view_is_read_by_name(): + part = Controllable("Valve", controls=("update",)) + view = ControlsView({"valve.update": 0.3}, [part]) + assert view.valve["update"] == 0.3 + assert "0.3" in repr(view.valve) + + +def test_one_control_name_given_alone_is_one_control(): + assert Controllable("Valve", controls="opening").controls == ("opening",) + + +def test_enable_event_queues_the_event_to_turn_on(): + commands, other = Commands(), object() + commands.enable_event(other) + assert commands.enable_events == [other] + + +def _context_at(time, vz, height=100.0): + state = [0.0] * 13 + state[5] = vz + return EventContext( + time=time, + canonical_state=state, + raw_state=state, + phase_names=(), + height_agl=height, + ) + + +def test_the_apogee_trigger_holds_from_the_first_check_past_apogee(): + """Whatever the time between checks: it does not need the check to fall + in the solver step where the apogee was crossed. Like the other named + triggers it holds from then on. On the pad, at rest, it does not fire.""" + event = Event(lambda context: None, trigger="apogee", sampling_rate=1) + checks = ((0, 0.0, 0.0), (1, 50.0, 30.0), (2, 5.0, 90.0), (3, -4.0, 91.0)) + fired = [event(_context_at(*check)) for check in (*checks, (4, -9.0, 85.0))] + assert fired == [False, False, False, True, True] + + +def test_the_apogee_gates_hold_from_the_apogee_on(): + event = Event(lambda context: None, enabled=False, enable_on="apogee") + assert event.enable_on(_context_at(1.0, 50.0)) is False + assert event.enable_on(_context_at(3.0, -4.0)) is True + assert event.enable_on(_context_at(9.0, -30.0)) is True diff --git a/tests/unit/control/test_controllable_states.py b/tests/unit/control/test_controllable_states.py new file mode 100644 index 000000000..81dc49f13 --- /dev/null +++ b/tests/unit/control/test_controllable_states.py @@ -0,0 +1,204 @@ +"""Controllables with states of their own: the flight integrates them after the +phase's states, and the controllable's physics receives the values the controllable acts +with, not the ones its controller wrote. They use stand-ins for the rocket +and the flight, so no simulation is run.""" + +from types import SimpleNamespace + +import numpy as np +import pytest + +from rocketpy import Flight +from rocketpy.control import ContinuousController, Controllable +from rocketpy.control.controllable import ForceEffector, ThrustEffector +from rocketpy.simulation.helpers.dynamics import ( + CANONICAL_STATE_NAMES, + SIX_DOF_DYNAMICS, + _PhaseDynamics, + _with_controllables, +) +from rocketpy.simulation.solution import _PhaseSolution + + +class Servo(Controllable): + """A control that reaches the commanded angle with a first-order lag.""" + + states = ("angle",) + + def __init__(self, name="Servo", start=0.1): + super().__init__(name, ("angle",), control_limits={"angle": (-1, 1)}) + self.start = start + + def initial_states(self): + return [self.start] + + def state_derivative(self, states, commands, conditions): + return [(commands[0] - states[0]) / 0.05] + + def actual_controls(self, states, commands, conditions): + return [states[0]] + + +def _rocket(*controllables): + """A rocket with these controllables, sorted as Rocket sorts them.""" + laws = tuple(c for c in controllables if isinstance(c, ContinuousController)) + parts = tuple(c for c in controllables if c not in laws) + return SimpleNamespace( + _parts_with_states=tuple(p for p in parts if p._acts_on_its_own()), + _continuous_controllers=laws, + effectors=SimpleNamespace( + get_components=lambda: [ + p for p in parts if isinstance(p, (ThrustEffector, ForceEffector)) + ] + ), + controllables=controllables, + ) + + +# What FlightConditions reads of a flight +_FLIGHT = SimpleNamespace(rocket=None, env=None) + + +def _reads_controls(flight, t, u, controls, post_processing=False): # pylint: disable=unused-argument + """A phase whose derivative and post-process value are what it read.""" + if post_processing: + return [controls["servo.angle"]] + return [controls["servo.angle"], *[0.0] * 12] + + +_PHASE = _PhaseDynamics( + "toy", _reads_controls, CANONICAL_STATE_NAMES, post_process_vars=("read",) +) + + +def test_a_rocket_without_controllable_states_flies_the_phase_as_it_is(): + plain = Controllable("Plain", ("on",)) + assert _with_controllables(_PHASE, _rocket(plain)) is _PHASE + assert _with_controllables(_PHASE, _rocket()) is _PHASE + + +def test_the_controllable_states_come_after_the_phase_states(): + servo, other = Servo(), Servo("Other Servo") + extended = _with_controllables(SIX_DOF_DYNAMICS, _rocket(servo, other)) + assert extended.states == ( + *CANONICAL_STATE_NAMES, + "servo_angle", + "other_servo_angle", + ) + assert extended.name == SIX_DOF_DYNAMICS.name + # Extending twice changes nothing + assert _with_controllables(extended, _rocket(servo, other)) is extended + + +class Counter(Controllable): + """A state of its own and no controls, so only the state's name can clash.""" + + states = ("count",) + + def __init__(self, name="Counter"): + super().__init__(name, ()) + + def initial_states(self): + return [0.0] + + def state_derivative(self, states, commands, conditions): + return [1.0] + + +def test_two_controllables_cannot_share_a_state_name(calisto): + with pytest.raises(ValueError, match="state named 'counter_count'"): + calisto._check_new_controllables(Counter(), Counter()) + + +def test_the_phase_reads_the_values_the_controllable_acts_with(): + """The phase's derivative receives the servo's angle, a state, not the + command, and the state's derivative follows the command.""" + extended = _with_controllables(_PHASE, _rocket(Servo())) + controls = {"servo.angle": 0.6} + u = [0.0] * 13 + [0.2] + derivative = extended.derivative(_FLIGHT, 0.0, u, controls) + assert len(derivative) == 14 + assert derivative[0] == 0.2 + assert derivative[-1] == pytest.approx((0.6 - 0.2) / 0.05) + assert extended.derivative(_FLIGHT, 0.0, u, controls, post_processing=True) == [0.2] + # The controls the controller wrote are left as they were + assert controls == {"servo.angle": 0.6} + + +def test_controllable_states_start_from_the_controllable_then_carry_over(): + extended = _with_controllables(_PHASE, _rocket(Servo(start=0.1))) + canonical = list(range(13)) + assert extended.initial_state(None, 0.0, canonical) == [*canonical, 0.1] + assert extended.initial_state(None, 0.0, canonical, {"servo_angle": 0.4}) == [ + *canonical, + 0.4, + ] + + +def test_a_controllable_whose_initial_states_do_not_match_is_refused(calisto): + servo = Servo() + servo.initial_states = lambda: [0.0, 0.0] + with pytest.raises(ValueError, match="1 states, but its initial_states"): + calisto._check_new_controllables(servo) + + +def test_a_state_that_is_not_a_plain_name_is_refused(calisto): + """A state is read by name in the flight, and a name with a dot would + look like a control input.""" + servo = Servo() + servo.states = ("angle.fast",) + with pytest.raises(ValueError, match="letters, digits and underscores"): + calisto._check_new_controllables(servo) + + +def test_a_state_of_its_own_carries_over_between_phases(): + phase = _PhaseDynamics("own", None, (*CANONICAL_STATE_NAMES, "spin")) + assert phase.initial_state(None, 0.0, [0.0] * 13, {"spin": 3.0})[-1] == 3.0 + + +def test_the_canonical_state_is_the_first_thirteen_values(): + extended = _with_controllables(SIX_DOF_DYNAMICS, _rocket(Servo())) + state = list(range(14)) + assert not extended.is_canonical + assert extended.canonicalize(state, None) == list(range(13)) + assert extended.canonicalize_derivative(state) == list(range(13)) + + +def test_a_phase_extended_for_is_saved_and_read_back(): + extended = _with_controllables(SIX_DOF_DYNAMICS, _rocket(Servo())) + phase = _PhaseSolution(extended, [0.0] * 13, t_start=0.0, name="free") + loaded = _PhaseSolution.from_dict(phase.to_dict()) + assert loaded.dynamics.name == SIX_DOF_DYNAMICS.name + assert loaded.dynamics.states == extended.states + assert loaded.dynamics.post_process_vars == SIX_DOF_DYNAMICS.post_process_vars + assert loaded.state_dict(list(range(14)))["servo_angle"] == 13 + + +def test_the_phase_also_reads_the_controllable_states_by_name(): + seen = {} + + def reads(flight, t, u, controls): # pylint: disable=unused-argument + seen.update(controls) + return [0.0] * 13 + + phase = _PhaseDynamics("reads", reads, CANONICAL_STATE_NAMES) + extended = _with_controllables(phase, _rocket(Servo())) + extended.derivative(_FLIGHT, 0.0, [0.0] * 13 + [0.25], {"servo.angle": 0.6}) + assert seen == {"servo.angle": 0.25, "servo_angle": 0.25} + + +def test_the_states_are_read_after_the_flight_by_controllable_and_name(): + flight = SimpleNamespace( + rocket=_rocket(Servo("Fin Servo"), Servo("Idle", start=0)), + solution={ + "fin_servo_angle": np.array([[0.0, 0.0], [1.0, 1.0], [2.0, 1.0]]), + "idle_angle": np.array([[0.0, 0.0], [2.0, 0.0]]), + }, + ) + history = Flight.state_history.func(flight) + assert list(history) == ["Fin Servo", "Idle"] + assert list(history.fin_servo) == ["angle"] + assert history["Fin Servo"].angle(0.5) == pytest.approx(0.5) # interpolated + assert history.fin_servo.angle(1.5) == pytest.approx(1.0) + with pytest.raises(AttributeError, match="Nothing here is named 'position'"): + _ = history.fin_servo.position diff --git a/tests/unit/control/test_controller.py b/tests/unit/control/test_controller.py index 154ad3450..3367eac4f 100644 --- a/tests/unit/control/test_controller.py +++ b/tests/unit/control/test_controller.py @@ -1,151 +1,503 @@ +import copy +import json from types import SimpleNamespace import pytest -from rocketpy.control.controlled import Controlled -from rocketpy.control.controller import _Controller +from rocketpy import AirBrakes, Controller, GenericSurface +from rocketpy._encoders import RocketPyDecoder, RocketPyEncoder +from rocketpy.control._helpers import initial_controls +from rocketpy.control._legacy import _PositionalController from rocketpy.simulation.events.event_context import EventContext +from rocketpy.simulation.events.event_execution import call_event +from rocketpy.simulation.events.views import output_events -def _run(controller): - """Run a controller's event once and return what its function logged.""" +def _air_brakes(name="AirBrakes"): + return AirBrakes( + drag_coefficient_curve=lambda deployment_level, mach: deployment_level, + reference_area=0.01, + name=name, + ) + + +def _canards(): + return GenericSurface( + 0.01, + 0.1, + {"cl": lambda mach, deflection: deflection}, + name="Canards", + controls=("deflection",), + control_limits={"deflection": (-0.2, 0.2)}, + ) + + +def _flight_of(*controllables): + """A stand-in flight holding the control inputs of ``controllables``.""" + controls, channels, limits = initial_controls(controllables) + return SimpleNamespace( + t=0.0, + _controls=controls, + _control_names=channels, + _control_limits=limits, + rocket=SimpleNamespace(controllables=list(controllables)), + # The rows a positional controller function receives as state_history + solution=SimpleNamespace(_rows=[[0.0] * 14]), + ) + + +def _run(controller, flight, time=0.0, sensors=None, sharing=()): + """Run ``controller`` once at ``time`` in the stand-in ``flight``, whose + events with outputs are among ``sharing``.""" + flight.t = time context = EventContext( - time=0.0, + time=time, canonical_state=[0.0] * 13, raw_state=[0.0] * 13, phase_names=(), + controls=flight._controls, + rocket=flight.rocket, + sensors=sensors or {}, + environment=None, + solution=flight.solution, + output_events=output_events(sharing), ) - controller.event(context) - return controller.log[-1] + call_event(flight, controller, context, None, 0, 0) -def test_a_named_object_is_read_by_name_and_by_position(): - brakes = SimpleNamespace(deployment_level=0.0) +def test_a_controller_writes_the_flight_controls_not_the_object(): + brakes = _air_brakes() + flight = _flight_of(brakes) def function(context): - context.controlled.air_brakes.deployment_level = 0.5 - return { - "by_position": context.controlled[0], - "controller": context.controller, - "count": len(context.controlled), - } - - controller = _Controller( - function, brakes, sampling_rate=10, controlled_objects_name="air_brakes" - ) - log = _run(controller) - - assert brakes.deployment_level == 0.5 - assert log["by_position"] is brakes - assert log["controller"] is controller - assert log["count"] == 1 - - -def test_several_objects_are_read_by_their_own_names_in_order(): - brakes, fins = SimpleNamespace(), SimpleNamespace() - controller = _Controller( - lambda context: { - "brakes": context.controlled.brakes, - "fins": context.controlled.fins, - "all": list(context.controlled), - }, - [brakes, fins], + context.controls.air_brakes.deployment_level = 0.7 + + controller = Controller(function, sampling_rate=10) + _run(controller, flight) + + assert flight._controls["air_brakes.deployment_level"] == 0.7 + assert brakes.initial_deployment_level == 0.0 + assert controller.sampling_rate == 10 + assert controller.priority == 3 + + +def test_a_write_is_kept_inside_the_limits(): + flight = _flight_of(_air_brakes()) + controller = Controller( + lambda context: setattr(context.controls.air_brakes, "deployment_level", 3), sampling_rate=10, - controlled_objects_name=["brakes", "fins"], ) - log = _run(controller) + _run(controller, flight) + assert flight._controls["air_brakes.deployment_level"] == 1.0 + + +def test_a_controller_records_with_the_context(): + flight = _flight_of(_air_brakes()) + + def function(context): + context.record(estimated_apogee=3000.0 + context.time) - assert log["brakes"] is brakes - assert log["fins"] is fins - assert log["all"] == [brakes, fins] + controller = Controller(function, sampling_rate=10, name="Apogee Controller") + _run(controller, flight, time=0.0) + _run(controller, flight, time=0.1) + assert controller.records["estimated_apogee"] == [(0.0, 3000.0), (0.1, 3000.1)] -def test_objects_without_names_are_read_by_position(): - brakes, fins = SimpleNamespace(), SimpleNamespace() - controller = _Controller( - lambda context: {"second": context.controlled[1]}, - [brakes, fins], + +def test_an_outer_loop_hands_a_setpoint_to_an_inner_loop(): + """A controller's outputs are found under its name: the controller writes + them and another controller reads them.""" + + def guidance_function(context): + context.outputs.guidance.pitch_setpoint = 0.2 + + def attitude_function(context): + context.controls.canards.deflection = context.outputs.guidance.pitch_setpoint + + guidance = Controller( + guidance_function, sampling_rate=10, + name="Guidance", + outputs={"pitch_setpoint": 0.05}, ) + attitude = Controller(attitude_function, sampling_rate=100, name="Attitude") + assert guidance.outputs == ("pitch_setpoint",) + assert guidance.output_defaults == {"pitch_setpoint": 0.05} + assert attitude.outputs == () + + flight = _flight_of(_canards()) + both = (guidance, attitude) + # An output is not a control input of the flight + assert list(flight._controls) == ["canards.deflection"] + _run(attitude, flight, sharing=both) + assert flight._controls["canards.deflection"] == 0.05 + _run(guidance, flight, time=0.1, sharing=both) + # Writing an output does not change the trajectory + assert guidance.commands.control_changes == {} + _run(attitude, flight, time=0.1, sharing=both) + assert flight._controls["canards.deflection"] == 0.2 + assert guidance.output_history == {"pitch_setpoint": [(0.1, 0.2)]} + + +def test_a_output_holds_any_value_and_is_written_by_its_event_only(): + def estimator_function(context): + context.outputs.estimator.attitude = [1.0, 0.0, 0.0, 0.0] + context.outputs["Estimator"].mode = "coast" + + def reader_function(context): + context.memory["read"] = context.outputs.estimator.mode + context.outputs.estimator.mode = "boost" + + estimator = Controller( + estimator_function, + sampling_rate=10, + name="Estimator", + outputs=("attitude", "mode"), + ) + reader = Controller(reader_function, sampling_rate=10, name="Reader") + flight = _flight_of(_canards()) + both = (estimator, reader) + assert estimator.output_defaults == {"attitude": None, "mode": None} + _run(estimator, flight, sharing=both) + assert estimator.output_history == { + "attitude": [(0.0, [1.0, 0.0, 0.0, 0.0])], + "mode": [(0.0, "coast")], + } + with pytest.raises(AttributeError, match="written only by 'Estimator'"): + _run(reader, flight, sharing=both) + assert reader.memory["read"] == "coast" + assert estimator._outputs["mode"] == "coast" + + +def test_a_output_goes_back_with_the_flight_and_starts_again(): + controller = Controller( + lambda context: None, + sampling_rate=10, + name="Guidance", + outputs={"setpoint": 0.05, "path": None}, + ) + controller._write_output(0.1, "setpoint", 0.2) + controller._write_output(0.2, "setpoint", 0.3) + controller._write_output(0.2, "path", [1, 2]) + controller._drop_after(0.1) + assert controller._outputs == {"setpoint": 0.2, "path": None} + assert controller.output_history == {"setpoint": [(0.1, 0.2)], "path": []} + controller.reset() + assert controller._outputs == {"setpoint": 0.05, "path": None} + assert controller.output_history == {} - assert _run(controller)["second"] is fins +def test_printing_the_context_lists_what_a_controller_can_use(): + seen = {} -def test_a_name_no_object_was_given_says_which_names_exist(): - controlled = Controlled([SimpleNamespace()], ["air_brakes"]) + def function(context): + seen["text"] = repr(context) + seen["names"] = dir(context) - with pytest.raises(AttributeError, match="fins.*available.*air_brakes"): - _ = controlled.fins + controller = Controller( + function, sampling_rate=10, name="Guidance", outputs=("setpoint",) + ) + _run(controller, _flight_of(_canards()), sharing=(controller,)) + assert "EventContext at t = 0 s, event 'Guidance'" in seen["text"] + assert "canards: deflection" in seen["text"] + assert "guidance: setpoint" in seen["text"] + assert "x, y, z, vx, vy, vz" in seen["text"] + # Only what a function reads, not the methods of the dictionary + assert {"time", "state", "controls", "outputs", "record"} <= set(seen["names"]) + assert not {"pop", "clear", "update", "keys"} & set(seen["names"]) -def test_the_controlled_objects_leave_the_context_with_the_controller(): - """The next event of the step must not see another controller's objects.""" - controller = _Controller(lambda context: None, SimpleNamespace(), sampling_rate=10) - context = EventContext( - time=0.0, canonical_state=[0.0] * 13, raw_state=[0.0] * 13, phase_names=() +def test_output_names_are_checked(): + with pytest.raises(ValueError, match="letters, digits and underscores"): + Controller(lambda context: None, sampling_rate=10, outputs=("1st",)) + + +def test_a_rocket_checks_its_controllers_outputs(calisto): + controller = Controller( + lambda context: None, sampling_rate=10, name="Guidance", outputs=("x", "y") + ) + calisto.add_controller(controller) + # Outputs are not control inputs + assert calisto.control_names == () + clash = Controller( + lambda context: None, sampling_rate=10, name="Guidance", outputs=("z",) + ) + with pytest.raises(ValueError, match="both have outputs"): + calisto.add_controller(clash) + assert calisto.controllers == (controller,) + + +def test_a_controller_chooses_how_the_flight_reaches_its_samples(): + assert Controller(lambda context: None, sampling_rate=10).time_overshootable + stopped = Controller( + lambda context: None, sampling_rate=10, time_overshootable=False ) - controller.event(context) - assert context.controlled is not None + assert stopped.time_overshootable is False - context.bind(SimpleNamespace(sampling_rate=None)) - assert context.controlled is None - assert context.controller is None +def test_what_a_controller_returns_is_ignored(): + controller = Controller(lambda context: {"state": [1, 2]}, sampling_rate=10) + _run(controller, _flight_of(_air_brakes()), time=0.5) + assert not controller.records -def test_a_name_may_be_one_the_context_itself_uses(): - """Objects live under ``context.controlled``, so no name is reserved.""" - controller = _Controller( - lambda context: {"time": context.time, "mine": context.controlled.time}, - "the object", +@pytest.mark.parametrize("function", [lambda: None, lambda a, b: None, 3]) +def test_the_function_must_take_the_context(function): + with pytest.raises((TypeError, ValueError)): + Controller(function, sampling_rate=10) + + +@pytest.mark.parametrize("sampling_rate", [0, -1, None]) +def test_the_sampling_rate_must_be_positive(sampling_rate): + """A controller always has a rate: without one it would run once per + solver step, as often as the solver's tolerances happen to make it.""" + with pytest.raises(ValueError, match="sampling rate"): + Controller(lambda context: None, sampling_rate=sampling_rate) + + +def test_memory_starts_again_at_every_flight(): + def count(context): + context.memory["calls"] += 1 + + controller = Controller(count, sampling_rate=10, memory={"calls": 0}) + flight = _flight_of(_air_brakes()) + _run(controller, flight) + _run(controller, flight) + assert controller.memory["calls"] == 2 + controller.reset() + assert controller.memory["calls"] == 0 + + +def test_a_controller_write_marks_its_commands(): + """A controller is a plain event: a write that changes a control cuts the + solver step at the sampling time, and a write that changes nothing does + not.""" + flight = _flight_of(_air_brakes()) + controller = Controller( + lambda context: setattr(context.controls.air_brakes, "deployment_level", 0.5), sampling_rate=10, - controlled_objects_name="time", - ) - - assert _run(controller) == {"time": 0.0, "mine": "the object"} - - -@pytest.mark.parametrize("name", ["air brakes", "1st", "_hidden", "class", ""]) -def test_a_name_that_cannot_follow_a_dot_is_rejected(name): - with pytest.raises(ValueError, match="context.controlled"): - _Controller( - lambda context: None, - SimpleNamespace(), - sampling_rate=10, - controlled_objects_name=name, - ) - - -def test_names_must_match_the_objects(): - one, two = SimpleNamespace(), SimpleNamespace() - with pytest.raises(ValueError, match="unique"): - _Controller( - lambda context: None, [one, two], 10, controlled_objects_name=["a", "a"] - ) - with pytest.raises(ValueError, match="Length"): - _Controller(lambda context: None, [one, two], 10, controlled_objects_name=["a"]) - with pytest.raises(ValueError, match="not a list"): - _Controller(lambda context: None, one, 10, controlled_objects_name=["a"]) - with pytest.raises(TypeError): - _Controller(lambda context: None, one, 10, controlled_objects_name=3) - - -def test_rebinding_points_the_context_at_the_new_objects(): - """A loaded rocket reconnects its controller to its own rebuilt objects.""" - saved, loaded = SimpleNamespace(), SimpleNamespace() - controller = _Controller( - lambda context: { - "by_name": context.controlled.air_brakes, - "by_position": context.controlled[0], - }, - saved, + ) + _run(controller, flight) + assert controller.commands.control_changes == {"air_brakes.deployment_level": 0.5} + assert controller.commands.changes_trajectory is True + _run(controller, flight) + assert controller.commands.changes_trajectory is False + + +def test_a_positional_function_moves_the_air_brakes_by_name(recwarn): + """The deprecated positional form of v1.13 receives the state history and + the air brakes as an object whose deployment level is the flight's + channel.""" + brakes = _air_brakes() + flight = _flight_of(_canards(), brakes) + received = [] + + def legacy( # pylint: disable=unused-argument + time, sampling_rate, state, state_history, observed_variables, air_brakes + ): + received.append((sampling_rate, state_history, list(observed_variables))) + air_brakes.deployment_level = 0.3 + return air_brakes.deployment_level + + controller = Controller( + _PositionalController( + legacy, 20, part_name="AirBrakes", initial_observed_variables=1.0 + ), + sampling_rate=20, + ) + _run(controller, flight) + assert received == [(20, flight.solution._rows, [1.0])] + assert controller.controller_function.observed_variables == [1.0, 0.3] + # Kept on the wrapper, not in the memory copied before every run + assert controller.memory == {} + assert flight._controls["air_brakes.deployment_level"] == 0.3 + assert brakes.initial_deployment_level == 0.0 + assert not recwarn.list + + +def test_a_positional_function_gathers_what_it_returns(): + """As in v1.13, observed_variables starts with the initial value and gains + every value returned other than None; it starts again at every flight.""" + seen = [] + + def legacy(t, rate, state, history, observed, air_brakes): # pylint: disable=unused-argument + seen.append(list(observed)) + return None if len(seen) == 2 else len(seen) + + controller = Controller( + _PositionalController(legacy, 10, initial_observed_variables="start"), sampling_rate=10, - controlled_objects_name="air_brakes", ) + flight = _flight_of(_air_brakes()) + for _ in range(3): + _run(controller, flight) + assert seen == [["start"], ["start", 1], ["start", 1]] + assert controller.controller_function.observed_variables == ["start", 1, 3] + # A saved controller starts with the initial value again + saved = copy.deepcopy(controller.controller_function) + assert saved.observed_variables == ["start"] + controller.reset() + assert controller.controller_function.observed_variables == ["start"] + + +def test_a_positional_function_receives_the_sensor_objects(): + """As in v1.13, the seventh argument is the list of the rocket's sensors, + one per position, in the order they were added.""" + barometer, gyroscope = SimpleNamespace(name="b"), SimpleNamespace(name="g") + received = [] + + def legacy(t, rate, state, history, observed, air_brakes, sensors): # pylint: disable=unused-argument + received.append(sensors) + + controller = Controller(_PositionalController(legacy, 10), sampling_rate=10) + _run( + controller, + _flight_of(_air_brakes()), + sensors={"barometer_1": (barometer, None), "gyroscope": (gyroscope, None)}, + ) + assert received == [[barometer, gyroscope]] + + +def test_a_positional_function_without_a_name_needs_one_part(): + controller = Controller( + _PositionalController(lambda t, r, s, h, o, b: None, 10), sampling_rate=10 + ) + _run(controller, _flight_of(_air_brakes())) + with pytest.raises(ValueError, match="2 that it could be"): + _run(controller, _flight_of(_air_brakes(), _canards())) + + +def _round_trip(obj, **options): + return json.loads( + json.dumps(obj, cls=RocketPyEncoder, **options), cls=RocketPyDecoder + ) + + +def _saved_function(context): + context.controls.canards.deflection = 0.1 + context.record(time=context.time) + + +def test_a_controller_is_saved_and_loaded(): + controller = Controller( + _saved_function, + sampling_rate=25, + memory={"gain": 2.0}, + name="Roll Damper", + enabled=False, + disable_on="apogee", + enable_on=1.5, + outputs={"rate_setpoint": 0.3}, + time_overshootable=False, + ) + loaded = _round_trip(controller) + + assert isinstance(loaded, Controller) + assert loaded.sampling_rate == 25 + assert loaded.memory == {"gain": 2.0} + assert loaded.name == "Roll Damper" + assert loaded.enabled is False + assert loaded._gates == ("apogee", 1.5) + assert loaded.output_defaults == {"rate_setpoint": 0.3} + assert loaded.time_overshootable is False + loaded.enabled = True + flight = _flight_of(_canards()) + _run(loaded, flight) + assert loaded._records == {"time": [(0.0, 0.0)]} + assert flight._controls["canards.deflection"] == 0.1 + + +def test_a_controller_saved_without_its_function_loads_disabled(): + controller = Controller(_saved_function, sampling_rate=10) + with pytest.warns(UserWarning, match="could not be loaded"): + loaded = _round_trip(controller, allow_pickle=False) + assert loaded.enabled is False + loaded.enabled = True + flight = _flight_of(_canards()) + _run(loaded, flight) + assert flight._controls["canards.deflection"] == 0.0 + + +def test_a_controller_saved_by_the_old_class_loads(): + """What ``_Controller.to_dict`` saved, with its extra keys, loads as a + Controller.""" + data = { + "controller_function": Controller(_saved_function, 10).to_dict()[ + "controller_function" + ], + "sampling_rate": 10, + "name": "Old", + "controlled_objects_name": "air_brakes", + "controlled_objects_hash": 1234, + "memory": {}, + "enabled": True, + "disable_on": None, + "enable_on": None, + "signature": {"module": "rocketpy.control.controller", "name": "_Controller"}, + } + loaded = json.loads(json.dumps(data), cls=RocketPyDecoder) + assert isinstance(loaded, Controller) + assert loaded.name == "Old" + + +def test_a_controller_can_be_copied(): + controller = Controller(_saved_function, sampling_rate=10, memory={"a": [1]}) + copied = copy.deepcopy(controller) + flight = _flight_of(_canards()) + _run(copied, flight) + assert copied.triggered_times == [0.0] + assert controller.triggered_times == [] + + +def test_info_lists_the_function_and_memory(capsys): + controller = Controller( + _saved_function, sampling_rate=10, memory={"gain": 1}, outputs=("setpoint",) + ) + controller.info() + out = capsys.readouterr().out + assert "_saved_function" in out + assert "Outputs: setpoint" in out + assert "Memory keys: gain" in out + + +def _controller_with_a_gain(context, gain=2.0): # pylint: disable=unused-argument + return None + + +def test_a_function_with_extra_default_arguments_takes_the_context(): + """Saved and loaded as it is, not read as a v1.13 positional function.""" + controller = Controller(_controller_with_a_gain, 10, name="Gain") + loaded = Controller.from_dict(controller.to_dict()) + assert not isinstance(loaded.controller_function, _PositionalController) + assert loaded.enabled + + +def _gate(context): # pylint: disable=unused-argument + return False + + +def test_a_gate_saved_without_pickling_loads_the_controller_disabled(): + controller = Controller(lambda context: None, 10, disable_on=_gate) + data = controller.to_dict(allow_pickle=False) + with pytest.warns(UserWarning, match="could not be loaded"): + loaded = Controller.from_dict(data) + assert not loaded.enabled + + +def test_a_preset_gate_is_loaded_as_saved(): + controller = Controller(lambda context: None, 10, disable_on="apogee") + loaded = Controller.from_dict(controller.to_dict()) + assert loaded.enabled and loaded._gates[0] == "apogee" + + +def test_enabled_set_after_the_controller_is_built_is_kept_and_saved(): + """Turning a controller off after it was built, as with the one + ``rocket.add_air_brakes`` creates, holds for every flight and is what is + saved with the rocket.""" + controller = Controller(lambda context: None, sampling_rate=10) + controller.enabled = False - controller.rebind_controlled_objects(loaded) - log = _run(controller) + controller.reset() - assert controller.controlled_objects is loaded - assert log["by_name"] is loaded - assert log["by_position"] is loaded + assert controller.enabled is False + assert controller.to_dict()["enabled"] is False diff --git a/tests/unit/mathutils/test_function.py b/tests/unit/mathutils/test_function.py index 070d6eb42..91cfa5347 100644 --- a/tests/unit/mathutils/test_function.py +++ b/tests/unit/mathutils/test_function.py @@ -1571,3 +1571,28 @@ def test_regular_grid_dict_round_trip(bilinear_grid_2d): assert restored.get_domain_dim() == 2 for x, y in [(0.5, 1.5), (1.25, 0.75), (2.0, 2.0)]: assert np.isclose(restored(x, y), bilinear_grid_2d(x, y)) + + +def test_previous_interpolation_holds_each_value_until_the_next_point(): + """A sampled signal keeps its value until the next sample.""" + held = Function( + [[0.0, 0.0], [1.0, 0.5], [2.0, 0.2]], + interpolation="previous", + extrapolation="constant", + ) + assert held.get_interpolation_method() == "previous" + assert held(0.5) == 0.0 + assert held(1.0) == 0.5 # a point holds from its own time on + assert held(1.99) == 0.5 + assert held(2.0) == 0.2 + assert held(5.0) == 0.2 + assert held(-1.0) == 0.0 + assert list(held.get_value([0.5, 1.5])) == [0.0, 0.5] + + +def test_previous_interpolation_extrapolates_at_the_edge_values(): + held = Function( + [[0.0, 1.0], [1.0, 3.0]], interpolation="previous", extrapolation="natural" + ) + assert held(-2.0) == 1.0 + assert held(4.0) == 3.0 diff --git a/tests/unit/rocket/aero_surface/test_air_brakes.py b/tests/unit/rocket/aero_surface/test_air_brakes.py new file mode 100644 index 000000000..ad0a1bbc0 --- /dev/null +++ b/tests/unit/rocket/aero_surface/test_air_brakes.py @@ -0,0 +1,449 @@ +"""Air brakes as an aerodynamic surface: their drag comes from the surface +loop like every other surface's and is added to the rocket's own drag. Brakes +built with ``override_rocket_drag`` add what their whole-rocket curve gains +over its retracted values.""" + +import json +import warnings +from copy import deepcopy +from types import SimpleNamespace + +import numpy as np +import pytest + +from rocketpy import AirBrakes, Function, Rocket +from rocketpy._encoders import RocketPyDecoder, RocketPyEncoder +from rocketpy.control._helpers import initial_controls +from rocketpy.mathutils.vector_matrix import Vector +from rocketpy.simulation.helpers.flight_derivatives import ( + u_dot_generalized, +) + +CURVE = "data/rockets/calisto/air_brakes_cd.csv" + + +def _brakes(override=False, name="AirBrakes"): + return AirBrakes(CURVE, 0.01, override_rocket_drag=override, name=name) + + +def _stand_in(rocket, environment): + """A stand-in flight of ``rocket``, holding what the derivatives read.""" + controls, channels, _ = initial_controls(rocket.controllables) + flight = SimpleNamespace( + rocket=rocket, + env=environment, + _surface_switches={}, + _control_names=channels, + ) + return controls, flight + + +def _forces_and_moments(flight, controls, speed=200.0): + """R1, R2, R3, M1, M2, M3 of the rocket coasting nose-first at ``speed``, + straight up, no wind.""" + upright = [1.0, 0.0, 0.0, 0.0] + state = [0.0, 0.0, 1500.0, 0.0, 0.0, speed, *upright, 0.0, 0.0, 0.0] + out = u_dot_generalized(flight, 10.0, state, controls, post_processing=True) + return np.array(out[6:12]) + + +@pytest.mark.parametrize("override", [False, True]) +def test_retracted_air_brakes_make_no_drag(override): + brakes = _brakes(override) + assert brakes.cA(0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0) == 0.0 + forces = brakes.compute_forces_and_moments( + Vector([0, 0, -200.0]), + 200.0, + 0.6, + 1.0, + Vector([0, 0, 0]), + Vector([0, 0, 0]), + None, + None, + 0.0, + [0.0], + ) + assert all(value == 0 for value in forces) + + +# A curve of the whole rocket: 0.5 retracted, rising to 0.9 fully open, and +# 0.1 more at Mach 1 +WHOLE_ROCKET_CURVE = [ + [0.0, 0.0, 0.5], + [0.0, 1.0, 0.6], + [1.0, 0.0, 0.9], + [1.0, 1.0, 1.0], +] + + +def test_a_whole_rocket_curve_adds_its_gain_over_the_retracted_values(): + brakes = AirBrakes(WHOLE_ROCKET_CURVE, 0.01, override_rocket_drag=True) + at = (0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0) + assert brakes.cA(*at, 1.0) == pytest.approx(0.4) + assert brakes.cA(*at, 0.5) == pytest.approx(0.2) + # continuous through deployment level 0 + assert brakes.cA(*at, 1e-9) == pytest.approx(0.0, abs=1e-8) + assert brakes.cA(*at, 0.0) == 0.0 + + +def test_the_total_drag_is_the_whole_rocket_curve(calisto_robust, example_plain_env): + """With the rocket's drag set to the curve's retracted values, the drag of + the rocket with its brakes open is the curve at that deployment level.""" + rocket = calisto_robust + curve = AirBrakes(WHOLE_ROCKET_CURVE, rocket.area).drag_coefficient + rocket.power_off_drag = lambda mach: curve(0.0, mach) + with warnings.catch_warnings(): + warnings.simplefilter("error") + rocket.add_air_brakes( + WHOLE_ROCKET_CURVE, lambda context: None, 10, override_rocket_drag=True + ) + controls, flight = _stand_in(rocket, example_plain_env) + without_brakes = _forces_and_moments(flight, controls) + rho = example_plain_env.density(1500.0) + mach = 200.0 / example_plain_env.speed_of_sound(1500.0) + pressure_area = 0.5 * rho * 200.0**2 * rocket.area + + surfaces = without_brakes[2] + pressure_area * curve(0.0, mach) + for level in (0.0, 0.3, 1.0): + controls["air_brakes.deployment_level"] = level + axial = _forces_and_moments(flight, controls)[2] + assert axial - surfaces == pytest.approx( + -pressure_area * curve(level, mach), rel=1e-12 + ) + + +def test_the_exported_coefficients_follow_a_whole_rocket_curve(calisto_robust): + """The export adds the rocket's drag and the air brakes' gain, so its axial + coefficient rises with the deployment level by what the curve does.""" + rocket = calisto_robust + rocket.add_surfaces( + AirBrakes(WHOLE_ROCKET_CURVE, rocket.area, override_rocket_drag=True), 0.0 + ) + axial = rocket.to_coefficients( + machs=[0.0, 0.5, 1.0], controls={"deployment_level": [0.0, 0.5, 1.0]} + )["power_off"]["cA_0"] + assert axial(0.5, 1.0) - axial(0.5, 0.0) == pytest.approx(0.4) + assert axial(0.5, 0.5) - axial(0.5, 0.0) == pytest.approx(0.2) + + +def test_a_whole_rocket_curve_that_disagrees_with_the_rocket_drag_warns( + calisto_robust, +): + with pytest.warns(UserWarning, match="deployment level 0"): + calisto_robust.add_air_brakes( + CURVE, lambda context: None, 10, override_rocket_drag=True + ) + + +def test_a_whole_rocket_curve_is_checked_whichever_way_it_is_added(calisto_robust): + """Added as a surface, the air brakes get the same warning as through + ``add_air_brakes``, once each way, and none for a curve of the air brakes + alone.""" + rocket = calisto_robust + + def retracted_drag_warnings(record): + return [w for w in record if "deployment level 0" in str(w.message)] + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + rocket.add_surfaces( + AirBrakes(CURVE, rocket.area, override_rocket_drag=True, name="First"), + 0.0, + ) + assert len(retracted_drag_warnings(record)) == 1 + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + rocket.add_air_brakes( + CURVE, lambda context: None, 10, override_rocket_drag=True, name="Second" + ) + assert len(retracted_drag_warnings(record)) == 1 + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + rocket.add_surfaces(AirBrakes(CURVE, rocket.area, name="Third"), 0.0) + assert not retracted_drag_warnings(record) + + +def test_the_drag_is_the_same_as_before_at_zero_angle_of_attack( + calisto_robust, example_plain_env +): + """Nose-first, the brakes' drag is what the separate air-brakes code gave: + 0.5 rho V^2 times the area and the curve at the deployment level.""" + calisto_robust.add_air_brakes(CURVE, lambda context: None, 10) + controls, flight = _stand_in(calisto_robust, example_plain_env) + retracted = _forces_and_moments(flight, controls) + controls["air_brakes.deployment_level"] = 0.7 + deployed = _forces_and_moments(flight, controls) + + (brakes,) = calisto_robust.air_brakes + rho = example_plain_env.density(1500.0) + mach = 200.0 / example_plain_env.speed_of_sound(1500.0) + expected = -0.5 * rho * 200.0**2 * brakes.reference_area + expected *= brakes.drag_coefficient(0.7, mach) + assert deployed[2] - retracted[2] == pytest.approx(expected, rel=1e-12) + # pinned at the center of dry mass: no moment, and no side force + assert list(deployed[[0, 1, 3, 4, 5]]) == list(retracted[[0, 1, 3, 4, 5]]) + + +def test_air_brakes_without_a_position_follow_the_center_of_dry_mass( + calisto_motorless, cesaroni_m1670 +): + """Without a position the brakes act at the center of dry mass, wherever a + motor added before or after puts it, and no warning is raised.""" + rocket = calisto_motorless + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + rocket.add_air_brakes(CURVE, lambda context: None, 10) + rocket.add_motor(cesaroni_m1670, position=-1.373) + rocket._refresh_aerodynamics() + (brakes,) = rocket.air_brakes + assert rocket._is_at_center_of_dry_mass(brakes) + assert list(rocket.surfaces_cp_to_cdm[brakes]) == [0, 0, 0] + # Saved and loaded, they still follow it + loaded = json.loads(json.dumps(rocket, cls=RocketPyEncoder), cls=RocketPyDecoder) + (loaded_brakes,) = loaded.air_brakes + assert loaded._is_at_center_of_dry_mass(loaded_brakes) + assert list(loaded.surfaces_cp_to_cdm[loaded_brakes]) == [0, 0, 0] + + +def test_air_brakes_off_the_axis_make_a_moment(calisto_robust, example_plain_env): + calisto_robust.add_air_brakes( + CURVE, lambda context: None, 10, position=(0.05, 0.0, 0.0) + ) + controls, flight = _stand_in(calisto_robust, example_plain_env) + retracted = _forces_and_moments(flight, controls) + controls["air_brakes.deployment_level"] = 0.7 + deployed = _forces_and_moments(flight, controls) + + (brakes,) = calisto_robust.air_brakes + lever = calisto_robust.surfaces_cp_to_cdm[brakes] + force = Vector(list(deployed[:3] - retracted[:3])) + moment = deployed[3:] - retracted[3:] + assert lever.x != 0 + assert list(moment) == pytest.approx(list(lever ^ force), rel=1e-12) + assert moment[1] != 0 + + +def test_air_brakes_are_saved_once_inside_the_surfaces(calisto_robust): + calisto_robust.add_air_brakes(CURVE, lambda context: None, 10) + data = calisto_robust.to_dict() + assert "air_brakes" not in data + assert any(isinstance(s, AirBrakes) for s, _ in data["aerodynamic_surfaces"]) + + loaded = json.loads( + json.dumps(calisto_robust, cls=RocketPyEncoder), cls=RocketPyDecoder + ) + assert len(loaded.air_brakes) == 1 + assert loaded.control_names == ("air_brakes.deployment_level",) + + +def test_air_brakes_saved_before_they_were_surfaces_load(calisto_robust): + """Older files keep air brakes in their own list, apart from the surfaces; + they load as surfaces at the center of dry mass.""" + saved = json.loads(json.dumps(calisto_robust, cls=RocketPyEncoder)) + saved["air_brakes"] = [json.loads(json.dumps(_brakes(), cls=RocketPyEncoder))] + + loaded = json.loads(json.dumps(saved), cls=RocketPyDecoder) + assert isinstance(loaded, Rocket) + (loaded_brakes,) = loaded.air_brakes + assert loaded._is_at_center_of_dry_mass(loaded_brakes) + assert list(loaded.surfaces_cp_to_cdm[loaded_brakes]) == [0, 0, 0] + + +def test_rocket_air_brakes_lists_the_air_brakes_among_the_surfaces(calisto_robust): + brakes = calisto_robust.add_air_brakes(CURVE, lambda context: None, 10) + assert calisto_robust.air_brakes == [brakes] + assert any(surface is brakes for surface, _ in calisto_robust.aerodynamic_surfaces) + + +def test_return_controller_is_deprecated_and_still_returns_the_controller( + calisto_robust, +): + with pytest.warns(DeprecationWarning, match="`return_controller` is deprecated"): + brakes, controller = calisto_robust.add_air_brakes( + CURVE, + lambda context: None, + 10, + return_controller=True, + name="Second", + position=0.0, + ) + assert isinstance(brakes, AirBrakes) + assert controller is calisto_robust.controllers[-1] + + # Without the argument nothing is deprecated, and only the brakes return + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + third = calisto_robust.add_air_brakes( + CURVE, lambda context: None, 10, name="Third", position=0.0 + ) + assert isinstance(third, AirBrakes) + + +def test_info_prints_the_settings_and_the_drag_table(capsys, tmp_path): + brakes = AirBrakes(CURVE, 0.01, name="Main Brakes", override_rocket_drag=True) + brakes.info() + out = capsys.readouterr().out + assert "Control input: main_brakes.deployment_level" in out + assert "Reference area: 0.01 m^2" in out + assert "the drag of the whole rocket at each deployment level" in out + assert "Drag coefficient by deployment level" in out + assert f"{brakes.drag_coefficient(0.5, 0.3):8.4f}" in out + + brakes.plots.drag_coefficient(filename=str(tmp_path / "cd.png")) + assert (tmp_path / "cd.png").exists() + brakes.plots.drag_coefficient( + levels=(0.5,), mach=(0.1, 0.5), filename=str(tmp_path / "cd_one.png") + ) + assert (tmp_path / "cd_one.png").exists() + + +def test_a_curve_given_as_a_function_is_read_as_level_then_mach(tmp_path): + brakes = AirBrakes(lambda level, mach: 0.5 * level + mach, 0.01) + assert brakes.drag_coefficient(0.4, 0.3) == pytest.approx(0.5) + assert brakes.cA(0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.0, 0.4) == pytest.approx(0.5) + assert brakes.cA(0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0) == 0.0 + # No data points: the plot falls back to default levels and Mach range + brakes.plots.drag_coefficient(filename=str(tmp_path / "cd.png")) + assert (tmp_path / "cd.png").exists() + + +def test_the_initial_level_is_limited_or_warned_about(): + assert ( + AirBrakes(CURVE, 0.01, initial_deployment_level=1.5).initial_deployment_level + == 1 + ) + # Without clamp there is no limit at all + loose = AirBrakes(CURVE, 0.01, clamp=False, initial_deployment_level=1.5) + assert loose.initial_deployment_level == 1.5 + assert loose.control_limits["deployment_level"] is None + with pytest.warns(DeprecationWarning, match="initial_deployment_level"): + old = AirBrakes(CURVE, 0.01, deployment_level=0.3) + assert old.initial_deployment_level == 0.3 + + +def test_air_brakes_alone_are_saved_and_loaded(): + brakes = AirBrakes( + CURVE, + 0.01, + clamp=False, + override_rocket_drag=True, + initial_deployment_level=0.2, + name="Main Brakes", + active_during="power_off", + active=False, + ) + loaded = json.loads(json.dumps(brakes, cls=RocketPyEncoder), cls=RocketPyDecoder) + for attribute in ( + "reference_area", + "clamp", + "override_rocket_drag", + "initial_deployment_level", + "name", + "active_during", + "active", + ): + assert getattr(loaded, attribute) == getattr(brakes, attribute) + assert loaded.drag_coefficient(0.5, 0.3) == brakes.drag_coefficient(0.5, 0.3) + + # A file from before v1.15 names the level "deployment_level" and lacks + # the newer fields + data = json.loads(json.dumps(brakes, cls=RocketPyEncoder)) + data["deployment_level"] = data.pop("initial_deployment_level") + for key in ("active_during", "active", "clamp", "name"): + del data[key] + old = json.loads(json.dumps(data), cls=RocketPyDecoder) + assert old.initial_deployment_level == 0.2 + assert old.clamp and old.active and old.active_during == "always" + assert old.name == "AirBrakes" + + +def _still_air_flight(rocket, speed, level, rows=5): + """A flight stub flying ``rocket`` at ``speed`` m/s through still + sea-level air, the air brakes held at ``level``.""" + times = np.linspace(0, 1, rows) + constant = lambda value: Function(lambda t: value) # noqa: E731 + return SimpleNamespace( + rocket=rocket, + time=times, + free_stream_speed=constant(speed), + mach_number=constant(speed / 340.0), + density=constant(1.225), + aerodynamic_drag=Function(np.column_stack((times, np.full(rows, 100.0)))), + controls={"AirBrakes": {"deployment_level": constant(level)}}, + _surface_switches={}, + ) + + +def test_the_drag_over_a_flight_is_the_curve_at_the_air_met(calisto_robust, tmp_path): + brakes = _brakes() + calisto_robust.add_surfaces(brakes, 0.0) + flight = _still_air_flight(calisto_robust, 102.0, 0.7) + + drag = brakes._drag_in(flight) + expected = 0.5 * 1.225 * 102.0**2 * 0.01 * brakes.drag_coefficient(0.7, 0.3) + assert drag.x_array == pytest.approx(flight.time) + assert drag(0.5) == pytest.approx(expected) + assert brakes._drag_in(_still_air_flight(calisto_robust, 102.0, 0.0))(0.5) == 0 + + brakes.plots.drag(flight, filename=str(tmp_path / "drag.png")) + assert (tmp_path / "drag.png").exists() + with pytest.raises(ValueError, match="not on the rocket"): + _brakes(name="Other")._drag_in(flight) + + +def test_bad_inputs_are_refused_with_a_clear_message(): + with pytest.raises(ValueError, match="reference area must be positive"): + AirBrakes(CURVE, 0) + with pytest.raises(ValueError, match="deployment level and the Mach number"): + AirBrakes(lambda mach: mach, 0.01) + with pytest.raises(ValueError, match="three columns"): + AirBrakes(np.zeros((3, 2)), 0.01) + + +def test_a_number_is_a_constant_drag_coefficient(): + brakes = AirBrakes(0.4, 0.01) + assert brakes.cA(0, 0, 0.5, 0, 0, 0, 0, 1.0) == pytest.approx(0.4) + assert brakes.cA(0, 0, 0.5, 0, 0, 0, 0, 0.0) == 0.0 + + +def test_replacing_the_curve_changes_the_drag_flown(): + """The stochastic air brakes scale ``drag_coefficient`` after building.""" + brakes = _brakes() + before = brakes.cA(0, 0, 0.5, 0, 0, 0, 0, 1.0) + brakes.drag_coefficient *= 2 + assert brakes.cA(0, 0, 0.5, 0, 0, 0, 0, 1.0) == pytest.approx(2 * before) + + +@pytest.mark.parametrize("override", [False, True]) +def test_a_deep_copy_of_the_air_brakes_reads_its_own_drag_curve(override): + """A copied rocket is often changed and flown again: the copy's drag is + that of the copy's curve, and a change to either leaves the other alone.""" + state = (0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0) + brakes = _brakes(override) + drag = brakes.cA(*state) + assert drag > 0 + + copied = deepcopy(brakes) + assert copied.cA(*state) == pytest.approx(drag) + copied.drag_coefficient = copied.drag_coefficient * 4 + assert copied.cA(*state) == pytest.approx(4 * drag) + assert brakes.cA(*state) == pytest.approx(drag) + + brakes.drag_coefficient = brakes.drag_coefficient * 10 + assert copied.cA(*state) == pytest.approx(4 * drag) + + +def test_a_deep_copy_of_a_rocket_flies_its_own_air_brakes(calisto_robust): + calisto_robust.add_surfaces(_brakes(), None) + copied = deepcopy(calisto_robust) + (brakes,) = calisto_robust.air_brakes + (copied_brakes,) = copied.air_brakes + assert copied_brakes is not brakes + + state = (0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0) + drag = brakes.cA(*state) + copied_brakes.drag_coefficient = copied_brakes.drag_coefficient * 2 + assert copied_brakes.cA(*state) == pytest.approx(2 * drag) + assert brakes.cA(*state) == pytest.approx(drag) diff --git a/tests/unit/rocket/aero_surface/test_control_fins.py b/tests/unit/rocket/aero_surface/test_control_fins.py new file mode 100644 index 000000000..b89f7b880 --- /dev/null +++ b/tests/unit/rocket/aero_surface/test_control_fins.py @@ -0,0 +1,580 @@ +"""ControlFins: a set of individual fins a controller turns one by one. Each +test compares the set against the same individual fins added to a rocket +with a cant angle, so no simulation is run.""" + +import json +import math +from copy import deepcopy +from types import SimpleNamespace + +import numpy as np +import pytest + +from rocketpy import ControlFins, Function, TrapezoidalFin +from rocketpy._encoders import RocketPyDecoder, RocketPyEncoder +from rocketpy.mathutils.vector_matrix import Vector +from rocketpy.simulation.events.views import ControlsView + +POSITION = 0.8 # where the fins are added, in calisto's coordinate system + + +def _fin(angular_position=0.0, cant_angle=0.0, name="Fin"): + return TrapezoidalFin( + angular_position=angular_position, + root_chord=0.08, + tip_chord=0.04, + span=0.06, + rocket_radius=0.0635, + cant_angle=cant_angle, + name=name, + ) + + +def _individual_fins(rocket, n, deflections, start=0.0): + """Add ``n`` individual fins to ``rocket``, each canted by its deflection, + where ControlFins(n=n) would put them, and return them.""" + fins = [] + for i, deflection in enumerate(deflections): + fin = _fin(start + 360 * i / n, math.degrees(deflection), f"fin {i}") + rocket.add_surfaces(fin, POSITION) + fins.append(fin) + return fins + + +def _random_states(count=4, seed=0): + rng = np.random.default_rng(seed) + for _ in range(count): + stream = Vector(list(rng.normal(size=3) * [5, 5, 1] + [0, 0, -100])) + omega = Vector(list(rng.normal(size=3))) + yield stream, omega + + +def _forces_of_individual_fins(rocket, fins, stream, omega, reference): + """Sum the forces of individual fins, each fed the air where it sits, the + way the flight feeds them, with ``stream`` given at ``reference``.""" + total = np.zeros(6) + for fin in fins: + cp = rocket.surfaces_cp_to_cdm[fin] + local = stream - (omega ^ (cp - reference)) + speed = abs(local) + total += np.array( + fin.compute_forces_and_moments(local, speed, speed / 340, 1.1, cp, omega) + ) + return total + + +def test_each_fin_has_a_numbered_channel(calisto): + canards = ControlFins(_fin(angular_position=45), n=4, name="Canards") + calisto.add_surfaces(canards, POSITION) + + assert canards.controls == ("fin_1", "fin_2", "fin_3", "fin_4") + assert canards.angular_positions == (45.0, 135.0, 225.0, 315.0) + assert calisto.control_names[-4:] == ( + "canards.fin_1", + "canards.fin_2", + "canards.fin_3", + "canards.fin_4", + ) + + +def test_the_fin_classes_themselves_have_no_controls(): + assert _fin().controls == () + + +def test_the_fin_given_is_neither_changed_nor_flown(): + fin = _fin(angular_position=10, cant_angle=2) + canards = ControlFins(fin, n=3) + + assert fin.angular_position == 10 and fin.cant_angle == 2 + assert all(each is not fin for each in canards.fins) + # The fins of the set are uncanted: their deflection turns them + assert all(each.cant_angle == 0 for each in canards.fins) + assert canards.control_defaults == dict.fromkeys(canards.controls, math.radians(2)) + + +@pytest.mark.parametrize("deflections", [(0.0,) * 4, (0.05, -0.02, 0.1, 0.0)]) +def test_the_set_flies_as_the_same_individual_fins(calisto, deflections, request): + canards = ControlFins(_fin(), n=4, name="Canards") + calisto.add_surfaces(canards, POSITION) + reference = calisto.surfaces_cp_to_cdm[canards] + other = request.getfixturevalue("calisto_robust") + fins = _individual_fins(other, 4, deflections) + + for stream, omega in _random_states(): + speed = abs(stream) + expected = _forces_of_individual_fins(other, fins, stream, omega, reference) + got = canards.compute_forces_and_moments( + stream, speed, speed / 340, 1.1, reference, omega, controls=deflections + ) + assert np.allclose(got, expected, atol=1e-12, rtol=1e-12) + + +def test_the_default_deflection_is_the_cant_of_the_fin_given(calisto): + canards = ControlFins(_fin(cant_angle=3), n=4) + calisto.add_surfaces(canards, POSITION) + reference = calisto.surfaces_cp_to_cdm[canards] + stream, omega = next(_random_states()) + speed = abs(stream) + + held = canards.compute_forces_and_moments(stream, speed, 0.3, 1.1, reference, omega) + given = canards.compute_forces_and_moments( + stream, speed, 0.3, 1.1, reference, omega, controls=(math.radians(3),) * 4 + ) + assert held == pytest.approx(given) + + +def test_the_same_deflection_on_every_fin_only_rolls_the_rocket(): + canards = ControlFins(_fin(), n=4) + stream = Vector([0, 0, -100]) + R1, R2, _, M1, M2, M3 = canards.compute_forces_and_moments( + stream, 100, 0.3, 1.2, Vector([0, 0, 1]), (0, 0, 0), controls=(0.1,) * 4 + ) + assert [R1, R2, M1, M2] == pytest.approx([0, 0, 0, 0], abs=1e-9) + assert M3 != 0 + + +def test_the_static_margin_is_that_of_the_individual_fins(calisto, calisto_robust): + canards = ControlFins(_fin(cant_angle=2), n=4) + calisto.add_surfaces(canards, POSITION) + _individual_fins(calisto_robust, 4, (math.radians(2),) * 4) + + for mach in (0.3, 0.9): + assert calisto.aerodynamic_center(mach) == pytest.approx( + calisto_robust.aerodynamic_center(mach), abs=1e-9 + ) + assert calisto.stability_margin(mach, 0) == pytest.approx( + calisto_robust.stability_margin(mach, 0), abs=1e-9 + ) + + +def test_the_deflection_limits_apply_to_every_fin(calisto): + canards = ControlFins(_fin(cant_angle=20), n=2, deflection_limits=(-0.2, 0.2)) + calisto.add_surfaces(canards, POSITION) + + assert canards.control_limits == {"fin_1": (-0.2, 0.2), "fin_2": (-0.2, 0.2)} + # The cant given is outside the limits, so the default is clamped + assert canards.control_defaults == {"fin_1": 0.2, "fin_2": 0.2} + + +@pytest.mark.parametrize( + "fin, n, error", + [ + ("not a fin", 4, TypeError), + (None, 4, TypeError), + (_fin(), 2.5, TypeError), + (_fin(), 0, ValueError), + ], +) +def test_wrong_inputs_are_refused(fin, n, error): + with pytest.raises(error): + ControlFins(fin, n=n) + + +def test_control_fins_are_saved_and_loaded(): + canards = ControlFins( + _fin(angular_position=30, cant_angle=1), + n=3, + name="Canards", + deflection_limits=(-0.3, 0.3), + ) + loaded = json.loads(json.dumps(canards, cls=RocketPyEncoder), cls=RocketPyDecoder) + + assert isinstance(loaded, ControlFins) + assert loaded.name == "Canards" and loaded.n == 3 + assert loaded.angular_positions == canards.angular_positions + assert loaded.control_limits == canards.control_limits + assert loaded.control_defaults == pytest.approx(canards.control_defaults) + stream = Vector([1, 2, -100]) + args = (stream, abs(stream), 0.3, 1.2, Vector([0, 0, 1]), (0.1, 0.2, 0.3)) + assert loaded.compute_forces_and_moments(*args) == pytest.approx( + canards.compute_forces_and_moments(*args) + ) + + +def test_info_says_which_fin_is_which(capsys): + ControlFins(_fin(angular_position=90), n=2, name="Canards").info() + out = capsys.readouterr().out + assert "fin_1" in out and "90.00 deg" in out + assert "fin_2" in out and "270.00 deg" in out + + +def _placed(canards, z): + """The set as a rocket would leave it after adding it ``z`` meters ahead + of its center of dry mass (behind it for a negative ``z``).""" + canards._placed_at(Vector([0, 0, z])) + return canards + + +def test_deflections_mix_the_roll_pitch_and_yaw_commands(): + canards = _placed(ControlFins(_fin(), n=4), 0.4) + assert canards.deflections(roll=0.02) == pytest.approx( + dict.fromkeys(canards.controls, -0.02) + ) + assert canards.deflections(yaw=0.1) == pytest.approx( + {"fin_1": 0.1, "fin_2": 0.0, "fin_3": -0.1, "fin_4": 0.0} + ) + assert canards.deflections(pitch=0.1) == pytest.approx( + {"fin_1": 0.0, "fin_2": -0.1, "fin_3": 0.0, "fin_4": 0.1} + ) + mixed = canards.deflections(roll=0.02, pitch=0.05, yaw=0.1) + assert mixed == pytest.approx( + {"fin_1": 0.08, "fin_2": -0.07, "fin_3": -0.12, "fin_4": 0.03} + ) + three = _placed(ControlFins(_fin(), n=3), 0.4).deflections(yaw=0.1) + assert list(three.values()) == pytest.approx([0.1, -0.05, -0.05]) + + +def test_tail_fins_turn_the_other_way_for_the_same_pitch_or_yaw_command(): + canards = _placed(ControlFins(_fin(), n=4), 0.4) + tail_fins = _placed(ControlFins(_fin(), n=4), -0.9) + for command in ("pitch", "yaw"): + ahead = canards.deflections(**{command: 0.1}) + behind = tail_fins.deflections(**{command: 0.1}) + assert behind == pytest.approx({fin: -angle for fin, angle in ahead.items()}) + assert tail_fins.deflections(roll=0.1) == canards.deflections(roll=0.1) + + +@pytest.mark.parametrize("z", [0.4, -0.9]) +@pytest.mark.parametrize("command, axis", [("pitch", 0), ("yaw", 1), ("roll", 2)]) +def test_a_positive_command_turns_the_rocket_toward_the_positive_rate(z, command, axis): + """Ahead of the center of dry mass or behind it, a positive command gives + a positive moment about its own body axis and none about the others.""" + canards = _placed(ControlFins(_fin(), n=4), z) + deflections = canards.deflections(**{command: 0.1}) + forces = canards.compute_forces_and_moments( + Vector([0, 0, -100]), + 100, + 0.3, + 1.2, + Vector([0, 0, z]), + (0, 0, 0), + controls=[deflections[control] for control in canards.controls], + ) + moments = forces[3:6] + assert moments[axis] > 0 + for other in {0, 1, 2} - {axis}: + assert moments[other] == pytest.approx(0, abs=1e-9) + + +def test_pitch_and_yaw_commands_need_the_set_on_a_rocket(calisto): + canards = ControlFins(_fin(), n=4, name="Canards") + assert canards.deflections(roll=0.1) == dict.fromkeys(canards.controls, -0.1) + for command in ("pitch", "yaw"): + with pytest.raises(ValueError, match="not on a rocket yet"): + canards.deflections(**{command: 0.1}) + + calisto.add_surfaces(canards, POSITION) + assert canards.deflections(yaw=0.1)["fin_1"] == pytest.approx(0.1) + + with pytest.raises(ValueError, match="center of dry mass"): + _placed(ControlFins(_fin(), n=4), 0.0).deflections(pitch=0.1) + + +def test_the_rocket_tells_the_fins_where_they_sit(calisto): + canards = ControlFins(_fin(), n=4, name="Canards") + calisto.add_surfaces(canards, POSITION) + assert canards._position == calisto.surfaces_cp_to_cdm[canards] + assert canards._position.z > 0 + + tail_fins = ControlFins(_fin(), n=4, name="Tail fins") + calisto.add_surfaces(tail_fins, -1.0) + assert tail_fins._position.z < 0 + assert tail_fins.deflections(yaw=0.1)["fin_1"] == pytest.approx(-0.1) + + +def test_effectiveness_is_the_slope_of_the_coefficients(): + canards = _placed(ControlFins(_fin(), n=4), 0.4) + effectiveness = canards.effectiveness() + roll, pitch, yaw = (effectiveness[key](0.3) for key in ("roll", "pitch", "yaw")) + assert roll > 0 and pitch > 0 and yaw > 0 + assert pitch == pytest.approx(yaw) + # The roll coefficient at a small roll command, from the coefficients + h = 0.01 + cl = canards.cl(0, 0, 0.3, 0, 0, 0, 0, -h, -h, -h, -h) # with reynolds + assert roll * h == pytest.approx(cl, rel=1e-3) + # The yaw moment at a small yaw command: the force toward +x and the + # moment about the point the set is added at, moved to the center of dry mass + cY = canards.cY(0, 0, 0.3, 0, 0, 0, 0, h, 0, -h, 0) + cn = canards.cn(0, 0, 0.3, 0, 0, 0, 0, h, 0, -h, 0) + assert yaw * h == pytest.approx(cn + cY * 0.4 / canards.reference_length, rel=1e-3) + assert effectiveness["roll"](0.8) != pytest.approx(roll) # changes with Mach + + +def test_effectiveness_of_a_set_off_a_rocket_is_the_roll_one(): + assert set(ControlFins(_fin(), n=4).effectiveness()) == {"roll"} + + +def test_the_hinge_position_sets_where_a_fin_moves_to_when_it_turns(): + fin = _fin() + at_edge = ControlFins(fin, n=4, hinge_position=0.0) + quarter = ControlFins(fin, n=4, hinge_position=0.25) + middle = ControlFins(fin, n=4) + assert middle.hinge_position == 0.5 + offsets = [list(each._frame(0, 0.2)[2]) for each in (at_edge, quarter, middle)] + # Turning about the leading edge does not move it; the shift grows with the hinge + shift_quarter = np.subtract(offsets[1], offsets[0]) + shift_middle = np.subtract(offsets[2], offsets[0]) + assert shift_middle == pytest.approx(2 * shift_quarter) + assert list(shift_middle) == pytest.approx( + list(fin._cant_shift(0.2, fin._rotation_fin_to_body_uncanted)) + ) + with pytest.raises(ValueError, match="hinge position"): + ControlFins(fin, n=4, hinge_position=1.5) + + +def test_the_hinge_position_is_saved_and_printed(capsys): + canards = ControlFins(_fin(), n=4, hinge_position=0.3) + loaded = json.loads(json.dumps(canards, cls=RocketPyEncoder), cls=RocketPyDecoder) + assert loaded.hinge_position == 0.3 + canards.info() + assert "Hinge line: at 30% of the root chord" in capsys.readouterr().out + + +def test_the_hinge_moment_is_the_normal_force_times_the_arm_to_the_hinge(): + fin = _fin() + q = 30e3 # Pa + at_edge = ControlFins(fin, n=4, hinge_position=0.0, name="Canards") + at_cp = ControlFins(fin, n=4, hinge_position=fin.cpz / fin.root_chord) + behind = ControlFins(fin, n=4, hinge_position=1.0) + + # Hinge ahead of the center of pressure: the air pushes a deflected fin + # back toward zero. On the center of pressure: no torque. Behind it: the + # air pushes the fin further the way it is turned + torque = at_edge.hinge_moments(q, deflections=0.1) + assert set(torque) == set(at_edge.controls) + assert torque["fin_1"](0.3) < 0 + assert at_edge.hinge_moments(q, deflections=-0.1)["fin_1"](0.3) > 0 + assert at_cp.hinge_moments(q, deflections=0.1)["fin_1"](0.3) == pytest.approx(0) + assert behind.hinge_moments(q, deflections=0.1)["fin_1"](0.3) > 0 + + # It is the normal force times the arm, and scales with dynamic pressure + # and with the arm + expected = at_edge.hinge_moments(q, deflections=0.1)["fin_1"](0.3) + force = -expected / fin.cpz + arm = fin.cpz - 0.25 * fin.root_chord + quarter = ControlFins(fin, n=4, hinge_position=0.25) + assert quarter.hinge_moments(q, deflections=0.1)["fin_1"](0.3) == pytest.approx( + -force * arm + ) + assert at_edge.hinge_moments(2 * q, deflections=0.1)["fin_1"](0.3) == ( + pytest.approx(2 * expected) + ) + + # Deflections per control input, the rest at their defaults, zero here + torque = at_edge.hinge_moments(q, deflections={"fin_2": 0.1}) + assert torque["fin_1"](0.3) == pytest.approx(0) + assert torque["fin_2"](0.3) == pytest.approx(expected) + + # Head-on air at zero deflection gives no torque. Air crossing a fin does: + # fin 1 is on the +y axis, so sideslip (toward x) loads it and the angle + # of attack (toward y, along its span) does not + assert at_edge.hinge_moments(q)["fin_1"](0.3) == pytest.approx(0) + assert at_edge.hinge_moments(q, alpha=0.05)["fin_1"](0.3) == pytest.approx(0) + assert at_edge.hinge_moments(q, beta=0.05)["fin_1"](0.3) != pytest.approx(0) + assert at_edge.hinge_moments(q, alpha=0.05)["fin_2"](0.3) != pytest.approx(0) + + +def _still_air_flight(rocket, speed, deflections, rows=5): + """A flight stub flying ``rocket`` nose first at ``speed`` m/s through + still sea-level air with no rotation, the fins held at ``deflections``.""" + times = np.linspace(0, 1, rows) + constant = lambda value: Function(lambda t: value) # noqa: E731 + canards = next(s for s, _ in rocket.aerodynamic_surfaces if s.name == "Canards") + history = { + "Canards": {control: constant(value) for control, value in deflections.items()} + } + return SimpleNamespace( + rocket=rocket, + time=times, + stream_velocity_body_frame=np.tile([0.0, 0.0, -speed], (rows, 1)), + w1=constant(0.0), + w2=constant(0.0), + w3=constant(0.0), + density=constant(1.225), + speed_of_sound=constant(340.0), + controls=history, + _surface_switches={}, + canards=canards, + ) + + +def test_the_hinge_moments_over_a_flight_match_the_ones_at_its_air(calisto, tmp_path): + fin = _fin() + canards = ControlFins(fin, n=4, hinge_position=0.0, name="Canards") + calisto.add_surfaces(canards, POSITION) + deflections = dict.fromkeys(canards.controls, 0.1) + speed = 102.0 # m/s, Mach 0.3 at 340 m/s + flight = _still_air_flight(calisto, speed, deflections) + + over = canards._hinge_moments_in(flight) + at = canards.hinge_moments(0.5 * 1.225 * speed**2, deflections=deflections) + assert set(over) == set(canards.controls) + for control in canards.controls: + assert over[control].x_array == pytest.approx(flight.time) + assert over[control](0.5) == pytest.approx(at[control](0.3)) + assert over["fin_1"](0.5) < 0 + + canards.plots.hinge_moments(flight, filename=str(tmp_path / "hinge.png")) + assert (tmp_path / "hinge.png").exists() + + # A set that is not on the flight's rocket is refused + with pytest.raises(ValueError, match="not on the rocket"): + ControlFins(fin, n=4, name="Other")._hinge_moments_in(flight) + + +def test_a_controller_writes_the_deflections_at_once(): + canards = ControlFins(_fin(), n=4, name="Canards") + controls = {f"canards.{control}": 0.0 for control in canards.controls} + view = ControlsView(controls, [canards]) + view.canards.update(canards.deflections(roll=0.05)) + assert controls == pytest.approx(dict.fromkeys(controls, -0.05)) + with pytest.raises(KeyError): + view.canards.update({"fin_9": 0.0}) + + +def _mixed_fins(cants=(0.0, 0.0)): + """Two different fins, at 30 and 200 degrees, each with its own cant.""" + small = _fin(angular_position=30, cant_angle=cants[0], name="small") + big = TrapezoidalFin( + angular_position=200, + root_chord=0.12, + tip_chord=0.03, + span=0.09, + rocket_radius=0.0635, + cant_angle=cants[1], + name="big", + ) + return [small, big] + + +def test_fins_given_one_by_one_are_flown_as_given(calisto, calisto_robust): + deflections = (0.05, -0.08) + canards = ControlFins(_mixed_fins(), name="Canards") + calisto.add_surfaces(canards, POSITION) + reference = calisto.surfaces_cp_to_cdm[canards] + fins = _mixed_fins(cants=tuple(math.degrees(d) for d in deflections)) + for fin in fins: + calisto_robust.add_surfaces(fin, POSITION) + + assert canards.n == 2 and canards.fin is None + assert canards.angular_positions == (30, 200) + assert canards.controls == ("fin_1", "fin_2") + for stream, omega in _random_states(): + speed = abs(stream) + expected = _forces_of_individual_fins( + calisto_robust, fins, stream, omega, reference + ) + got = canards.compute_forces_and_moments( + stream, speed, speed / 340, 1.1, reference, omega, controls=deflections + ) + assert np.allclose(got, expected, atol=1e-12, rtol=1e-12) + + +def test_each_fin_given_starts_at_its_own_cant(): + canards = ControlFins(_mixed_fins(cants=(1.0, -2.0)), n=2) + assert canards.control_defaults == pytest.approx( + {"fin_1": math.radians(1.0), "fin_2": math.radians(-2.0)} + ) + assert all(fin.cant_angle == 0 for fin in canards.fins) + + +def test_fins_given_one_by_one_are_saved_and_loaded(): + canards = ControlFins(_mixed_fins(cants=(1.0, 0.0)), name="Canards") + loaded = json.loads(json.dumps(canards, cls=RocketPyEncoder), cls=RocketPyDecoder) + assert loaded.fin is None and loaded.n == 2 + assert loaded.angular_positions == canards.angular_positions + assert loaded.control_defaults == pytest.approx(canards.control_defaults) + assert [fin.root_chord for fin in loaded.fins] == [0.08, 0.12] + stream = Vector([1, 2, -100]) + args = (stream, abs(stream), 0.3, 1.2, Vector([0, 0, 1]), (0.1, 0.2, 0.3)) + assert loaded.compute_forces_and_moments(*args) == pytest.approx( + canards.compute_forces_and_moments(*args) + ) + + +@pytest.mark.parametrize( + "fins, n, error", + [ + ([], None, TypeError), + ([_fin(), "not a fin"], None, TypeError), + (_mixed_fins(), 3, ValueError), + ], +) +def test_wrong_fin_sequences_are_refused(fins, n, error): + with pytest.raises(error): + ControlFins(fins, n=n) + + +def test_effectiveness_is_printed_and_plotted(capsys, tmp_path): + canards = ControlFins(_fin(), n=4, name="Canards") + canards.info() + out = capsys.readouterr().out + assert "Effectiveness at Mach 0.3" in out + assert "Roll moment coefficient per rad" in out + assert "add the set to a rocket" in out + canards.plots.effectiveness(filename=str(tmp_path / "effectiveness.png")) + assert (tmp_path / "effectiveness.png").exists() + + _placed(canards, 0.4).info() + out = capsys.readouterr().out + assert "Pitch moment coefficient per rad" in out + assert "Yaw moment coefficient per rad" in out + canards.plots.effectiveness(filename=str(tmp_path / "placed.png")) + assert (tmp_path / "placed.png").exists() + + +def test_changed_defaults_and_limits_are_saved(): + fins = ControlFins(_fin(), n=4, deflection_limits=(-0.2, 0.2)) + fins.control_defaults["fin_1"] = 0.1 + fins.control_limits["fin_2"] = (-0.1, 0.1) + loaded = ControlFins.from_dict(fins.to_dict()) + assert loaded.control_defaults == fins.control_defaults + assert loaded.control_limits == fins.control_limits + + +def test_moving_the_hinge_drops_the_frames_kept(): + fins = ControlFins(_fin(), n=4) + before = fins._frame(0, 0.1)[2] + fins.hinge_position = 0.0 + assert fins._frame(0, 0.1)[2] != before + + +def test_a_deep_copy_of_control_fins_reads_its_own_fins(monkeypatch): + """The coefficients of a copy are computed from the copy's fins, and match + the original's while the two are the same.""" + canards = ControlFins(_fin(), n=4, name="Canards") + copied = deepcopy(canards) + state = (0.05, 0.02, 0.5, 0.0, 0.0, 0.0, 0.0, 0.1, 0.05, -0.1, 0.0) + names = ("cN", "cY", "cA", "cm", "cn", "cl") + expected = [getattr(canards, name)(*state) for name in names] + + readers = [] + compute = ControlFins._coefficients_at + + def spy(self, *args): + readers.append(self) + return compute(self, *args) + + monkeypatch.setattr(ControlFins, "_coefficients_at", spy) + assert [getattr(copied, name)(*state) for name in names] == pytest.approx(expected) + assert readers and all(reader is copied for reader in readers) + assert copied.cN_alpha.slice("mach")(0.5) == pytest.approx( + canards.cN_alpha.slice("mach")(0.5) + ) + + +def test_moving_the_hinge_updates_the_coefficients(): + """The coefficients read after the hinge is moved are those of a set built + with the hinge there, also where they had already been read.""" + state = (0.05, 0.02, 0.5, 0.0, 0.0, 0.0, 0.0, 0.1, 0.05, -0.1, 0.0) + names = ("cN", "cY", "cA", "cm", "cn", "cl") + canards = ControlFins(_fin(), n=4, name="Canards", hinge_position=0.25) + before = [getattr(canards, name)(*state) for name in names] + version = canards._version + + canards.hinge_position = 0.9 + moved = ControlFins(_fin(), n=4, name="Canards", hinge_position=0.9) + expected = [getattr(moved, name)(*state) for name in names] + assert expected != pytest.approx(before) + assert [getattr(canards, name)(*state) for name in names] == pytest.approx(expected) + assert canards._version > version diff --git a/tests/unit/rocket/aero_surface/test_controllable_generic_surface.py b/tests/unit/rocket/aero_surface/test_controllable_generic_surface.py deleted file mode 100644 index 49b9b5167..000000000 --- a/tests/unit/rocket/aero_surface/test_controllable_generic_surface.py +++ /dev/null @@ -1,172 +0,0 @@ -"""Unit tests for ControllableGenericSurface and the controllable-surface -controller linkage.""" - -import pytest - -from rocketpy import ControllableGenericSurface, Function, GenericSurface -from rocketpy.mathutils.vector_matrix import Vector - -DENSITY = Function(lambda z: 1.16) -VISCOSITY = Function(lambda z: 1.8e-5) - - -def _moment_at_deflection(surface, deflection, comp="pitch"): - surface.set_control("deflection", deflection) - _, _, _, m1, m2, m3 = surface.compute_forces_and_moments( - Vector([0, 0, -100]), - 100, - 0.29, - 1.16, - Vector([0, 0, 0]), - Vector([0, 0, 0]), - DENSITY, - VISCOSITY, - 100.0, - ) - return {"pitch": m1, "yaw": m2, "roll": m3}[comp] - - -def test_control_variable_extends_independent_vars(): - surface = ControllableGenericSurface( - reference_area=1, reference_length=0.2, coefficients={} - ) - assert surface.independent_vars[:7] == [ - "alpha", - "beta", - "mach", - "reynolds", - "pitch_rate", - "yaw_rate", - "roll_rate", - ] - assert surface.independent_vars[7:] == ["deflection"] - assert surface.control_state == {"deflection": 0.0} - - -def test_deflection_produces_proportional_control_moment(): - surface = ControllableGenericSurface( - reference_area=1, - reference_length=0.2, - coefficients={"cm": lambda a, b, m, re, p, q, r, deflection: 0.5 * deflection}, - ) - m0 = _moment_at_deflection(surface, 0.0) - m1 = _moment_at_deflection(surface, 0.1) - m2 = _moment_at_deflection(surface, 0.2) - assert m0 == pytest.approx(0.0) - assert m2 == pytest.approx(2 * m1) - assert m1 != pytest.approx(0.0) - - -def test_multiple_named_controls(): - surface = ControllableGenericSurface( - reference_area=1, - reference_length=0.2, - coefficients={"cn": lambda a, b, m, re, p, q, r, dp, dy: 0.3 * dy}, - controls=("delta_pitch", "delta_yaw"), - ) - assert surface.independent_vars[7:] == ["delta_pitch", "delta_yaw"] - surface.set_control("delta_yaw", 0.5) - yaw = surface.compute_forces_and_moments( - Vector([0, 0, -100]), - 100, - 0.29, - 1.16, - Vector([0, 0, 0]), - Vector([0, 0, 0]), - DENSITY, - VISCOSITY, - 100.0, - )[4] - assert yaw != pytest.approx(0.0) - - -def test_set_control_unknown_name_raises(): - surface = ControllableGenericSurface( - reference_area=1, reference_length=0.2, coefficients={} - ) - with pytest.raises(KeyError): - surface.set_control("not_a_control", 0.1) - - -def test_plain_generic_surface_default_independent_vars_unchanged(): - surface = GenericSurface(reference_area=1, reference_length=0.2, coefficients={}) - assert surface.independent_vars == [ - "alpha", - "beta", - "mach", - "reynolds", - "pitch_rate", - "yaw_rate", - "roll_rate", - ] - - -def test_active_during_preset_round_trips_through_dict(): - """A preset activation policy survives to_dict/from_dict (jet-vane case).""" - surface = ControllableGenericSurface( - reference_area=1, - reference_length=0.2, - coefficients={}, - active_during="power_on", - ) - restored = ControllableGenericSurface.from_dict(surface.to_dict()) - assert restored.active_during == "power_on" - - -def test_starting_switched_off_round_trips_through_dict(): - """Whether the surface starts each flight switched on is saved with it.""" - surface = ControllableGenericSurface( - reference_area=1, - reference_length=0.2, - coefficients={}, - active=False, - ) - restored = ControllableGenericSurface.from_dict(surface.to_dict()) - assert restored.active is False - assert ( - ControllableGenericSurface.from_dict( - ControllableGenericSurface(1, 0.2, {}).to_dict() - ).active - is True - ) - - -def test_controls_and_coefficients_round_trip_through_dict(): - """Saving and loading keeps the control names and the coefficient values, - including for coefficients given in the wind frame.""" - surface = ControllableGenericSurface( - reference_area=0.01, - reference_length=0.1, - coefficients={ - "cL": lambda alpha, canard: 2 * alpha + 0.5 * canard, - "cD": 0.3, - }, - controls=("canard", "elevon"), - force_convention="wind", - ) - surface.set_control("canard", 0.2) - - restored = ControllableGenericSurface.from_dict(surface.to_dict()) - restored.set_control("canard", 0.2) - - assert restored.control_variables == ["canard", "elevon"] - args = (0.05, 0.02, 0.3, 0.0, 0.0, 0.0, 0.0, 0.2, 0.0) - for name in ("cN", "cY", "cA"): - assert getattr(restored, name)(*args) == pytest.approx( - getattr(surface, name)(*args) - ) - - -def test_controllable_surface_from_csv_reads_the_control_column(tmp_path): - csv_file = tmp_path / "canard.csv" - rows = [f"{d},{m},{1.5 * d * (1 + m)}" for d in (-0.2, 0.0, 0.2) for m in (0, 1, 2)] - csv_file.write_text("canard,mach,cN\n" + "\n".join(rows) + "\n") - - surface = ControllableGenericSurface.from_csv( - str(csv_file), 1.0, 1.0, controls=("canard",) - ) - surface.set_control("canard", 0.1) - - assert surface.cN.depends_on == ("canard", "mach") - args = surface._coefficient_arguments(0.0, 0.0, 1.0, 0, 0, 0, 0) - assert surface.cN(*args) == pytest.approx(0.3) diff --git a/tests/unit/rocket/aero_surface/test_generic_surfaces.py b/tests/unit/rocket/aero_surface/test_generic_surfaces.py index 1dbcca1e6..9c5250554 100644 --- a/tests/unit/rocket/aero_surface/test_generic_surfaces.py +++ b/tests/unit/rocket/aero_surface/test_generic_surfaces.py @@ -1457,3 +1457,17 @@ def test_rate_derivative_names_are_checked(): for name in ("cm_alpha", "cN_0", "cL_q"): with pytest.raises(ValueError, match="Invalid coefficient name"): GenericSurface(1.0, 1.0, {name: 1.0}) + + +def test_a_small_residual_at_zero_total_angle_is_let_through(): + """Measured and computed tables carry a little normal force at zero angle; + it is accepted up to the tolerance and refused above it.""" + fine = GenericSurface( + 1.0, 0.1, {"cN": lambda alpha_total: 2 * alpha_total + 5e-4}, name="cfd" + ) + assert fine.cN(0, 0, 0.3, 0, 0, 0, 0) == 0.0 + assert fine.cN(0.1, 0, 0.3, 0, 0, 0, 0) == pytest.approx(0.2 + 5e-4) + with pytest.raises(ValueError, match="within 0.001"): + GenericSurface( + 1.0, 0.1, {"cN": lambda alpha_total: 2 * alpha_total + 5e-3}, name="bad" + ) diff --git a/tests/unit/rocket/aero_surface/test_surface_coefficient_completeness.py b/tests/unit/rocket/aero_surface/test_surface_coefficient_completeness.py index f0df58bb0..f287b7f51 100644 --- a/tests/unit/rocket/aero_surface/test_surface_coefficient_completeness.py +++ b/tests/unit/rocket/aero_surface/test_surface_coefficient_completeness.py @@ -13,7 +13,6 @@ from rocketpy import ( AirBrakes, - ControllableGenericSurface, EllipticalFin, EllipticalFins, FreeFormFin, @@ -42,10 +41,11 @@ def _make_surfaces(): reference_length=length, coefficients={"cN_alpha": 2.0}, ), - "ControllableGenericSurface": ControllableGenericSurface( + "GenericSurfaceWithControls": GenericSurface( reference_area=area, reference_length=length, coefficients={"cL": lambda a, b, m, re, p, q, r, d: 1.0}, + controls=("deflection",), ), "AirBrakes": AirBrakes( drag_coefficient_curve=lambda deployment, mach: 0.5, diff --git a/tests/unit/rocket/aero_surface/test_surface_controls.py b/tests/unit/rocket/aero_surface/test_surface_controls.py new file mode 100644 index 000000000..3408f03a9 --- /dev/null +++ b/tests/unit/rocket/aero_surface/test_surface_controls.py @@ -0,0 +1,338 @@ +"""Unit tests for the controls of an aerodynamic surface: the extra inputs its +coefficients read, and how they are saved.""" + +import warnings + +import numpy as np +import pytest + +from rocketpy import ( + AirBrakes, + Function, + GenericSurface, + LinearGenericSurface, + StochasticAirBrakes, +) +from rocketpy.control._helpers import initial_controls +from rocketpy.mathutils.vector_matrix import Vector + +DENSITY = Function(lambda z: 1.16) +VISCOSITY = Function(lambda z: 1.8e-5) +FLOW = ( + Vector([0, 0, -100]), + 100, + 0.29, + 1.16, + Vector([0, 0, 0]), + Vector([0, 0, 0]), + DENSITY, + VISCOSITY, + 100.0, +) + + +def _canard(**kwargs): + return GenericSurface( + reference_area=1, + reference_length=0.2, + coefficients={"cm": lambda mach, deflection: 0.5 * deflection}, + name="Canards", + controls=("deflection",), + **kwargs, + ) + + +def _pitch_moment(surface, controls=None): + return surface.compute_forces_and_moments(*FLOW, controls)[3] + + +@pytest.mark.parametrize("surface_class", [GenericSurface, LinearGenericSurface]) +def test_one_control_name_given_alone_is_one_control(surface_class): + surface = surface_class(1, 0.2, {}, name="Canards", controls="deflection") + assert surface.controls == ("deflection",) + assert surface.independent_vars[-1] == "deflection" + + with pytest.raises(ValueError, match="one of the flow variables"): + surface_class(1, 0.2, {}, name="Canards", controls="mach") + + +def test_a_surface_has_no_controls_unless_given(): + surface = GenericSurface(1, 0.2, {}) + assert surface.controls == () + assert surface.control_defaults == {} + assert surface.control_limits == {} + assert surface.active is True + + +def test_a_control_extends_the_variables_of_the_coefficients(): + surface = _canard() + assert surface.controls == ("deflection",) + assert surface.independent_vars == [ + "alpha", + "beta", + "mach", + "reynolds", + "pitch_rate", + "yaw_rate", + "roll_rate", + "deflection", + ] + assert surface.control_defaults == {"deflection": 0.0} + assert surface.control_limits == {"deflection": None} + + +def test_the_controls_given_produce_a_proportional_moment(): + surface = _canard() + m0 = _pitch_moment(surface, [0.0]) + m1 = _pitch_moment(surface, [0.1]) + m2 = _pitch_moment(surface, [0.2]) + assert m0 == pytest.approx(0.0) + assert m1 != pytest.approx(0.0) + assert m2 == pytest.approx(2 * m1) + + +def test_without_controls_the_defaults_are_used(): + """Outside a flight a surface is evaluated at its defaults, the same as + with those values given explicitly.""" + surface = _canard(control_defaults={"deflection": 0.1}) + assert _pitch_moment(surface) == _pitch_moment(surface, [0.1]) + assert surface._coefficient_arguments(0, 0, 0.5, 0, 0, 0, 0) == ( + surface._coefficient_arguments(0, 0, 0.5, 0, 0, 0, 0, controls=[0.1]) + ) + # a surface without controls is called with the seven flow variables + plain = GenericSurface(1, 0.2, {"cA": 0.4}) + assert plain._coefficient_arguments(1, 2, 3, 4, 5, 6, 7) == (1, 2, 3, 4, 5, 6, 7) + assert plain._coefficient_arguments(1, 2, 3, 4, 5, 6, 7, controls=[]) == ( + 1, + 2, + 3, + 4, + 5, + 6, + 7, + ) + + +def test_several_controls_keep_their_order(): + surface = GenericSurface( + 1, + 0.2, + {"cn": lambda delta_pitch, delta_yaw: 0.3 * delta_yaw}, + controls=("delta_pitch", "delta_yaw"), + ) + assert surface.independent_vars[7:] == ["delta_pitch", "delta_yaw"] + yaw = surface.compute_forces_and_moments(*FLOW, [0.0, 0.5])[4] + assert yaw != pytest.approx(0.0) + assert surface.compute_forces_and_moments(*FLOW, [0.5, 0.0])[4] == 0.0 + + +def test_defaults_outside_the_limits_are_clamped(): + clamped = _canard( + control_defaults={"deflection": 0.5}, control_limits={"deflection": (-0.2, 0.2)} + ) + assert clamped.control_defaults["deflection"] == 0.2 + free = _canard(control_defaults={"deflection": 0.5}) + assert free.control_defaults["deflection"] == 0.5 + + +@pytest.mark.parametrize( + "controls, match", + [ + (("mach",), "one of the flow variables"), + (("alpha_deg",), "one of the flow variables"), + (("deflection", "deflection"), "lists a control more than once"), + (("2nd",), "must be made of letters"), + (("_hidden",), "must be made of letters"), + ], +) +def test_a_bad_control_name_is_refused(controls, match): + with pytest.raises(ValueError, match=match): + GenericSurface(1, 0.2, {}, controls=controls) + + +def test_defaults_and_limits_must_name_a_control(): + with pytest.raises(ValueError, match="control_defaults for \\['flap'\\]"): + _canard(control_defaults={"flap": 0.1}) + with pytest.raises(ValueError, match="control_limits for \\['flap'\\]"): + _canard(control_limits={"flap": (0, 1)}) + with pytest.raises(ValueError, match="must not be larger"): + _canard(control_limits={"deflection": (0.2, -0.2)}) + + +def test_a_flight_never_changes_the_surface(): + """A controller writes the flight's control inputs: the surface keeps no + state.""" + surface = _canard() + before = dict(surface.control_defaults) + controls, _, _ = initial_controls([surface]) + controls["canards.deflection"] = 0.15 + assert surface.control_defaults == before + assert not hasattr(surface, "control_state") + assert _pitch_moment(surface) == pytest.approx(0.0) + + +def test_controls_round_trip_through_dict(): + surface = GenericSurface( + reference_area=0.01, + reference_length=0.1, + coefficients={ + "cL": lambda alpha, canard: 2 * alpha + 0.5 * canard, + "cD": 0.3, + }, + controls=("canard", "elevon"), + control_defaults={"canard": 0.05}, + control_limits={"canard": (-0.3, 0.3)}, + force_convention="wind", + active_during="power_on", + active=False, + ) + restored = GenericSurface.from_dict(surface.to_dict()) + + assert restored.controls == ("canard", "elevon") + assert restored.control_defaults == surface.control_defaults + assert restored.control_limits == surface.control_limits + assert restored.active_during == "power_on" + assert restored.active is False + args = (0.05, 0.02, 0.3, 0.0, 0.0, 0.0, 0.0, 0.2, 0.0) + for name in ("cN", "cY", "cA"): + assert getattr(restored, name)(*args) == pytest.approx( + getattr(surface, name)(*args) + ) + + +def test_a_surface_without_controls_saves_as_before(): + data = GenericSurface(1, 0.2, {"cA": 0.4}).to_dict() + assert "controls" not in data + assert data["active"] is True + + +def test_from_csv_reads_the_control_column(tmp_path): + csv_file = tmp_path / "canard.csv" + rows = [f"{d},{m},{1.5 * d * (1 + m)}" for d in (-0.2, 0.0, 0.2) for m in (0, 1, 2)] + csv_file.write_text("canard,mach,cN\n" + "\n".join(rows) + "\n") + + surface = GenericSurface.from_csv( + str(csv_file), 1.0, 1.0, controls=("canard",), control_defaults={"canard": 0.1} + ) + + assert surface.cN.depends_on == ("canard", "mach") + args = surface._coefficient_arguments(0.0, 0.0, 1.0, 0, 0, 0, 0) + assert surface.cN(*args) == pytest.approx(0.3) + + +def test_the_stability_slopes_are_taken_at_the_control_defaults(): + """A moment coupling the angle of attack and a control gives a slope that + depends on the control; the stability analysis reads it at the default.""" + coefficients = { + "cN": lambda alpha: 2.0 * alpha, + "cm": lambda alpha, deflection: (1.0 + deflection) * alpha, + } + at_zero = GenericSurface(1, 0.2, coefficients, controls=("deflection",)) + at_half = GenericSurface( + 1, + 0.2, + coefficients, + controls=("deflection",), + control_defaults={"deflection": 0.5}, + ) + assert at_zero.cm_alpha(0, 0, 0.3, 0, 0, 0, 0, 0) == pytest.approx(1.0) + assert at_half.cm_alpha(0, 0, 0.3, 0, 0, 0, 0, 0) == pytest.approx(1.5) + assert at_half.aerodynamic_center(0.3) != at_zero.aerodynamic_center(0.3) + + +def test_a_linear_surface_can_have_controls(): + surface = LinearGenericSurface( + 0.01, + 0.1, + {"cl_0": lambda mach, deflection: 0.5 * deflection}, + controls=("deflection",), + control_defaults={"deflection": 0.2}, + ) + assert surface.controls == ("deflection",) + assert surface.cl.get_value_opt(0, 0, 0.5, 0, 0, 0, 0, 0.1) == pytest.approx(0.05) + restored = LinearGenericSurface.from_dict(surface.to_dict()) + assert restored.control_defaults == {"deflection": 0.2} + + +# --------------------------------------------------------------------------- +# Air brakes +# --------------------------------------------------------------------------- + + +def _air_brakes(**kwargs): + return AirBrakes( + drag_coefficient_curve=lambda deployment_level, mach: deployment_level, + reference_area=0.01, + **kwargs, + ) + + +def test_air_brakes_have_one_control_with_limits(): + air_brakes = _air_brakes(deployment_level=0.3) + assert air_brakes.controls == ("deployment_level",) + assert air_brakes.control_defaults == {"deployment_level": 0.3} + assert air_brakes.control_limits["deployment_level"] == (0, 1) + assert air_brakes.clamp is True + + +def test_the_initial_deployment_level_is_the_default(): + """It is the level every flight starts at, clamped like a write.""" + air_brakes = _air_brakes() + air_brakes.initial_deployment_level = 0.4 + assert air_brakes.control_defaults["deployment_level"] == 0.4 + air_brakes.initial_deployment_level = 1.5 + assert air_brakes.initial_deployment_level == 1 + loose = _air_brakes(clamp=False) # no limit at all + loose.initial_deployment_level = 1.5 + assert loose.initial_deployment_level == 1.5 + + +def test_deployment_level_is_a_deprecated_name_of_the_initial_level(): + air_brakes = _air_brakes() + with pytest.warns(DeprecationWarning, match="initial_deployment_level"): + air_brakes.deployment_level = 0.4 + assert air_brakes.initial_deployment_level == 0.4 + with pytest.warns(DeprecationWarning, match="flight.controls"): + assert air_brakes.deployment_level == 0.4 + + +def test_air_brakes_drag_follows_the_deployment_given(): + air_brakes = _air_brakes(deployment_level=0.3) + args = (0, 0, 0.3, 0, 0, 0, 0) + assert air_brakes.cA(*air_brakes._coefficient_arguments(*args)) == 0.3 + assert air_brakes.cA( + *air_brakes._coefficient_arguments(*args, controls=[0.8]) + ) == pytest.approx(0.8) + # retracted brakes add no drag, unless they replace the rocket's drag + assert air_brakes.cA(*air_brakes._coefficient_arguments(*args, controls=[0])) == 0 + + +def test_air_brakes_round_trip_keeps_their_deployment_level(): + air_brakes = _air_brakes(deployment_level=0.25, clamp=False) + with warnings.catch_warnings(): + warnings.simplefilter("error") + restored = AirBrakes.from_dict(air_brakes.to_dict()) + assert restored.initial_deployment_level == 0.25 + assert restored.clamp is False + + +def test_dispersed_air_brakes_keep_their_name(): + """The name names the control channels, so a Monte Carlo copy keeps it.""" + air_brakes = _air_brakes(name="Upper Brakes") + copy = StochasticAirBrakes(air_brakes=air_brakes).create_object() + assert copy.name == "Upper Brakes" + assert initial_controls([copy])[0] == {"upper_brakes.deployment_level": 0.0} + + +def test_prints_and_plots_read_the_surface_at_its_defaults(capsys): + surface = GenericSurface( + 1, + 0.2, + {"cN": lambda alpha, deflection: 2 * alpha + deflection}, + controls=("deflection",), + control_defaults={"deflection": 0.1}, + ) + assert surface._reference_arguments() == [0.0] * 7 + [0.1] + surface.prints.coefficients() + expected = 2 * np.deg2rad(5) + 0.1 + assert f"cN = {expected:.4f}" in capsys.readouterr().out diff --git a/tests/unit/rocket/test_effectors.py b/tests/unit/rocket/test_effectors.py new file mode 100644 index 000000000..2a0349d37 --- /dev/null +++ b/tests/unit/rocket/test_effectors.py @@ -0,0 +1,496 @@ +"""Effectors, the controllables with controls that are not aerodynamic surfaces: +adding them to a rocket, the generic effector, and the hooks that bring them +into the equations of motion.""" + +import json +import math +import warnings +from types import SimpleNamespace + +import pytest + +from rocketpy import Controller, GenericSurface +from rocketpy._encoders import RocketPyDecoder, RocketPyEncoder +from rocketpy.control import ( + Controllable, + FlightConditions, + ForceEffector, + ThrustEffector, +) +from rocketpy.control._helpers import initial_controls +from rocketpy.mathutils.vector_matrix import Vector +from rocketpy.simulation.helpers.dynamics import ( + SIX_DOF_DYNAMICS, + _with_controllables, +) +from rocketpy.simulation.helpers.flight_derivatives import ( + _effector_force_and_moment, + _effector_thrust, +) +from tests.fixtures.effectors.effector_fixtures import Gimbal + + +def _flight_of(rocket): + """A stand-in flight with the control inputs of ``rocket``.""" + controls, channels, limits = initial_controls(rocket.controllables) + flight = SimpleNamespace( + rocket=rocket, + _controls=controls, + _control_names=channels, + _control_limits=limits, + env=None, + ) + return flight + + +def _conditions(flight, t=0.0): + """What the stand-in flight's effectors are told at ``t``.""" + return FlightConditions(flight.rocket, flight.env, t, [0.0] * 13) + + +def test_the_conditions_give_the_state_by_name_and_the_height_above_ground(): + env = SimpleNamespace(elevation=100.0) + state = [0.0, 0.0, 350.0, 1.0, 2.0, 3.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5] + conditions = FlightConditions(None, env, 0.0, state) + assert conditions.state.w3 == 0.5 + assert conditions.state[12] == 0.5 + assert conditions.state.vz == conditions.state[5] == 3.0 + assert conditions.height_agl == 250.0 + # a state the phase follows besides the thirteen is read by its name + more = FlightConditions(None, env, 0.0, state, (*"abc", "fuel"), [0, 0, 0, 7.0]) + assert more.state.fuel == 7.0 + assert more.state.w3 == 0.5 + + +class _Both(Gimbal, ForceEffector): + """Turns the thrust and pushes the rocket: filed under both kinds.""" + + def force_and_moment(self, controls, conditions): # pylint: disable=unused-argument + return [0, 0, 0], [0, 0, 0] + + +def test_add_effector_files_the_part_by_what_it_does(calisto, gimbal, push_effector): + calisto.add_effector(gimbal) + calisto.add_effector(push_effector) + + assert calisto.effectors.get_components() == [gimbal, push_effector] + assert calisto._thrust_effectors == (gimbal,) + assert calisto._force_effectors == (push_effector,) + assert calisto.control_names[-2:] == ("gimbal.pitch", "push.on") + + +def test_a_part_that_acts_in_two_ways_has_its_channels_once(calisto): + both = _Both(name="Vectored Thruster") + calisto.add_effector(both) + assert calisto.effectors.get_components() == [both] + assert calisto._thrust_effectors == (both,) + assert calisto._force_effectors == (both,) + assert calisto.control_names.count("vectored_thruster.pitch") == 1 + + +def test_add_effector_refuses_what_is_not_a_part_with_controls(calisto): + with pytest.raises(TypeError, match="ThrustEffector or ForceEffector"): + calisto.add_effector(SimpleNamespace(name="x", controls=())) + + +def test_add_effector_refuses_a_surface(calisto): + with pytest.raises(TypeError, match="add_surfaces"): + calisto.add_effector(GenericSurface(1.0, 1.0, {}, name="Canards")) + + +def test_an_effector_without_its_method_cannot_be_built(): + class Forgetful(ThrustEffector): + """A thrust effector that does not say what it does to the thrust.""" + + with pytest.raises(TypeError, match="needs a thrust_and_nozzle"): + Forgetful(name="Forgetful") + with pytest.raises(TypeError, match="needs a force_and_moment"): + ForceEffector(name="Forgetful") + + +class _Canopy(Controllable): + def __init__(self): + super().__init__("Canopy", ("brake",)) + + +def test_a_part_with_no_physics_is_refused(calisto): + """A controllable that is none of the three kinds of effector would do nothing in + a flight, so adding it as one is an error, not a silent no-op.""" + with pytest.raises(TypeError, match="ThrustEffector or ForceEffector"): + calisto.add_effector(_Canopy()) + assert len(calisto.effectors) == 0 + assert calisto.control_names == () + + +class _Damper(ForceEffector): + """A controllable with a state of its own and no controls.""" + + states = ("deflection",) + + def __init__(self): + super().__init__(name="Damper") + + def force_and_moment(self, controls, conditions): + return [0.0, 0.0, 0.0], [0.0, 0.0, 0.0] + + +def test_a_part_with_states_and_no_controls_is_still_integrated(calisto): + damper = _Damper() + calisto.add_effector(damper) + assert calisto.controllables == () + extended = _with_controllables(SIX_DOF_DYNAMICS, calisto) + assert extended.states[-1] == "damper_deflection" + + +def test_add_effector_refuses_a_name_already_used(calisto, gimbal): + calisto.add_effector(gimbal) + with pytest.raises(ValueError, match="both have controls"): + calisto.add_effector(Gimbal()) + assert calisto.effectors.get_components() == [gimbal] + + +def test_effectors_take_no_part_in_stability(calisto, push_effector, side_effector): + margin = calisto.static_margin(0) + center = calisto.aerodynamic_center(0.3) + calisto.add_effector(push_effector) + calisto.add_effector(side_effector) + assert calisto.static_margin(0) == margin + assert calisto.aerodynamic_center(0.3) == center + assert all( + not isinstance(surface, ForceEffector) + for surface, _ in calisto.aerodynamic_surfaces + ) + + +def test_effectors_are_not_in_the_surface_of_the_whole_rocket( + calisto_robust, push_effector +): + before = calisto_robust.to_surface() + calisto_robust.add_effector(push_effector) + after = calisto_robust.to_surface() + arguments = (0.05, 0.0, 0.3, 1e6, 0.0, 0.0, 0.0) + for old, new in zip(before, after): + assert new.controls == () + assert new.cN(*arguments) == old.cN(*arguments) + + +def test_an_effector_built_from_a_function_is_given_the_controls_spread_out(): + effector = ForceEffector( + lambda a, b, conditions: ([a, b, 0], [0, 0, a * b * conditions]), + controls=("a", "b"), + control_defaults={"b": 2.0}, + name="RCS Pair", + ) + force, moment = effector.force_and_moment([3.0, 2.0], 0.5) + assert list(force) == [3.0, 2.0, 0] and list(moment) == [0, 0, 3.0] + assert effector.control_defaults == {"a": 0.0, "b": 2.0} + assert repr(effector) == "ForceEffector(name='RCS Pair', controls=('a', 'b'))" + + gimbal = ThrustEffector( + lambda thrust, nozzle, pitch, conditions: ( + [thrust[2] * pitch, 0, thrust[2]], + [pitch, 0, nozzle[2]], + ), + controls=("pitch",), + name="Gimbal", + ) + assert gimbal.thrust_and_nozzle([0, 0, 10.0], [0, 0, -1.0], [0.1], None) == ( + [1.0, 0, 10.0], + [0.1, 0, -1.0], + ) + + +@pytest.mark.parametrize( + "function", [lambda conditions: None, lambda: None, "not a function"] +) +def test_an_effector_checks_its_function(function): + with pytest.raises(TypeError, match="force_and_moment"): + ForceEffector(function, controls=("on",)) + with pytest.raises(TypeError, match="thrust_and_nozzle"): + ThrustEffector(function, controls=("on",)) + + +def test_an_effector_built_from_a_function_is_saved_and_loaded(calisto, push_effector): + calisto.add_effector(push_effector) + loaded = json.loads(json.dumps(calisto, cls=RocketPyEncoder), cls=RocketPyDecoder) + (effector,) = loaded.effectors.get_components() + assert type(effector) is ForceEffector # pylint: disable=unidiomatic-typecheck + assert effector.name == "Push" + assert effector.control_limits == {"on": (0, 1)} + assert list(effector.force_and_moment([1.0], None)[0]) == [0, 0, 10.0] + assert loaded.control_names == calisto.control_names + + +def test_a_part_written_by_the_user_is_saved_and_loaded(calisto, gimbal): + """A subclass of an effector class holds its physics in code, so it is + saved pickled and comes back as the same class, controls included.""" + calisto.add_effector(gimbal) + with warnings.catch_warnings(): + warnings.simplefilter("error") + text = json.dumps(calisto, cls=RocketPyEncoder) + loaded = json.loads(text, cls=RocketPyDecoder) + assert [type(c) for c in loaded.effectors.get_components()] == [Gimbal] + assert loaded.control_names == calisto.control_names + assert loaded.effectors[0].component.control_limits == gimbal.control_limits + # Readable next to the pickled controllable + saved = json.loads(text)["effectors"][0][0] # [component, position] pairs + assert saved["name"] == "Gimbal" and saved["controls"] == ["pitch"] + + +def test_a_part_saved_without_pickling_is_left_out_with_a_warning( + calisto, gimbal, push_effector +): + calisto.add_effector(gimbal) + calisto.add_effector(push_effector) + text = json.dumps(calisto, cls=RocketPyEncoder, allow_pickle=False) + with pytest.warns(UserWarning, match="'Gimbal' could not be loaded"): + with pytest.warns(UserWarning, match="'Push' could not be loaded"): + loaded = json.loads(text, cls=RocketPyDecoder) + assert len(loaded.effectors) == 0 + assert loaded.control_names == () + + +def test_the_gimbal_turns_the_thrust_and_makes_a_moment(calisto, gimbal): + calisto.add_effector(gimbal) + flight = _flight_of(calisto) + flight._controls["gimbal.pitch"] = 0.1 + + force, moment, _ = _effector_thrust( + flight, _conditions(flight, 1.0), 1000.0, flight._controls + ) + + assert list(force) == pytest.approx([1000 * math.sin(0.1), 0, 1000 * math.cos(0.1)]) + # the nozzle is behind the center of dry mass, so a thrust tipped toward + # +x turns the nose toward -x: a negative moment about y + lever = calisto.nozzle_to_cdm + assert list(moment) == pytest.approx([0, -lever * 1000 * math.sin(0.1), 0]) + + +def test_the_thrust_moment_includes_the_eccentricity(calisto): + calisto.add_thrust_eccentricity(x=0.01, y=-0.02) + calisto.add_effector(Gimbal()) + flight = _flight_of(calisto) + _, moment, _ = _effector_thrust( + flight, _conditions(flight, 1.0), 1000.0, flight._controls + ) + # as the equations without effectors add it: M1 += ey T, M2 -= ex T + assert list(moment) == pytest.approx( + [ + calisto.thrust_eccentricity_y * 1000, + -calisto.thrust_eccentricity_x * 1000, + 0, + ] + ) + + +def test_the_nozzle_exit_is_behind_the_center_of_dry_mass(calisto): + calisto.add_thrust_eccentricity(x=0.01, y=-0.02) + assert list(calisto.nozzle_exit) == pytest.approx( + [0.01, -0.02, -calisto.nozzle_to_cdm] + ) + + +def test_effectors_add_up(calisto, push_effector, side_effector): + calisto.add_effector(push_effector) + calisto.add_effector(side_effector) + flight = _flight_of(calisto) + flight._controls.update({"push.on": 1.0, "side.on": 0.5}) + force, moment = _effector_force_and_moment( + flight, _conditions(flight), flight._controls + ) + assert list(force) == [5.0, 0.0, 10.0] + assert list(moment) == [0.0, 0.0, 0.5] + + +def _sideways(on, conditions): # pylint: disable=unused-argument + """10 N toward +x and a 0.5 N m couple about the axis, when on.""" + return [10.0 * on, 0.0, 0.0], [0.0, 0.0, 0.5 * on] + + +def test_a_placed_effector_makes_the_moment_of_its_force(calisto): + cdm = calisto.center_of_dry_mass_position + calisto.add_effector( + ForceEffector(_sideways, controls=("on",), name="Side"), position=cdm + 0.4 + ) + assert calisto.effectors[0].position == Vector([0, 0, cdm + 0.4]) + flight = _flight_of(calisto) + flight._controls["side.on"] = 1.0 + force, moment = _effector_force_and_moment( + flight, _conditions(flight), flight._controls + ) + assert list(force) == [10.0, 0.0, 0.0] + # r x F = (0, 0, 0.4) x (10, 0, 0) = (0, 4, 0), plus the couple returned + assert list(moment) == pytest.approx([0.0, 4.0, 0.5]) + + +def _roll_push(on, conditions): # pylint: disable=unused-argument + """10 N in the positive roll direction at angular position 90, when on: + (-cos 90, -sin 90, 0) = (0, -1, 0).""" + return [0.0, -10.0 * on, 0.0], [0.0, 0.0, 0.0] + + +@pytest.mark.parametrize("fixture", ["calisto", "calisto_nose_to_tail"]) +def test_an_effector_is_placed_around_the_tube_like_a_fin(request, fixture): + rocket = request.getfixturevalue(fixture) + cdm = rocket.center_of_dry_mass_position + rocket.add_effector( + ForceEffector(_roll_push, controls=("on",), name="Roll"), + position=cdm + 0.2 * rocket._csys, + angular_position=90, + radius=0.1, + ) + # In the user's coordinate system the x axis flips with the orientation + assert list(rocket.effectors[0].position) == pytest.approx( + [-0.1 * rocket._csys, 0.0, cdm + 0.2 * rocket._csys] + ) + # In the body frame the point is the same: on -x, 0.2 m toward the nose + point = rocket._effector_points[rocket.effectors[0].component] + assert list(point) == pytest.approx([-0.1, 0.0, 0.2]) + flight = _flight_of(rocket) + flight._controls["roll.on"] = 1.0 + _, moment = _effector_force_and_moment( + flight, _conditions(flight), flight._controls + ) + # A tangential force at radius R gives a roll moment R F, positive here + assert list(moment) == pytest.approx([2.0, 0.0, 1.0]) + + +def test_an_effector_is_placed_from_the_center_of_dry_mass(calisto): + # The center of mass eccentricity moves the center of dry mass off the + # axis, and with it the lever arm of an effector, as for a surface + cdm = calisto.center_of_dry_mass_position + effector = ForceEffector(_roll_push, controls=("on",), name="Roll") + calisto.add_effector(effector, position=(0.1, 0.0, cdm + 0.2)) + assert list(calisto._effector_points[effector]) == pytest.approx([0.1, 0.0, 0.2]) + calisto.add_cm_eccentricity(0.01, -0.02) + assert list(calisto._effector_points[effector]) == pytest.approx([0.09, 0.02, 0.2]) + + +def test_an_effector_is_added_once(calisto, push_effector): + calisto.add_effector(push_effector) + with pytest.raises(ValueError, match="already on the rocket"): + calisto.add_effector(push_effector, position=0.5) + assert len(calisto.effectors) == 1 + + +def test_an_effector_placed_at_a_point_takes_no_angular_position(calisto): + effector = ForceEffector(_roll_push, controls=("on",), name="Roll") + calisto.add_effector(effector, position=(0.1, 0.2, 0.3)) + assert calisto.effectors[0].position == Vector([0.1, 0.2, 0.3]) + with pytest.raises(ValueError, match="not used"): + calisto.add_effector( + ForceEffector(_roll_push, controls=("on",), name="Other"), + position=(0.1, 0.2, 0.3), + radius=1, + ) + + +def test_an_effector_placement_is_checked(calisto, gimbal): + with pytest.raises(TypeError, match="acts at the motor's nozzle"): + calisto.add_effector(gimbal, position=0.5) + with pytest.raises(ValueError, match="no position"): + calisto.add_effector( + ForceEffector(_roll_push, controls=("on",), name="Roll"), radius=0.1 + ) + assert len(calisto.effectors) == 0 + + +def test_a_placed_effector_is_saved_and_loaded(calisto, side_effector): + calisto.add_effector(side_effector, position=0.7, angular_position=45, radius=0.05) + loaded = json.loads(json.dumps(calisto, cls=RocketPyEncoder), cls=RocketPyDecoder) + assert list(loaded.effectors[0].position) == pytest.approx( + list(calisto.effectors[0].position) + ) + loaded_point = loaded._effector_points[loaded.effectors[0].component] + point = calisto._effector_points[side_effector] + assert list(loaded_point) == pytest.approx(list(point)) + + +def test_controllables_are_only_the_parts_with_controls(calisto, gimbal): + # calisto's nose cone, fins and tail have no controls + assert calisto.controllables == () + canards = GenericSurface(1.0, 1.0, {}, name="Canards", controls=("deflection",)) + calisto.add_surfaces(canards, 0.5) + calisto.add_effector(gimbal) + assert calisto.controllables == (canards, gimbal) + + +class _PivotedGimbal(Gimbal): + """A gimbal that turns the nozzle about a pivot ``length`` above its exit, + so the exit moves with it.""" + + def __init__(self, length): + super().__init__() + self.length = length + + def thrust_and_nozzle(self, thrust, nozzle, controls, conditions): + turned, _ = super().thrust_and_nozzle(thrust, nozzle, controls, conditions) + angle = controls[0] + pivot = nozzle + Vector([0, 0, self.length]) + # the nozzle points backwards: turning the thrust toward +x swings + # the exit toward -x + offset = Vector( + [-self.length * math.sin(angle), 0, -self.length * math.cos(angle)] + ) + return turned, pivot + offset + + +def test_a_moved_nozzle_sets_the_moment_of_the_thrust(calisto): + """The turned thrust acts along a line through the pivot, so the moment's + lever is the pivot's distance to the center of dry mass, not the exit's.""" + calisto.add_effector(_PivotedGimbal(length=0.1)) + flight = _flight_of(calisto) + flight._controls["gimbal.pitch"] = 0.1 + force, moment, nozzle = _effector_thrust( + flight, _conditions(flight, 1.0), 1000.0, flight._controls + ) + pivot_lever = calisto.nozzle_to_cdm - 0.1 + assert list(moment) == pytest.approx([0, -pivot_lever * force.x, 0]) + assert list(nozzle) == pytest.approx( + [-0.1 * math.sin(0.1), 0, -pivot_lever - 0.1 * math.cos(0.1)] + ) + + +def test_a_nozzle_no_effector_moves_stays_at_the_rocket_exit(calisto, gimbal): + calisto.add_effector(gimbal) + flight = _flight_of(calisto) + nozzle = _effector_thrust(flight, _conditions(flight), 1000.0, flight._controls)[2] + assert list(nozzle) == list(calisto.nozzle_exit) + + +def test_an_effector_reads_its_own_states(calisto): + class Thruster(ForceEffector): + """A thruster whose force follows the gas it has left.""" + + states = ("gas",) + + def force_and_moment(self, controls, conditions): + (gas,) = conditions.states_of(self) + return [0, 0, gas], [0, 0, 0] + + calisto.add_effector(Thruster(name="Thruster")) + flight = _flight_of(calisto) + # the flight follows the controllable's states by name with the rocket's + conditions = FlightConditions( + flight.rocket, flight.env, 0.0, [0.0] * 13, ("thruster_gas",), [0.7] + ) + force, _ = _effector_force_and_moment(flight, conditions, flight._controls) + assert force.z == 0.7 + + +def test_the_rocket_prints_what_controls_it(calisto, gimbal, push_effector, capsys): + """Its controllers, each part with controls and where each effector acts.""" + calisto.add_effector(gimbal) + calisto.add_effector(push_effector, position=0.4) + calisto.add_controller(Controller(lambda context: None, 10, name="Sampled")) + calisto.prints.all() + out = capsys.readouterr().out + assert "Controller 'Sampled' with sampling rate 10 Hz." in out + assert "context.controls.gimbal." in out + assert "'Gimbal', acting on the motor's thrust" in out + assert "'Push', at (" in out + + +def test_a_rocket_without_controls_prints_no_controls_block(calisto, capsys): + calisto.prints.all() + assert "Controls" not in capsys.readouterr().out diff --git a/tests/unit/rocket/test_parachute.py b/tests/unit/rocket/test_parachute.py index 215bbc29e..b3419a897 100644 --- a/tests/unit/rocket/test_parachute.py +++ b/tests/unit/rocket/test_parachute.py @@ -230,8 +230,8 @@ def _noise_context(pressure=90000.0, vz=-10.0): raw_state=state, phase_names=(), height_agl=500.0, - pressure=pressure, - sensors=[], + conditions=SimpleNamespace(pressure=pressure), + sensors={}, environment=SimpleNamespace( barometric_height=SimpleNamespace(get_value_opt=lambda p: 100000.0 - p), elevation=9500.0, diff --git a/tests/unit/rocket/test_rocket.py b/tests/unit/rocket/test_rocket.py index 724a6f8fb..2a3fbb47f 100644 --- a/tests/unit/rocket/test_rocket.py +++ b/tests/unit/rocket/test_rocket.py @@ -1247,3 +1247,85 @@ def test_axisymmetric_linear_surface_refuses_what_singles_out_a_plane(): ) assert surface.cN(0.2, 0, 0, 0, 0, 0, 0) == pytest.approx(1.48) assert surface.cY(0, 0.2, 0, 0, 0, 0, 0) == pytest.approx(-1.48) + + +def test_nozzle_gyration_tensor_follows_the_thrust_eccentricity(calisto): + """The tensor of a disk at the nozzle exit, about the center of dry mass: + the on-axis one plus the parallel axis terms of the eccentricity.""" + on_axis = calisto.nozzle_gyration_tensor + calisto.add_thrust_eccentricity(0.003, -0.002) + x, y, z = calisto.nozzle_exit + tensor = calisto.nozzle_gyration_tensor + assert tensor[0][0] == pytest.approx(on_axis[0][0] + y**2) + assert tensor[1][1] == pytest.approx(on_axis[1][1] + x**2) + assert tensor[2][2] == pytest.approx(on_axis[2][2] + x**2 + y**2) + assert tensor[0][1] == pytest.approx(-x * y) + assert tensor[0][2] == pytest.approx(-x * z) + assert tensor[1][2] == pytest.approx(-y * z) + + +def test_a_surface_added_again_with_a_position_is_placed_there(calisto): + surface = GenericSurface(0.01, 0.1, {"cN": 1.0}, name="Probe") + calisto.add_surfaces(surface, None) + assert calisto._is_at_center_of_dry_mass(surface) + calisto.add_surfaces(surface, 0.5) + assert not calisto._is_at_center_of_dry_mass(surface) + + +def test_static_margin_of_a_surface_at_the_center_of_dry_mass_ignores_motor_order( + cesaroni_m1670, +): + """A surface added without a position follows the center of dry mass, so + the static margin is the same whether the motor is added before or after.""" + + def build(motor_first): + rocket = Rocket( + radius=0.0635, + mass=14.426, + inertia=(6.321, 6.321, 0.034), + power_off_drag=0.5, + power_on_drag=0.5, + center_of_mass_without_motor=0, + coordinate_system_orientation="tail_to_nose", + ) + surface = LinearGenericSurface( + rocket.area, + 2 * rocket.radius, + {"cN_alpha": 5.0, "cm_alpha": -3.0}, + axisymmetric=True, + ) + if motor_first: + rocket.add_motor(cesaroni_m1670, position=-1.373) + rocket.add_full_body_aerodynamics(surface) + else: + rocket.add_full_body_aerodynamics(surface) + rocket.add_motor(cesaroni_m1670, position=-1.373) + return rocket, surface + + after, surface_after = build(motor_first=True) + before, surface_before = build(motor_first=False) + assert before.static_margin(0) == pytest.approx(after.static_margin(0)) + for rocket, surface in ((after, surface_after), (before, surface_before)): + ((_, position),) = rocket.aerodynamic_surfaces + assert position.z == pytest.approx(rocket.center_of_dry_mass_position) + assert list(rocket.surfaces_cp_to_cdm[surface]) == [0, 0, 0] + + +def test_a_surface_shared_by_two_rockets_keeps_its_place_on_each(calisto): + """Where a surface sits is kept by each rocket: placing it on a second + rocket does not move it on the first.""" + other = Rocket( + radius=0.0635, + mass=14.426, + inertia=(6.321, 6.321, 0.034), + power_off_drag=0.5, + power_on_drag=0.5, + center_of_mass_without_motor=0, + ) + surface = GenericSurface(0.01, 0.1, {"cN": 1.0}, name="Probe") + calisto.add_surfaces(surface, None) + other.add_surfaces(surface, 0.5) + assert calisto._is_at_center_of_dry_mass(surface) + assert not other._is_at_center_of_dry_mass(surface) + calisto._refresh_aerodynamics() + assert list(calisto.surfaces_cp_to_cdm[surface]) == [0, 0, 0] diff --git a/tests/unit/rocket/test_stability_rework.py b/tests/unit/rocket/test_stability_rework.py index b1505e0f9..99a47eec2 100644 --- a/tests/unit/rocket/test_stability_rework.py +++ b/tests/unit/rocket/test_stability_rework.py @@ -11,7 +11,6 @@ import pytest from rocketpy import ( - ControllableGenericSurface, Function, GenericSurface, LinearGenericSurface, @@ -351,6 +350,26 @@ def test_add_full_body_aerodynamics_single_phase(calisto_robust): assert surface.active_during == "power_off" +def test_add_full_body_aerodynamics_overwrite_keeps_the_air_brakes(calisto_robust): + """The air brakes and the controller that sets them go together: an + overwrite keeps both, so the controller still finds its control input.""" + rocket = calisto_robust + air_brakes = rocket.add_air_brakes( + drag_coefficient_curve=0.5, + controller_function=lambda context: None, + sampling_rate=10, + ) + surface = _full_body_surface(rocket, {"cA": 0.4}) + with pytest.warns(UserWarning, match="Air brakes, if any, are kept"): + rocket.add_full_body_aerodynamics(surface, overwrite=True) + + assert rocket.aerodynamic_surfaces.get_components() == [air_brakes, surface] + assert rocket.control_names == ("air_brakes.deployment_level",) + assert len(rocket.controllers) == 1 + assert rocket._is_at_center_of_dry_mass(air_brakes) + assert set(rocket.surfaces_cp_to_cdm) == {air_brakes, surface} + + def test_add_full_body_aerodynamics_overwrite_replaces_surfaces_and_drag( calisto_robust, ): @@ -1014,7 +1033,7 @@ def test_lumping_follows_the_reynolds_number(model): def _canard(name): area, diameter = math.pi * 0.0635**2, 2 * 0.0635 - return ControllableGenericSurface( + return GenericSurface( area, diameter, { @@ -1022,16 +1041,18 @@ def _canard(name): "cY": lambda beta: -1.5 * beta, }, name=name, + controls=("deflection",), ) def test_lumping_keeps_a_control(): """A control listed in ``controls`` becomes an input of the coefficients, - the surface built from them is controllable and matches the rocket at a - deflection, and the rocket's own control is left where it was.""" + the surface built from them has that control and matches the rocket at a + deflection, and the default of the rocket's own control is left where it + was.""" canard = _canard("Canard") rocket = _rocket_with(canard, 0.8) - canard.set_control("deflection", 0.02) + canard.control_defaults["deflection"] = 0.02 machs, angles = [0.2, 0.5, 0.8], np.radians([-10, 0, 10]) controls = {"deflection": np.radians([-10, 0, 10])} @@ -1039,17 +1060,17 @@ def test_lumping_keeps_a_control(): assert linear["cN_0"](0.5, math.radians(10)) == pytest.approx( 1.5 * math.radians(10) ) - assert canard.get_control("deflection") == 0.02 + assert canard.control_defaults["deflection"] == 0.02 power_off = rocket.to_surface( machs=machs, model="table", angles=angles, controls=controls )[0] - assert isinstance(power_off, ControllableGenericSurface) - assert power_off.control_variables == ["deflection"] + assert power_off.controls == ("deflection",) alpha, deflection = math.radians(3), math.radians(5) - power_off.set_control("deflection", deflection) - canard.set_control("deflection", deflection) - args = power_off._coefficient_arguments(alpha, 0, 0.5, 0, 0, 0, 0) + canard.control_defaults["deflection"] = deflection + args = power_off._coefficient_arguments( + alpha, 0, 0.5, 0, 0, 0, 0, controls=(deflection,) + ) expected = _source_coefficients(rocket, alpha, 0.5) assert power_off.cN.get_value_opt(*args) == pytest.approx(expected[0]) assert power_off.cm.get_value_opt(*args) == pytest.approx(expected[1]) diff --git a/tests/unit/sensors/test_sensor.py b/tests/unit/sensors/test_sensor.py index 0813a3638..5bb47801a 100644 --- a/tests/unit/sensors/test_sensor.py +++ b/tests/unit/sensors/test_sensor.py @@ -1,11 +1,13 @@ import json import os +from types import SimpleNamespace import numpy as np import pytest from pytest import approx from rocketpy.mathutils.vector_matrix import Matrix, Vector +from rocketpy.prints.flight_prints import _FlightPrints from rocketpy.tools import euler313_to_quaternions # calisto standard simulation no wind solution index 200 @@ -618,3 +620,19 @@ def test_export_multiple_sensors_json( os.remove(f"{file_name}_1") os.remove(f"{file_name}_2") + + +def test_sensor_events_keep_their_sensor_and_no_memory( + calisto, noisy_barometer, capsys +): + """A sensor's event reads its position from where it was made, not from + memory, and the flight prints name the sensor it belongs to.""" + calisto.add_sensor(noisy_barometer, 0.3) + ((sensor, event),) = calisto._sensor_events + assert sensor is noisy_barometer + assert event.memory == {} + + _FlightPrints(SimpleNamespace(rocket=calisto)).sensor_events() + out = capsys.readouterr().out + assert f"Parent Sensor: {noisy_barometer.name}" in out + assert "Memory Keys" not in out diff --git a/tests/unit/sensors/test_sensor_history.py b/tests/unit/sensors/test_sensor_history.py new file mode 100644 index 000000000..00242def8 --- /dev/null +++ b/tests/unit/sensors/test_sensor_history.py @@ -0,0 +1,457 @@ +"""The readings of a rocket's sensors: read during a flight through +``context.sensors``, kept in the flight's solution as ``solution.sensors`` and +as Functions in ``flight.sensor_history``, and taken back when the flight goes +back in time, without flying.""" + +from types import SimpleNamespace + +import numpy as np +import pytest + +from rocketpy import Flight +from rocketpy.mathutils.vector_matrix import Vector +from rocketpy.sensors.accelerometer import Accelerometer +from rocketpy.sensors.barometer import Barometer +from rocketpy.sensors.gnss_receiver import GnssReceiver +from rocketpy.sensors.gyroscope import Gyroscope +from rocketpy.simulation.events.event_execution import rewind +from rocketpy.simulation.events.views import SensorsView, sensor_positions +from rocketpy.simulation.flight_data_exporter import _sensor_rows +from rocketpy.simulation.solution import Solution + +# A rocket at rest 100 m above the ground, upright +STATE = [0, 0, 100, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0] +STATE_DOT = [0] * 13 + + +class _Context(dict): + """The part of the event context a sensor's event reads.""" + + def __init__(self, solution, **values): + super().__init__(**values) + self._solution = solution + + +def _read(solution, event, rocket, environment, time): + """Run a sensor's event once at ``time``.""" + event.callback( + _Context( + solution, + event=event, + time=time, + canonical_state=STATE, + canonical_state_dot=STATE_DOT, + rocket=rocket, + environment=environment, + ) + ) + + +def _positions_by_key(rocket): + """Each sensor position by its key, as the flight stores it. Each sensor + event is given the name its readings go by.""" + return sensor_positions(rocket._sensor_events) + + +def _flight_of(rocket, solution, t=1.0): + """A stand-in flight holding what the sensor results read.""" + flight = SimpleNamespace( + rocket=rocket, + solution=solution, + t=t, + events=[event for _, event in rocket._sensor_events], + _controls={}, + _step_log={}, + _sensors_by_key=_positions_by_key(rocket), + ) + return flight + + +def _history(flight): + """``flight.sensor_history`` of the stand-in flight.""" + return Flight.sensor_history.func(flight) + + +def _view(rocket, solution): + """``context.sensors`` for a flight of ``rocket``.""" + return SensorsView(_positions_by_key(rocket), solution) + + +@pytest.fixture +def solution(): + return Solution() + + +@pytest.fixture +def rocket(calisto_with_sensors, example_plain_env, solution): + """Calisto with its ideal sensors (the accelerometer added twice), each + position having read at 0.1 s and 0.2 s.""" + for sensor, _ in calisto_with_sensors._sensor_events: + sensor._reset(calisto_with_sensors) + _positions_by_key(calisto_with_sensors) + # Each position reads both times before the next one reads: the position + # a measurement belongs to does not depend on the order they run in + for _, event in calisto_with_sensors._sensor_events: + event.reset() + for time in (0.1, 0.2): + _read(solution, event, calisto_with_sensors, example_plain_env, time) + return calisto_with_sensors + + +def _sensor(rocket, index): + return rocket._sensor_events[index][0] + + +def _event(rocket, index): + return rocket._sensor_events[index][1] + + +# --------------------------------------------------------------------------- +# Names +# --------------------------------------------------------------------------- + + +def test_sensors_are_named_by_name_and_numbered_at_later_positions(rocket, solution): + keys = list(_flight_of(rocket, solution)._sensors_by_key) + assert keys == [ + "accelerometer", + "accelerometer_2", + "gyroscope", + "barometer", + "gnss_receiver", + ] + assert list(solution.sensors) == [ + "Accelerometer", + "Accelerometer 2", + "Gyroscope", + "Barometer", + "GnssReceiver", + ] + + +def test_two_sensors_with_one_name_are_numbered(calisto, solution): + first, second = Barometer(sampling_rate=10), Barometer(sampling_rate=10) + calisto.add_sensor(first, 0.0) + calisto.add_sensor(second, 0.5) + view = _view(calisto, solution) + + assert list(view) == ["Barometer", "Barometer 2"] + assert dir(view) == ["barometer", "barometer_2"] + assert len(calisto.sensors_by_name["Barometer"]) == 2 + + +def test_a_name_in_snake_case_counts_as_the_same_name(calisto, solution): + calisto.add_sensor(Barometer(sampling_rate=10), 0.0) + calisto.add_sensor(Barometer(sampling_rate=10, name="barometer"), 0.5) + assert list(_view(calisto, solution)) == ["Barometer", "barometer 2"] + + +def test_a_number_taken_by_a_name_is_skipped(calisto, solution): + calisto.add_sensor(Barometer(sampling_rate=10, name="Barometer 2"), 0.0) + barometer = Barometer(sampling_rate=10) + calisto.add_sensor(barometer, 0.1) + calisto.add_sensor(barometer, 0.5) + assert list(_view(calisto, solution)) == ["Barometer 2", "Barometer", "Barometer 3"] + + +# --------------------------------------------------------------------------- +# context.sensors +# --------------------------------------------------------------------------- + + +def test_context_sensors_read_the_latest_measurement(rocket, solution): + sensors = _view(rocket, solution) + barometer = _sensor(rocket, 3) + + assert sensors.barometer.pressure == barometer.measurement + assert sensors["Gyroscope"].wz == _sensor(rocket, 2).measurement[2] + assert sensors.gnss_receiver.altitude == _sensor(rocket, 4).measurement[2] + assert list(sensors) == [ + "Accelerometer", + "Accelerometer 2", + "Gyroscope", + "Barometer", + "GnssReceiver", + ] + + +def test_each_position_of_a_sensor_is_read_on_its_own(rocket, solution): + """One sensor object added twice has one ``measurement``; the context + gives the reading made at each position.""" + sensors = _view(rocket, solution) + # a different reading at position 1 + solution._sensors["Accelerometer"]["az"][-1] = (0.2, -1.0) + + assert sensors.accelerometer.az == -1.0 + assert ( + sensors.accelerometer_2.az == solution._sensors["Accelerometer 2"]["az"][-1][1] + ) + + +def test_context_sensors_are_none_before_the_first_measurement(calisto_with_sensors): + sensors = _view(calisto_with_sensors, Solution()) + assert sensors.barometer.pressure is None + assert sensors["Accelerometer 2"].ax is None + + +def test_context_sensors_name_what_is_missing_and_cannot_be_written(rocket, solution): + sensors = _view(rocket, solution) + with pytest.raises(AttributeError, match="Its sensors are: accelerometer,"): + _ = sensors.accelerometer_3 + with pytest.raises(AttributeError, match="Its channels are: ax, ay, az"): + _ = sensors.accelerometer.jerk + with pytest.raises(KeyError, match="no sensor named 'barometer'.*'Barometer'"): + _ = sensors["barometer"] # the name as given, not in snake_case + with pytest.raises(TypeError, match="read-only"): + sensors["Barometer"] = 0.0 + with pytest.raises(AttributeError, match="read-only"): + sensors.barometer.pressure = 0.0 + + +# --------------------------------------------------------------------------- +# The flight's readings +# --------------------------------------------------------------------------- + + +def test_a_sensor_event_stores_each_reading_by_channel(rocket, solution): + pressure = solution.sensors.barometer.pressure + assert list(solution.sensors.barometer) == ["pressure"] + assert list(pressure[:, 0]) == [0.1, 0.2] + assert pressure[-1, 1] == _sensor(rocket, 3).measurement + assert np.array_equal(solution.sensors["Barometer"]["pressure"], pressure) + assert list(solution.sensors["Barometer"].items())[0][0] == "pressure" + + +def test_each_position_of_a_sensor_keeps_its_own_measurements(rocket, solution): + assert list(solution.sensors["Accelerometer 2"].az[:, 0]) == [0.1, 0.2] + rows = _sensor_rows(_flight_of(rocket, solution)) + accelerometer = _sensor(rocket, 0) + assert [[row[0] for row in position] for position in rows[accelerometer]] == [ + [0.1, 0.2], + [0.1, 0.2], + ] + + +def test_the_sensor_history_uses_the_names_of_context_sensors(rocket, solution): + history = _history(_flight_of(rocket, solution)) + + view = _view(rocket, solution) + assert list(history) == list(view) + assert [list(history[name]) for name in history] == [ + list(view[name]) for name in view + ] + pressure = history["Barometer"].pressure + assert list(history.barometer.pressure.x_array) == list(pressure.x_array) + assert list(pressure.x_array) == [0.1, 0.2] + # between two readings the earlier one holds + assert pressure(0.15) == pressure.y_array[0] + assert pressure(0.2) == solution.sensors.barometer.pressure[-1, 1] + + +def test_the_sensor_rows_give_the_same_readings_as_tuples(rocket, solution): + flight = _flight_of(rocket, solution) + history = _history(flight) + rows = _sensor_rows(flight) + + # added twice: one list per position + assert len(rows[_sensor(rocket, 0)]) == 2 + assert rows[_sensor(rocket, 0)][1][0] == ( + 0.1, + history["Accelerometer 2"].ax(0.1), + history["Accelerometer 2"].ay(0.1), + history.accelerometer_2.az(0.1), + ) + assert [row[0] for row in rows[_sensor(rocket, 2)]] == [0.1, 0.2] + + +def test_flight_records_leave_out_the_sensors(rocket, solution): + assert Flight.records.fget(_flight_of(rocket, solution)) == {} + + +def test_flight_sensor_data_is_deprecated_and_gives_the_sensor_rows(rocket, solution): + """``flight.sensor_data`` is kept as it was in v1.13, sensor object to its + list of tuples, with a deprecation warning.""" + flight = _flight_of(rocket, solution) + with pytest.warns(DeprecationWarning, match="sensor_data is deprecated"): + # pylint: disable-next=assignment-from-no-return + data = Flight.sensor_data.fget(flight) + assert data == _sensor_rows(flight) + + +def test_a_flight_without_readings_has_empty_sensor_rows(calisto_with_sensors): + _positions_by_key(calisto_with_sensors) + flight = _flight_of(calisto_with_sensors, Solution()) + assert len(_history(flight)) == 0 + rows = _sensor_rows(flight) + accelerometer = _sensor(calisto_with_sensors, 0) + assert rows[accelerometer] == [[], []] + assert all( + position == [] + for sensor, position in rows.items() + if sensor is not accelerometer + ) + + +def test_the_readings_are_saved_with_the_solution(rocket, solution): # pylint: disable=unused-argument + loaded = Solution.from_dict(solution.to_dict()) + assert list(loaded.sensors) == list(solution.sensors) + assert np.array_equal( + loaded.sensors.accelerometer_2.az, solution.sensors.accelerometer_2.az + ) + + +# --------------------------------------------------------------------------- +# Going back in time +# --------------------------------------------------------------------------- + + +def test_a_rollback_drops_the_readings_after_its_time( + rocket, solution, example_plain_env +): + flight = _flight_of(rocket, solution, t=0.3) + rewind(flight, 0.15) + + assert list(solution.sensors.barometer.pressure[:, 0]) == [0.1] + assert list(_history(flight)["Barometer"].pressure.x_array) == [0.1] + # the sensor reads that time again on the trajectory flown from there + _read(solution, _event(rocket, 3), rocket, example_plain_env, 0.2) + assert list(solution.sensors.barometer.pressure[:, 0]) == [0.1, 0.2] + + +def test_a_rollback_takes_the_sensors_back(rocket, solution): + """What a controller reads of a sensor during the flight: its measured + data loses the measurements after the time the flight went back to, and + its measurement is again the last one kept.""" + flight = _flight_of(rocket, solution, t=0.3) + barometer = _sensor(rocket, 3) + barometer.measurement = -1.0 # a measurement on the trajectory left behind + + rewind(flight, 0.15) + + assert barometer.measurement == solution.sensors.barometer.pressure[-1, 1] + assert [row[0] for row in barometer.measured_data] == [0.1] + accelerometer = _sensor(rocket, 0) + assert [[row[0] for row in rows] for rows in accelerometer.measured_data] == [ + [0.1], + [0.1], + ] + assert accelerometer.measurement == accelerometer.measured_data[1][0][1:] + assert _view(rocket, solution).barometer.pressure == barometer.measurement + + +def test_a_new_flight_starts_without_a_measurement(rocket): + barometer = _sensor(rocket, 3) + assert barometer.measurement is not None + barometer._reset(rocket) + assert barometer.measurement is None + assert barometer.measured_data == [] + + +def test_a_rollback_before_any_measurement_leaves_none(rocket, solution): + rewind(_flight_of(rocket, solution, t=0.3), 0.05) + assert all(sensor.measurement is None for sensor, _ in rocket._sensor_events) + assert _sensor(rocket, 3).measured_data == [] + assert _view(rocket, solution).accelerometer.ax is None + + +@pytest.mark.parametrize("sensor_class", [Barometer, Gyroscope]) +def test_a_rollback_takes_the_random_walk_back( + sensor_class, calisto, solution, example_plain_env +): + """Each reading moves the drift of the sensor's noise by one random step. + Going back in time takes away the steps of the readings dropped, so the + drift does not grow with the number of rollbacks.""" + sensor = sensor_class(sampling_rate=10, random_walk_density=1.0) + calisto.add_sensor(sensor, 0.5) + sensor._reset(calisto) + _positions_by_key(calisto) + ((_, event),) = calisto._sensor_events + event.reset() + drift = {} + for time in (0.1, 0.2, 0.3): + _read(solution, event, calisto, example_plain_env, time) + drift[time] = sensor._random_walk_drift + assert drift[0.1] != drift[0.2] != drift[0.3] + + flight = _flight_of(calisto, solution, t=0.3) + rewind(flight, 0.15) + assert sensor._random_walk_drift == drift[0.1] + + # The reading taken again adds one step to the drift it went back to + _read(solution, event, calisto, example_plain_env, 0.2) + assert sensor._random_walk_drift != drift[0.1] + assert [time for time, _ in sensor._drift_log] == [0.1, 0.2] + + rewind(flight, 0.05) # before every reading + assert sensor._random_walk_drift == ( + Vector([0, 0, 0]) if sensor_class is Gyroscope else 0 + ) + assert sensor._drift_log == [] + + +def test_a_rollback_that_drops_no_reading_leaves_the_random_walk( + calisto, solution, example_plain_env +): + barometer = Barometer(sampling_rate=10, random_walk_density=1.0) + calisto.add_sensor(barometer, 0.5) + barometer._reset(calisto) + _positions_by_key(calisto) + ((_, event),) = calisto._sensor_events + event.reset() + for time in (0.1, 0.2): + _read(solution, event, calisto, example_plain_env, time) + drift = barometer._random_walk_drift + + rewind(_flight_of(calisto, solution, t=0.3), 0.25) + + assert barometer._random_walk_drift == drift + + +# --------------------------------------------------------------------------- +# What a reading costs +# --------------------------------------------------------------------------- + + +class _CountingContext(_Context): + """Counts how many times the derivative of the state is asked for, which + in a flight is an evaluation of the equations of motion.""" + + asked = 0 + + def __getitem__(self, key): + if key == "canonical_state_dot": + self.asked += 1 + return super().__getitem__(key) + + +@pytest.mark.parametrize( + "sensor, reads_it", + [ + (Barometer(sampling_rate=10), False), + (GnssReceiver(sampling_rate=10), False), + (Gyroscope(sampling_rate=10), False), + (Gyroscope(sampling_rate=10, acceleration_sensitivity=0.1), True), + (Accelerometer(sampling_rate=10), True), + ], +) +def test_a_reading_asks_for_the_state_derivative_only_when_the_sensor_reads_it( + calisto, example_plain_env, solution, sensor, reads_it +): + calisto.add_sensor(sensor, position=0.2) + sensor._reset(calisto) + _positions_by_key(calisto) + event = calisto._sensor_events[0][1] + context = _CountingContext( + solution, + event=event, + time=0.1, + canonical_state=STATE, + canonical_state_dot=STATE_DOT, + rocket=calisto, + environment=example_plain_env, + ) + + event.callback(context) + + assert context.asked == (1 if reads_it else 0) + assert sensor.measurement is not None diff --git a/tests/unit/simulation/test_aerodynamic_drag_force.py b/tests/unit/simulation/test_aerodynamic_drag_force.py index aa6197032..25d34afaf 100644 --- a/tests/unit/simulation/test_aerodynamic_drag_force.py +++ b/tests/unit/simulation/test_aerodynamic_drag_force.py @@ -23,7 +23,11 @@ def _flight_stand_in(power_off_drag, power_on_drag, burn_out_time=3.0): center_of_mass_without_motor=0, ) rocket.motor = SimpleNamespace(burn_out_time=burn_out_time) - return SimpleNamespace(rocket=rocket) + return SimpleNamespace( + rocket=rocket, + _controls={}, + _control_names={}, + ) def _head_on(speed): @@ -79,7 +83,14 @@ def test_rocket_drag_reads_the_flow_from_the_stream(): reynolds = density * speed * (2 * 0.05) / viscosity drag_area = _compute_drag_area( - flight, 5.0, stream, speed, 0.25, density, viscosity, (0, 0, 0) + flight, + 5.0, + stream, + speed, + 0.25, + density, + viscosity, + (0, 0, 0), ) expected = alpha + 10 * beta + 100 * 0.25 + reynolds / 1e6 @@ -90,10 +101,24 @@ def test_rocket_drag_curve_follows_the_motor_burn(): """The power-on curve is used until burn out, the power-off curve after.""" flight = _flight_stand_in(power_off_drag=0.6, power_on_drag=0.4) before = _compute_drag_area( - flight, 1.0, _head_on(50.0), 50.0, 0.15, 1.2, 0, (0, 0, 0) + flight, + 1.0, + _head_on(50.0), + 50.0, + 0.15, + 1.2, + 0, + (0, 0, 0), ) after = _compute_drag_area( - flight, 5.0, _head_on(50.0), 50.0, 0.15, 1.2, 0, (0, 0, 0) + flight, + 5.0, + _head_on(50.0), + 50.0, + 0.15, + 1.2, + 0, + (0, 0, 0), ) assert before == pytest.approx(0.4 * flight.rocket.area) assert after == pytest.approx(0.6 * flight.rocket.area) @@ -142,7 +167,13 @@ def test_axial_drag_follows_the_air_moving_along_the_axis(angle_deg, equations): position=-0.5, ) # all the derivative reads - flight = SimpleNamespace(env=env, rocket=rocket, _surface_switches={}) + flight = SimpleNamespace( + env=env, + rocket=rocket, + _surface_switches={}, + _control_names={}, + ) + controls = {} speed, angle = 80.0, np.radians(angle_deg) upright = [1.0, 0.0, 0.0, 0.0] # the body axis is the inertial z axis velocity = [speed * np.sin(angle), 0.0, speed * np.cos(angle)] @@ -150,7 +181,7 @@ def test_axial_drag_follows_the_air_moving_along_the_axis(angle_deg, equations): # After burn out, with no aerodynamic surface, the axial force is the drag derivative = getattr(flight_derivatives, equations) - axial_force = derivative(flight, 10.0, state, post_processing=True)[8] + axial_force = derivative(flight, 10.0, state, controls, post_processing=True)[8] rho = env.density.get_value_opt(1000.0) full = 0.5 * rho * speed**2 * 0.5 * rocket.area @@ -192,12 +223,18 @@ def test_3dof_drag_acts_against_the_velocity(velocity): position=0, ) # all the derivative reads - flight = SimpleNamespace(env=env, rocket=rocket, _surface_switches={}) + flight = SimpleNamespace( + env=env, + rocket=rocket, + _surface_switches={}, + _control_names={}, + ) + controls = {} upright = [1.0, 0.0, 0.0, 0.0] state = [0.0, 0.0, 1000.0, *velocity, *upright, 0.0, 0.0, 0.0] drag = np.array( - u_dot_generalized_3dof(flight, 10.0, state, post_processing=True)[6:9] + u_dot_generalized_3dof(flight, 10.0, state, controls, post_processing=True)[6:9] ) speed = np.linalg.norm(velocity) diff --git a/tests/unit/simulation/test_dynamics.py b/tests/unit/simulation/test_dynamics.py index 5444ce403..957502431 100644 --- a/tests/unit/simulation/test_dynamics.py +++ b/tests/unit/simulation/test_dynamics.py @@ -6,7 +6,6 @@ import numpy as np import pytest -from rocketpy.simulation.events.event_execution import apply_rollback_command from rocketpy.simulation.flight import Flight from rocketpy.simulation.helpers import dynamics as dynamics_module from rocketpy.simulation.helpers.dynamics import ( @@ -29,9 +28,10 @@ class StubFlight: def __init__(self): self.calls = [] self.atol = 6 * [1e-3] + 4 * [1e-6] + 3 * [1e-3] + self._controls = {} -def stub_derivative(flight, t, u, post_processing=False): +def stub_derivative(flight, t, u, controls, post_processing=False): # pylint: disable=unused-argument flight.calls.append((t, list(u), post_processing)) if post_processing: return [t] @@ -47,13 +47,12 @@ def stub_derivative(flight, t, u, post_processing=False): ) -def stub_flight_shell(live=False): +def stub_flight_shell(): """Return a Flight shell with only what post-processing reads.""" flight = Flight.__new__(Flight) flight.calls = [] flight.solution = Solution() - flight._has_change_dynamics_events = live - flight.solution.records_post_values = live + flight._controls = {} return flight @@ -113,6 +112,11 @@ def test_canonicalize_freezes_the_states_a_phase_does_not_integrate(): assert result[6:] == frozen[6:] +def test_canonicalize_needs_the_start_of_phase_state_to_freeze_from(): + with pytest.raises(ValueError, match="Pass start_canonical"): + TRANSLATION_DYNAMICS.canonicalize([10, 11, 12, 13, 14, 15], None) + + def heading_to_canonical(values): """Rebuild e0 from the heading; every other canonical state is copied.""" values["e0"] = values["heading"] * 2 @@ -206,7 +210,7 @@ def test_bound_dynamics_post_process_at_returns_reported_variables(): def test_bound_dynamics_forwards_phase_arguments(): """A phase argument fixed at bind time reaches both call paths.""" - def with_extra(flight, t, u, post_processing=False, *, parachute): # pylint: disable=unused-argument + def with_extra(flight, t, u, controls, post_processing=False, *, parachute): # pylint: disable=unused-argument flight.calls.append((t, post_processing, parachute)) return [parachute] @@ -223,7 +227,7 @@ def test_a_phase_reporting_no_variables_never_calls_the_derivative(): # This derivative has no post_processing parameter, so it raises TypeError if # post-processing asks it for variables the phase never declared. dynamics = _PhaseDynamics( - "silent", lambda flight, t, u: list(u), TRANSLATION_STATES + "silent", lambda flight, t, u, controls: list(u), TRANSLATION_STATES ) bound = dynamics.bind(StubFlight()) assert bound(0.0, [1] * 6) == [1] * 6 @@ -239,7 +243,7 @@ def test_bound_dynamics_default_initial_state(): def test_bound_dynamics_custom_initial_state(): - def seed(flight, t, canonical_state): # pylint: disable=unused-argument + def seed(flight, t, canonical_state, previous): # pylint: disable=unused-argument return [canonical_state[2]] # only altitude dynamics = _PhaseDynamics( @@ -264,6 +268,13 @@ def test_scalar_atol_passthrough(): assert SIX_DOF_DYNAMICS.select_atol(1e-5) == 1e-5 +def test_an_atol_vector_of_the_wrong_length_is_refused_for_every_phase(): + with pytest.raises(ValueError, match="neither the canonical state"): + SIX_DOF_DYNAMICS.select_atol([1e-3] * 12) + with pytest.raises(ValueError, match="neither the canonical state"): + TRANSLATION_DYNAMICS.select_atol([1e-3] * 5) + + def test_atol_matching_the_phase_width_passes_through(): custom = [1e-4] * 6 assert TRANSLATION_DYNAMICS.select_atol(custom) == custom @@ -321,84 +332,17 @@ def test_build_replays_the_stored_states(): flight.solution._append([0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) # The stub reports the time as its single post-process variable. - assert flight.solution.post["ax"].tolist() == [[0.0, 0.0], [0.5, 0.5]] + assert flight.solution.ax.tolist() == [[0.0, 0.0], [0.5, 0.5]] # Every stored state was replayed, in post-processing mode. assert [call[0] for call in flight.calls] == [0.0, 0.5] assert all(call[2] is True for call in flight.calls) -def test_build_prefers_values_recorded_during_the_simulation(): - """Live rows win, since a replay cannot reproduce a controller's changes.""" - flight = stub_flight_shell(live=True) - dynamics = _PhaseDynamics("stub", stub_derivative, TRANSLATION_STATES, ("ax",)) - flight.solution._start_phase( - dynamics.bind(flight), start_canonical=tuple([0.0] * 13) - ) - flight.solution._append([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) - flight.solution._set_post_values(-1, [42.0]) - - assert flight.solution.post["ax"].tolist() == [[0.0, 42.0]] - assert flight.calls == [] # nothing was replayed - - -def test_a_row_records_the_values_of_its_own_state(): - """A row added to mark an exact event time gets values of its own. - - The row is written out of order, before the step the solver already took - past it, so recording it against the most recent row would put the values - on the wrong row and leave this one with nothing. - """ - flight = stub_flight_shell(live=True) - dynamics = _PhaseDynamics("stub", stub_derivative, TRANSLATION_STATES, ("ax",)) - flight.solution._start_phase( - dynamics.bind(flight), start_canonical=tuple([0.0] * 13) - ) - flight.solution._append([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) - flight._Flight__post_process_step() - # a step, with an exact-time row wedged in before its end by an event of - # that step: the wedged row is recorded as soon as it is inserted, the - # step's own row once its events are handled - flight.solution._append([1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) - flight.solution._insert_before_last([0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) - flight._post_process_row(-2) - assert flight.solution._post_values[-2] == [0.5] - assert flight.solution._post_values[-1] is None - flight._Flight__post_process_step() - - # the stub reports the row's own time as its post-process variable - assert flight.solution.post["ax"].tolist() == [ - [0.0, 0.0], - [0.5, 0.5], - [1.0, 1.0], - ] - - -def test_a_replaced_row_records_the_values_of_its_new_state(): - """Rolling a row back clears its values; the loop then records them anew.""" - flight = stub_flight_shell(live=True) - dynamics = _PhaseDynamics("stub", stub_derivative, TRANSLATION_STATES, ("ax",)) - flight.solution._start_phase( - dynamics.bind(flight), start_canonical=tuple([0.0] * 13) - ) - flight.solution._append([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) - flight._Flight__post_process_step() - flight.solution._append([1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) - flight._Flight__post_process_step() - apply_rollback_command(flight, 0.75, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) - # the rollback itself records nothing: the solver loop does, once per step - assert flight.solution._post_values[-1] is None - flight._Flight__post_process_step() - recorded_calls = len(flight.calls) - - assert flight.solution.post["ax"].tolist() == [[0.0, 0.0], [0.75, 0.75]] - assert len(flight.calls) == recorded_calls # nothing was replayed - - def test_a_phase_that_does_not_compute_a_variable_reports_zero(): flight = stub_flight_shell() full = _PhaseDynamics( "full", - lambda flight, t, u, post_processing=False: ( + lambda flight, t, u, controls, post_processing=False: ( [1.0, 2.0] if post_processing else list(u) ), TRANSLATION_STATES, @@ -406,7 +350,7 @@ def test_a_phase_that_does_not_compute_a_variable_reports_zero(): ) partial = _PhaseDynamics( "partial", - lambda flight, t, u, post_processing=False: ( + lambda flight, t, u, controls, post_processing=False: ( [3.0] if post_processing else list(u) ), TRANSLATION_STATES, @@ -419,9 +363,9 @@ def test_a_phase_that_does_not_compute_a_variable_reports_zero(): ) flight.solution._append([1.0, *[0.0] * 6]) - assert flight.solution.post["ax"].tolist() == [[0.0, 1.0], [1.0, 3.0]] + assert flight.solution.ax.tolist() == [[0.0, 1.0], [1.0, 3.0]] # M1 is not computed by the second phase, so it is zero there. - assert flight.solution.post["M1"].tolist() == [[0.0, 2.0], [1.0, 0.0]] + assert flight.solution.M1.tolist() == [[0.0, 2.0], [1.0, 0.0]] def test_unknown_post_process_variable_raises(): @@ -431,8 +375,8 @@ def test_unknown_post_process_variable_raises(): dynamics.bind(flight), start_canonical=tuple([0.0] * 13) ) flight.solution._append([0.0, *[0.0] * 6]) - with pytest.raises(KeyError, match="No flight phase computed"): - _ = flight.solution.post["nope"] + with pytest.raises(KeyError, match="nothing named 'nope'"): + _ = flight.solution["nope"] def test_a_phase_with_no_live_dynamics_is_skipped(): @@ -443,7 +387,10 @@ def test_a_phase_with_no_live_dynamics_is_skipped(): # The variable is one the phase declares, so the error says why it cannot be # produced rather than claiming the flight never computes it. with pytest.raises(KeyError, match="read back from a saved file"): - _ = flight.solution.post["ax"] + _ = flight.solution["ax"] + # read as an attribute, the same message comes as an AttributeError + with pytest.raises(AttributeError, match="read back from a saved file"): + _ = flight.solution.ax @pytest.mark.parametrize("name", FULL_POST_PROCESS_VARS) @@ -457,7 +404,7 @@ def test_every_built_in_variable_has_a_flight_attribute(name): """ flight = stub_flight_shell() - def report_everything(_flight, t, u, post_processing=False): + def report_everything(_flight, t, u, _controls, post_processing=False): return [t] * len(FULL_POST_PROCESS_VARS) if post_processing else list(u) dynamics = _PhaseDynamics( @@ -471,3 +418,34 @@ def report_everything(_flight, t, u, post_processing=False): attribute = getattr(flight, name) assert np.allclose(attribute.y_array, [0.0, 0.5, 1.0, 1.5]) + + +def test_each_row_stores_a_copy_of_the_controls_after_its_step(): + """The controls in force when a step's events are done are stored with the + step's row (and the first row, on the first step), and replaying a row + reads them, not the flight's controls at the end.""" + flight = stub_flight_shell() + flight._controls = {"tab.trim": 0.0} + + def trim_derivative(_flight, t, u, controls, post_processing=False): # pylint: disable=unused-argument + return [controls["tab.trim"]] if post_processing else list(u) + + dynamics = _PhaseDynamics("trim", trim_derivative, TRANSLATION_STATES, ("ax",)) + flight.solution._start_phase( + dynamics.bind(flight), start_canonical=tuple([0.0] * 13) + ) + flight.solution._append([0.0, *[0.0] * 6]) + flight.solution._append([0.5, *[0.0] * 6]) + flight._controls["tab.trim"] = 0.25 + flight._Flight__store_row_controls() + flight._controls["tab.trim"] = 0.5 + flight.solution._append([1.0, *[0.0] * 6]) + flight._Flight__store_row_controls() + flight._controls["tab.trim"] = 0.75 + + assert flight.solution._controls[0] == {"tab.trim": 0.25} + assert flight.solution.ax.tolist() == [ + [0.0, 0.25], + [0.5, 0.25], + [1.0, 0.5], + ] diff --git a/tests/unit/simulation/test_event.py b/tests/unit/simulation/test_event.py index 6888fec61..ce64aa148 100644 --- a/tests/unit/simulation/test_event.py +++ b/tests/unit/simulation/test_event.py @@ -1,3 +1,4 @@ +import logging import warnings from types import SimpleNamespace @@ -5,13 +6,23 @@ import pytest from rocketpy.simulation.events import Event -from rocketpy.simulation.events.event_context import EventContext, build_event_kwargs -from rocketpy.simulation.events.event_execution import apply_event_list_updates +from rocketpy.simulation.events.event_context import ( + EventContext, + build_event_kwargs, + refresh_event_kwargs, +) +from rocketpy.simulation.events.event_execution import ( + apply_event_commands, + apply_event_list_updates, + apply_rollback_command, + rewind, +) from rocketpy.simulation.helpers.dynamics import ( CANONICAL_STATE_NAMES, SIX_DOF_DYNAMICS, _PhaseDynamics, ) +from rocketpy.simulation.helpers.flight_phase import _FlightPhases, _TimeNodes from rocketpy.simulation.solution import Solution @@ -35,13 +46,17 @@ def _context(**values): if "state" in values: values["canonical_state"] = values.pop("state") values.setdefault("raw_state", values["canonical_state"]) + # What build_event_kwargs takes from the flight and its current phase + flight = values.pop("flight", None) + phase = values.pop("phase", None) + if hasattr(flight, "env"): + values.setdefault("environment", flight.env) if "phase_names" not in values: try: - dynamics = values["flight"].solution.phases[-1].dynamics - values["phase_names"] = dynamics.states - except (KeyError, AttributeError): + values["phase_names"] = flight.solution.phases[-1].dynamics.states + except AttributeError: values["phase_names"] = CANONICAL_STATE_NAMES - return EventContext(values) + return EventContext(values, solution=getattr(flight, "solution", None), phase=phase) def _always_true(_context): @@ -53,14 +68,7 @@ def _trigger_on_positive_vz(context): def _callback_record_kwargs(context): - return { - "time": context["time"], - "state": context["state"], - } - - -def _callback_returns_int(_context) -> int: - return 1 + context.record(time=context["time"], vz=context["state"][5]) def _trigger_returns_int(_context) -> int: @@ -187,10 +195,6 @@ def test_trigger_rejects_unknown_preset(): {"callback": lambda time, state: None}, "Callback function must take the event context as its single", ), - ( - {"callback": _callback_returns_int}, - "Callback function return annotation must be None, dict, or unspecified", - ), ], ) def test_callback_validation_rejects_invalid_callbacks(kwargs, message): @@ -299,7 +303,9 @@ def test_exact_time_configuration_rejects_invalid_solver_and_sampling_mix(): }, ) - with pytest.raises(ValueError, match="only supported for continuous hooks"): + with pytest.raises( + ValueError, match="only supported for an event without a sampling_rate" + ): Event( callback=_callback_record_kwargs, trigger=_always_true, @@ -318,26 +324,22 @@ def test_reset_restores_initial_runtime_state(): sampling_rate=2.0, ) event.memory["count"] = 99 - event.verbose_log.append({"time": 1.0}) - event.callback_log.append({"time": 1.0}) + event._record(1.0, {"time": 1.0}) event.triggered_times.append(1.0) event.enabled_times.append(2.0) event.disabled_times.append(3.0) event.commands.disable() - event._trigger_checked = True - event.enabled = True + event._enabled = True # as a flight turns it on event.reset() assert event.enabled is False assert event.memory == {"count": 1} - assert event.verbose_log == [] - assert event.callback_log == [] + assert event._records == {} assert event.triggered_times == [] assert event.enabled_times == [] assert event.disabled_times == [] assert event.commands._disabled is None - assert event._trigger_checked is False def test_call_supports_trigger_only_callback_only_and_disable_commands(): @@ -349,7 +351,7 @@ def test_call_supports_trigger_only_callback_only_and_disable_commands(): def callback(context): triggered.append(context["time"]) context["event"].commands.disable() - return {"time": context["time"]} + context.record(time=context["time"]) event = Event( callback=callback, @@ -373,7 +375,7 @@ def callback(context): assert trigger_only_result is True assert triggered == [] - assert event.callback_log == [] + assert event._records == {} callback_only_result = event( _context( @@ -389,7 +391,7 @@ def callback(context): assert callback_only_result is True assert triggered == [3.0] - assert event.callback_log[0]["time"] == 3.0 + assert event._records["time"] == [(3.0, 3.0)] assert event.triggered_times == [3.0] assert event.commands._disabled is True @@ -406,7 +408,7 @@ def test_enable_on_is_checked_before_the_trigger_and_disable_on_after(): ) assert event(_context(time=1.0, state=[0.0] * 13)) is True - assert len(event.callback_log) == 1 + assert len(event._records["time"]) == 1 # enable_on queued an enable, then disable_on queued a disable: the disable # is what the simulation applies assert event.commands._disabled is True @@ -588,8 +590,8 @@ def test_call_refines_exact_time(): assert result is True assert event.triggered_times == [pytest.approx(0.5)] - assert event.callback_log[0]["time"] == pytest.approx(0.5) - assert event.callback_log[0]["state"][5] == pytest.approx(0.0) + assert event._records["time"][0][1] == pytest.approx(0.5) + assert event._records["vz"][0][1] == pytest.approx(0.0) assert event.commands.exact_time == pytest.approx(0.5) assert event.commands.exact_state[5] == pytest.approx(0.0) @@ -620,7 +622,7 @@ def test_call_falls_back_to_sampled_time_when_exact_time_solver_fails(): assert result is True assert event.triggered_times == [1.0] - assert event.callback_log[0]["time"] == 1.0 + assert event._records["time"][0][1] == 1.0 assert event.commands.exact_time is None assert event.commands.exact_state is None @@ -733,14 +735,10 @@ def _build_event_call_kwargs(time, state): "canonical_state": state, "raw_state": state, "phase_names": CANONICAL_STATE_NAMES, - "flight": SimpleNamespace(), "rocket": SimpleNamespace(), "environment": SimpleNamespace(), - "phase": SimpleNamespace(), - "step_size": 0.01, "height_agl": state[2], - "sensors": [], - "sensors_by_name": {}, + "sensors": {}, } @@ -815,6 +813,84 @@ def trigger(context): assert fired == [3.0] +def test_a_callback_sees_the_check_before_this_one(): + """The callback runs after the trigger, and still sees the previous + check, not the one being made.""" + seen = [] + event = Event( + callback=lambda context: seen.append( + (context.time, context.previous_time, context.previous_state) + ) + ) + for t in (1.0, 2.0): + event(EventContext(_build_event_call_kwargs(t, [t] * 13))) + + assert seen[0] == (1.0, None, None) + assert seen[1][:2] == (2.0, 1.0) + assert list(seen[1][2]) == [1.0] * 13 + + +def test_dt_is_the_time_since_the_previous_check(): + dts = [] + event = Event(callback=lambda context: dts.append(context.dt), sampling_rate=20) + for t in (0.05, 0.1, 0.25): + event(EventContext(_build_event_call_kwargs(t, [0.0] * 13))) + + assert dts == pytest.approx([0.05, 0.05, 0.15]) + + +def test_dt_is_none_on_the_first_check_without_a_sampling_rate(): + dts = [] + event = Event(callback=lambda context: dts.append(context.dt)) + for t in (1.0, 1.5): + event(EventContext(_build_event_call_kwargs(t, [0.0] * 13))) + + assert dts == [None, 0.5] + + +def test_going_back_in_time_drops_what_happened_after(): + event = Event(callback=_callback_record_kwargs) + for t in (1.0, 2.0, 3.0): + event(_context(time=t, state=[0.0] * 13)) + event.disabled_times.extend([1.5, 2.5]) + event.enabled_times.append(2.8) + + event._drop_after(2.0) + + assert event.triggered_times == [1.0, 2.0] + assert event.disabled_times == [1.5] + assert event.enabled_times == [] + assert [t for t, _ in event._records["time"]] == [1.0, 2.0] + + +def test_a_verbose_event_reports_its_checks_at_info(): + messages = [] + handler = logging.Handler(logging.INFO) + handler.emit = lambda record: messages.append(record.getMessage()) + rocketpy_logger = logging.getLogger("rocketpy") + level = rocketpy_logger.level + rocketpy_logger.addHandler(handler) + rocketpy_logger.setLevel(logging.INFO) + try: + Event(callback=lambda context: None, name="Quiet")( + _context(time=1.0, state=[0.0] * 13) + ) + Event(callback=lambda context: None, name="Loud", verbose=True)( + _context(time=1.0, state=[0.0] * 13) + ) + finally: + rocketpy_logger.removeHandler(handler) + rocketpy_logger.setLevel(level) + + assert [message[:12] for message in messages] == ["Event 'Loud'"] + + +def test_what_a_callback_returns_is_ignored(): + event = Event(callback=lambda context: {"time": context.time}) + assert event(_context(time=1.0, state=[0.0] * 13)) is True + assert event._records == {} + + def _check_at(event, time, vz, height): """Check ``event`` once with the rocket at ``height`` above the ground, moving vertically at ``vz``. Returns whether it fired.""" @@ -946,8 +1022,9 @@ def run_one_step(start, end): solution=solution, t=end, y_sol=[end] * 13, - sensors=[], - sensors_by_name={}, + _sensors_by_key={}, + _controls={}, + _control_limits={}, env=SimpleNamespace(elevation=0.0), rocket=SimpleNamespace(), out_of_rail_state=[0.0] * 13, # already off the rail @@ -984,16 +1061,15 @@ def run_one_step(start, end): # --------------------------------------------------------------------------- -def _flight_shell_for_added_events(records_post_values=False): +def _flight_shell_for_added_events(): """A stand-in Flight holding only what apply_event_list_updates reads.""" - solution = Solution() - solution.records_post_values = records_post_values return SimpleNamespace( - solution=solution, + solution=Solution(), events=[], custom_events=[], _overshootable_events=[], _non_overshootable_events=[], + _output_events={}, time_overshoot=False, ) @@ -1010,50 +1086,6 @@ def _phase_shell(): ) -def test_adding_an_event_that_changes_the_rocket_warns(): - """Recording is settled before the flight starts, so this arrives too late.""" - flight = _flight_shell_for_added_events() - added = Event( - callback=lambda context: None, - trigger=_always_true, - name="Late controller", - changes_dynamics=True, - ) - - with pytest.warns( - UserWarning, match="added with add_event after the flight started" - ): - apply_event_list_updates( - flight, - SimpleNamespace(new_events=[added]), - _phase_shell(), - 1.0, - ) - - # the event is still added: the trajectory it produces is correct - assert flight.events == [added] - assert flight.custom_events == [added] - - -def test_adding_an_event_that_changes_the_rocket_is_quiet_when_already_recording(): - """Another such event was there from the start, so recording is already on.""" - flight = _flight_shell_for_added_events(records_post_values=True) - added = Event( - callback=lambda context: None, - trigger=_always_true, - name="Another controller", - changes_dynamics=True, - ) - - with warnings.catch_warnings(): - warnings.simplefilter("error") - apply_event_list_updates( - flight, SimpleNamespace(new_events=[added]), _phase_shell(), 1.0 - ) - - assert flight.events == [added] - - def test_adding_an_ordinary_event_does_not_warn(): flight = _flight_shell_for_added_events() added = Event(callback=lambda context: None, trigger=_always_true, name="Plain") @@ -1077,8 +1109,9 @@ def test_state_is_read_by_name_or_by_position(): solution = _canonical_solution([0.0, *range(13)], [1.0, *range(1, 14)]) flight = SimpleNamespace( solution=solution, - sensors=[], - sensors_by_name={}, + _sensors_by_key={}, + _controls={}, + _control_limits={}, env=SimpleNamespace(elevation=0.0), rocket=None, ) @@ -1106,15 +1139,16 @@ def test_state_carries_a_state_the_canonical_thirteen_cannot_hold(): "parafoil", lambda _flight, _t, u, post_processing=False: [0.0] * 6 + [0.5], ("x", "y", "z", "vx", "vy", "vz", "heading"), - initial_state=lambda _flight, _t, canonical: [*canonical[:6], 0.0], + initial_state=lambda _flight, _t, canonical, _previous: [*canonical[:6], 0.0], ) solution = Solution() solution._start_phase(parafoil, start_canonical=tuple([0.0] * 13)) solution._append([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.25]) flight = SimpleNamespace( solution=solution, - sensors=[], - sensors_by_name={}, + _sensors_by_key={}, + _controls={}, + _control_limits={}, env=SimpleNamespace(elevation=0.0), rocket=None, ) @@ -1140,8 +1174,9 @@ def test_a_name_the_phase_does_not_have_says_which_names_exist(): solution = _canonical_solution([0.0, *range(13)]) flight = SimpleNamespace( solution=solution, - sensors=[], - sensors_by_name={}, + _sensors_by_key={}, + _controls={}, + _control_limits={}, env=SimpleNamespace(elevation=0.0), rocket=None, ) @@ -1156,8 +1191,9 @@ def test_state_is_not_built_unless_read(): solution = _canonical_solution([0.0, *range(13)]) flight = SimpleNamespace( solution=solution, - sensors=[], - sensors_by_name={}, + _sensors_by_key={}, + _controls={}, + _control_limits={}, env=SimpleNamespace(elevation=0.0), rocket=None, ) @@ -1173,8 +1209,9 @@ def test_state_dot_is_not_computed_unless_read(): solution = _canonical_solution([0.0, *range(13)]) flight = SimpleNamespace( solution=solution, - sensors=[], - sensors_by_name={}, + _sensors_by_key={}, + _controls={}, + _control_limits={}, env=SimpleNamespace(elevation=0.0), rocket=None, ) @@ -1198,8 +1235,9 @@ def test_reading_the_rates_twice_costs_one_evaluation(): solution = _canonical_solution([0.0, *range(13)]) flight = SimpleNamespace( solution=solution, - sensors=[], - sensors_by_name={}, + _sensors_by_key={}, + _controls={}, + _control_limits={}, env=SimpleNamespace(elevation=0.0), rocket=None, ) @@ -1222,8 +1260,9 @@ def test_moving_the_context_drops_what_was_worked_out_for_the_old_moment(): solution = _canonical_solution([0.0, *range(13)]) flight = SimpleNamespace( solution=solution, - sensors=[], - sensors_by_name={}, + _sensors_by_key={}, + _controls={}, + _control_limits={}, env=SimpleNamespace( elevation=0.0, pressure=SimpleNamespace(get_value_opt=lambda z: 10.0 * z) ), @@ -1231,16 +1270,18 @@ def test_moving_the_context_drops_what_was_worked_out_for_the_old_moment(): ) phase = SimpleNamespace(dynamics=lambda t, u: [t] * 13) context = build_event_kwargs(flight, 0.0, list(range(13)), phase) - assert context["pressure"] == 20.0 + assert context.pressure == 20.0 assert context["state_dot"][0] == 0.0 - moved = context.at(1.0, [5.0] * 13) + moved = refresh_event_kwargs( + EventContext(context, solution=solution, phase=phase), 1.0, [5.0] * 13 + ) - assert moved["pressure"] == 50.0 + assert moved.pressure == 50.0 assert moved["state_dot"][0] == 1.0 assert moved.state.x == 5.0 # the original is untouched - assert context["pressure"] == 20.0 + assert context.pressure == 20.0 # --------------------------------------------------------------------------- @@ -1274,20 +1315,6 @@ def test_binding_swaps_the_values_that_belong_to_one_event(): assert "previous_time" not in context -def test_owned_values_leave_with_the_event_that_added_them(): - context = _context(time=1.0, state=[0.0] * 13) - first = _tracking_event("first") - second = _tracking_event("second") - - context.bind(first) - assert context.controller is None # not a controller's event - context.own(controller="mine") - assert context.controller == "mine" - - context.bind(second) - assert "controller" not in context - - def test_expanding_the_context_gives_the_event_exactly_its_own_keys(): seen = {} @@ -1464,7 +1491,7 @@ def bound_dynamics(_t, _u): "parafoil_exact", lambda _flight, t, u, post_processing=False: bound_dynamics(t, u), PARAFOIL_EXACT_STATES, - initial_state=lambda _flight, _t, canonical: [*canonical[:6], 0.0], + initial_state=lambda _flight, _t, canonical, _previous: [*canonical[:6], 0.0], ) solution = Solution() solution._start_phase(parafoil, start_canonical=tuple([0.0] * 13)) @@ -1654,3 +1681,336 @@ def test_a_phase_state_cannot_take_a_name_the_state_uses(taken): the values of the state, so a phase's own state could not be read by them.""" with pytest.raises(ValueError, match=f"cannot have a state called '{taken}'"): _PhaseDynamics("custom", None, ("x", "y", "z", taken)) + + +# A rollback and the flight's schedule: its phases, its events and which are +# enabled, its surface switches and its parachutes + + +class _Surface: + """A stand-in for an aerodynamic surface.""" + + name = "Canard" + + +def _flight_in_a_step(t=2.0): + """A stand-in flight at the end of a solver step from 1 s to ``t``, in a + phase that runs to 100 s, holding what an event's commands change. It has + one event checked at every step, one sampled event the solver steps over + and one it stops at, and one surface.""" + every_step = Event(lambda context: None, name="Every step") + stepped_over = Event(lambda context: None, sampling_rate=10, name="Stepped over") + stopped_at = Event( + lambda context: None, + sampling_rate=1, + time_overshootable=False, + enabled=False, + enable_on=lambda context: False, + name="Stopped at", + ) + events = [every_step, stepped_over, stopped_at] + phases = _FlightPhases(t_initial=0.0, initial_dynamics=None, max_time=100.0) + phase = phases[0] + phase.time_nodes = _TimeNodes() + for node_time in (0.0, 50.0, 100.0): + phase.time_nodes.add_node(node_time, []) + phase.time_nodes.add_continuous_events([every_step]) + phase.solver = SimpleNamespace(status="running") + surface = _Surface() + flight = SimpleNamespace( + t=t, + y_sol=_sample_state(t, 1.0)[1:], + solution=_canonical_solution(_sample_state(1.0, 1.0), _sample_state(t, 1.0)), + flight_phases=phases, + events=list(events), + custom_events=list(events), + _overshootable_events=[stepped_over], + _non_overshootable_events=[every_step, stopped_at], + _output_events={}, + _surface_switches={}, + parachute_events=[], + time_overshoot=True, + _controls={}, + _step_log={}, + _schedule_log=[], + rocket=SimpleNamespace(aerodynamic_surfaces=[(surface, None)]), + ) + return flight, phase, surface + + +def _schedule(flight, phase): + """Everything of the flight's schedule, as plain values to compare.""" + return ( + [(kept.name, kept.t, kept.time_bound) for kept in flight.flight_phases.list], + [(node.t, list(node.events)) for node in phase.time_nodes.list], + list(phase.time_nodes.continuous_events), + phase.solver.status, + [(event.name, event.enabled) for event in flight.events], + [event.name for event in flight.custom_events], + [event.name for event in flight._overshootable_events], + [event.name for event in flight._non_overshootable_events], + dict(flight._output_events), + {s.name: list(rows) for s, rows in flight._surface_switches.items()}, + list(flight.parachute_events), + ) + + +def _apply(flight, phase, time, queue, event=None): + """Apply at ``time`` the commands ``queue`` puts on ``event`` (a new one + by default), as the flight does once the event fired.""" + event = event or Event(lambda context: None, name=f"Event at {time}") + event.commands.reset() + queue(event.commands, flight) + if event.commands.changes_trajectory and time < flight.t: + apply_rollback_command(flight, time, flight.y_sol, event.commands) + apply_event_commands(flight, event, event.commands, phase, 0, 0, time) + return event + + +def _switch_the_surface(commands, flight): + commands.surface_switches.append((flight.rocket.aerodynamic_surfaces[0][0], True)) + + +def _start_a_phase(commands, _flight): + commands.start_flight_phase("new_phase") + + +def _start_a_phase_after_a_lag(commands, _flight): + commands.start_flight_phase("new_phase", lag=1.5) + + +def _deploy_a_parachute(commands, _flight): + commands.start_flight_phase("descent", lag=1.5) + commands.new_dynamics_kwargs["parachute"] = "Drogue" + + +def _end_the_flight(commands, _flight): + commands.terminate_flight() + + +def _add_a_sampled_event(commands, _flight): + commands.add_event( + Event(lambda context: None, sampling_rate=5, outputs=("level",), name="Added") + ) + + +def _add_an_event_the_solver_stops_at(commands, _flight): + commands.add_event( + Event( + lambda context: None, + sampling_rate=0.1, + time_overshootable=False, + name="Added", + ) + ) + + +def _disable_another_event(commands, flight): + commands.disable_event(flight.events[0]) + + +def _enable_another_event(commands, flight): + commands.enable_event(flight.events[2]) + + +def _disable_itself(commands, _flight): + commands.disable() + + +_SCHEDULE_CHANGES = [ + _switch_the_surface, + _start_a_phase, + _start_a_phase_after_a_lag, + _deploy_a_parachute, + _end_the_flight, + _add_a_sampled_event, + _add_an_event_the_solver_stops_at, + _disable_another_event, + _enable_another_event, + _disable_itself, +] + + +@pytest.mark.parametrize( + "change", _SCHEDULE_CHANGES, ids=lambda change: change.__name__ +) +def test_a_rollback_undoes_what_an_event_did_to_the_schedule(change): + """Whatever an event's commands changed after the time the flight goes + back to is put back as it was.""" + flight, phase, _ = _flight_in_a_step() + before = _schedule(flight, phase) + event = flight.events[0] if change is _disable_itself else None + + _apply(flight, phase, 2.0, change, event) # at the step end + assert _schedule(flight, phase) != before + + rewind(flight, 1.5) + + assert _schedule(flight, phase) == before + assert not flight._schedule_log + + +@pytest.mark.parametrize( + "change", _SCHEDULE_CHANGES, ids=lambda change: change.__name__ +) +def test_a_rollback_keeps_what_an_event_did_before_the_time_it_goes_back_to(change): + flight, phase, _ = _flight_in_a_step() + event = flight.events[0] if change is _disable_itself else None + _apply(flight, phase, 1.2, change, event) + kept = _schedule(flight, phase) + + rewind(flight, 1.5) + + assert _schedule(flight, phase) == kept + + +def test_a_rollback_undoes_only_the_changes_made_after_its_time(): + """An event added at 1.2 s stays; the surface switched and the phase + started at the step end, both after the time gone back to, do not.""" + flight, phase, _ = _flight_in_a_step() + _apply(flight, phase, 1.2, _add_a_sampled_event) + kept = _schedule(flight, phase) + _apply(flight, phase, 2.0, _switch_the_surface) + _apply(flight, phase, 2.0, _start_a_phase_after_a_lag) + + rewind(flight, 1.5) + + assert _schedule(flight, phase) == kept + assert [event.name for event in flight.events][-1] == "Added" + + +def test_the_event_that_cuts_the_step_keeps_what_it_changed(): + """An event at a sampling time the step went past cuts the step there and + then starts its phase: going back to its own time does not undo it.""" + flight, phase, surface = _flight_in_a_step() + + def switch_and_start(commands, flight): + _switch_the_surface(commands, flight) + _start_a_phase(commands, flight) + + _apply(flight, phase, 1.2, switch_and_start) + + assert flight.t == 1.2 + assert [kept.name for kept in flight.flight_phases.list] == [ + "initial_phase", + "new_phase", + "max_time_stop", + ] + assert flight._surface_switches == {surface: [(1.2, True)]} + assert phase.solver.status == "finished" + + +def test_an_exact_time_event_undoes_the_sampled_event_it_is_found_before(): + """A sampled event starts a phase and switches a surface at 1.8 s. An + event checked at the step end is then found to have happened at 1.5 s and + starts its own phase: the flight goes back to 1.5 s, where the sampled + event has not happened yet.""" + flight, phase, _ = _flight_in_a_step() + + def switch_and_start(commands, flight): + _switch_the_surface(commands, flight) + commands.start_flight_phase("sampled_phase") + + _apply(flight, phase, 1.8, switch_and_start) + + def start_at_the_exact_time(commands, _flight): + commands.start_flight_phase("exact_phase") + commands.exact_time = 1.5 + commands.exact_state = _sample_state(1.5, 1.0)[1:] + + _apply(flight, phase, 1.8, start_at_the_exact_time) + + assert flight.t == 1.5 + assert [(kept.name, kept.t) for kept in flight.flight_phases.list] == [ + ("initial_phase", 0.0), + ("exact_phase", 1.5), + ("max_time_stop", 100.0), + ] + assert not flight._surface_switches + assert phase.time_bound == 1.5 + + +# ``enabled`` set by the user, and by a flight + + +def test_enabled_set_after_the_event_is_built_is_how_every_flight_starts(): + """A flight resets each of its events when it starts: what the user set + stands, in both directions.""" + event = Event(lambda context: None, name="Logger") + event.enabled = False + event.reset() + assert event.enabled is False + + event.enabled = True + event.reset() + assert event.enabled is True + + +def test_what_a_flight_did_to_enabled_is_undone_at_the_next_flight(): + """An event the flight turned off, by its own command or by another + event's, starts the next flight as the user left it.""" + flight, phase, _ = _flight_in_a_step() + every_step, _, stopped_at = flight.events + + _apply(flight, phase, 2.0, _disable_itself, every_step) + _apply(flight, phase, 2.0, _enable_another_event) + assert every_step.enabled is False and stopped_at.enabled is True + + every_step.reset() + stopped_at.reset() + assert every_step.enabled is True and stopped_at.enabled is False + + +def test_a_rollback_does_not_change_how_the_event_starts_a_flight(): + event = Event(lambda context: None, name="Logger") + saved = event._check_state() + event._enabled = False # as a flight turns it off + event._restore_check_state(saved) + assert event.enabled is True + + event._restore_check_state((False, *saved[1:])) + assert event.enabled is False + event.reset() + assert event.enabled is True + + +# An event checked by hand + + +def test_an_event_checked_with_a_plain_dictionary_is_refused(): + event = Event(lambda context: None) + with pytest.raises( + TypeError, match="checked with an EventContext.*not with a dict" + ): + event({"time": 1.0}) + + +@pytest.mark.parametrize("missing", ["canonical_state", "raw_state", "phase_names"]) +def test_a_context_without_the_state_is_refused_before_the_trigger_runs(missing): + """The error names what is missing, and none of the event's functions was + called with the incomplete context.""" + called = [] + event = Event( + lambda context: called.append("callback"), + trigger=lambda context: called.append("trigger") or True, + ) + state = [0.0] * 13 + values = {"canonical_state": state, "raw_state": state, "phase_names": ()} + del values[missing] + + with pytest.raises(KeyError, match=f"has no '{missing}'.*built by the flight"): + event(EventContext(time=1.0, **values)) + + assert called == [] + + +def test_a_context_built_by_hand_with_the_time_and_the_state_is_enough(): + seen = [] + event = Event(lambda context: seen.append(context.state.vz)) + state = [0.0] * 5 + [12.0] + [0.0] * 7 + + fired = event( + EventContext(time=1.0, canonical_state=state, raw_state=state, phase_names=()) + ) + + assert fired is True and seen == [12.0] diff --git a/tests/unit/simulation/test_flight.py b/tests/unit/simulation/test_flight.py index 1820170aa..1a2429de6 100644 --- a/tests/unit/simulation/test_flight.py +++ b/tests/unit/simulation/test_flight.py @@ -178,12 +178,11 @@ def test_get_solution_at_time(flight_calisto): def test_get_controller_observed_variables(flight_calisto_air_brakes): """Tests whether the method Flight.get_controller_observed_variables is working as intended.""" - obs_vars = flight_calisto_air_brakes.get_controller_observed_variables() - assert isinstance(obs_vars, list) - # The basic air brakes controller mutates the deployment level but does not - # return observed variables, so every logged entry is None. - assert len(obs_vars) > 0 - assert all(var is None for var in obs_vars) + with pytest.warns(DeprecationWarning): + obs_vars = flight_calisto_air_brakes.get_controller_observed_variables() + # Only a controller function written the deprecated positional way has + # observed variables; this one takes the context, so the list is empty. + assert obs_vars == [] def test_initial_stability_margin(flight_calisto_custom_wind): @@ -822,12 +821,17 @@ def test_an_angular_rate_is_aerodynamically_damped(flight_calisto_robust, deriva equations. """ flight = flight_calisto_robust + controls = flight._controls t, state = _coasting_state(flight) - at_rest = derivative(flight, t, state) + at_rest = derivative(flight, t, state, controls) for axis, rate in ((0, 2.0), (1, 2.0), (2, 20.0)): slot = 10 + axis - positive = derivative(flight, t, _with_rates(state, **{f"w{axis + 1}": rate})) - negative = derivative(flight, t, _with_rates(state, **{f"w{axis + 1}": -rate})) + positive = derivative( + flight, t, _with_rates(state, **{f"w{axis + 1}": rate}), controls + ) + negative = derivative( + flight, t, _with_rates(state, **{f"w{axis + 1}": -rate}), controls + ) assert positive[slot] < at_rest[slot] < negative[slot], f"axis {axis + 1}" # damping is close to linear in the rate at these magnitudes assert positive[slot] - at_rest[slot] == pytest.approx( @@ -846,8 +850,8 @@ def test_solid_propulsion_and_generalized_equations_agree_when_rotating( flight = flight_calisto_robust t, state = _coasting_state(flight) pitching = _with_rates(state, w1=2.0) - solid = u_dot(flight, t, pitching) - generalized = u_dot_generalized(flight, t, pitching) + solid = u_dot(flight, t, pitching, flight._controls) + generalized = u_dot_generalized(flight, t, pitching, flight._controls) assert solid[10] == pytest.approx(generalized[10], rel=0.1) assert solid[3:6] == pytest.approx(generalized[3:6], rel=0.05) @@ -970,7 +974,7 @@ def test_dynamics_take_moments_about_the_center_of_mass( # Vertical, 100 m/s up with 10 m/s sideways: sideslip, no rotation state = [0, 0, 1500, 10.0, 0, 100.0, 1, 0, 0, 0, 0, 0, 0] - out = derivative(flight, t, state, post_processing=True) + out = derivative(flight, t, state, flight._controls, post_processing=True) w_dot, forces, moments = Vector(out[3:6]), Vector(out[6:9]), Vector(out[9:12]) assert abs(moments[1]) > 10 # the fins push back about_center_of_mass = moments + (forces ^ r_cm) @@ -1009,7 +1013,7 @@ def test_generalized_dynamics_match_a_rigid_body_when_rotating( mass = rocket.total_mass.get_value_opt(t) w = Vector([0.4, -0.3, 2.0]) state = [0, 0, 1500, 10.0, -5.0, 100.0, 1, 0, 0, 0, *w] - out = u_dot_generalized(flight, t, state, post_processing=True) + out = u_dot_generalized(flight, t, state, flight._controls, post_processing=True) a_cdm, w_dot = Vector(out[:3]), Vector(out[3:6]) forces, moments, thrust = Vector(out[6:9]), Vector(out[9:12]), out[12] @@ -1049,7 +1053,7 @@ def test_integrator_damping_matches_the_oscillator(flight_calisto_robust): state = [0, 0, 1500, 0, 0, speed, 1, 0, 0, 0, 0, 0, 0] def pitch_acceleration(rate): - out = u_dot_generalized(flight, t, [*state[:10], rate, 0, 0]) + out = u_dot_generalized(flight, t, [*state[:10], rate, 0, 0], flight._controls) return (inertia_cm @ Vector(out[10:13]))[0] step = 1e-3 diff --git a/tests/unit/simulation/test_solution.py b/tests/unit/simulation/test_solution.py index 0dc2214f9..db3daa70a 100644 --- a/tests/unit/simulation/test_solution.py +++ b/tests/unit/simulation/test_solution.py @@ -31,7 +31,7 @@ def descent_row(t, fill=None): return [float(t), *state] -def stub_derivative(flight, t, u, post_processing=False): # pylint: disable=unused-argument +def stub_derivative(flight, t, u, controls, post_processing=False): # pylint: disable=unused-argument """Stand-in equations of motion. These tests store rows, never integrate.""" return [t] if post_processing else list(u) @@ -143,9 +143,6 @@ def test_canonical_array_follows_an_edit(): assert solution.canonical_array[-1][1] == 5.0 solution._replace_last(descent_row(5, fill=[9.0] * 6)) assert solution.canonical_array[-1][1] == 9.0 - # and again when the row is written by position rather than at the tail - solution._set_row(-1, descent_row(5, fill=[7.0] * 6)) - assert solution.canonical_array[-1][1] == 7.0 assert solution.time[-1] == 5.0 @@ -288,9 +285,9 @@ def test_drop_last_removes_and_returns_the_raw_row(): assert solution.raw_row(-1)[0] == 4.0 -def test_setitem_replaces_tail_row(): +def test_replace_last_replaces_tail_row(): solution = build_mixed_solution() - solution._set_row(-1, descent_row(9)) + solution._replace_last(descent_row(9)) assert solution[-1][0] == 9.0 @@ -298,27 +295,27 @@ def test_insert_before_tail_first_row(): """Exact-time insert whose time precedes the tail phase's first row.""" solution = build_mixed_solution() # pop the tail down to a single reduced row - solution._pop(-1) - solution._pop(-1) + solution._drop_last() + solution._drop_last() assert solution.phase_span(1) == (3, 4) - solution._insert(-1, descent_row(2.5)) + solution._insert_before_last(descent_row(2.5)) # inserted before the tail's only row, still in the reduced phase assert solution.phase_span(1) == (3, 5) assert solution.raw_row(3)[0] == 2.5 assert solution.phases[-1].dynamics.width == 6 -def test_pop_across_boundary(): +def test_drop_last_across_boundary(): solution = build_mixed_solution() - solution._pop(-1) - solution._pop(-1) - solution._pop(-1) # empties the reduced phase + solution._drop_last() + solution._drop_last() + solution._drop_last() # empties the reduced phase assert solution.phase_span(1) == (3, 3) # the emptied phase is still the one being flown, but the last row is the # canonical one before it assert solution.phase_index_at(-1) == 0 - # popping again removes the last canonical row - row = solution._pop(-1) + # dropping again removes the last canonical row + row = solution._drop_last() assert len(row) == 14 @@ -607,25 +604,10 @@ def assert_starts_agree(solution): def test_phase_starts_follow_inserts_and_drops(): - """Adding or removing a row moves every phase that begins after it.""" + """Adding or removing a row at the end leaves the phases' starts alone.""" solution = build_mixed_solution() assert [phase.start for phase in solution.phases] == [0, 3] - # inserting inside the first phase pushes the second one along - solution._insert(1, canonical_row(0.5)) - assert [phase.start for phase in solution.phases] == [0, 4] - assert_starts_agree(solution) - - # ... and removing it puts things back - solution._pop(1) - assert [phase.start for phase in solution.phases] == [0, 3] - - # a row inserted exactly at a phase's start joins the later phase - solution._insert(3, descent_row(2.5)) - assert [phase.start for phase in solution.phases] == [0, 3] - assert solution.raw_row(3)[0] == 2.5 - solution._pop(3) - # changes at the very end never move anything solution._insert_before_last(descent_row(4.5)) assert [phase.start for phase in solution.phases] == [0, 3] @@ -667,78 +649,16 @@ def test_index_resolution_skips_empty_phases(): assert solution["vz"].shape == (2, 2) -# --------------------------------------------------------------------------- -# Post-process values recorded beside the rows -# --------------------------------------------------------------------------- - - -def post_values(solution, phase_index): - """The values recorded beside one phase's rows, ``None`` where nothing is.""" - start, stop = solution.phase_span(phase_index) - return solution._post_values[start:stop] - - -def test_post_values_track_every_row_mutation(): - """Values move with their row, so the two can never drift apart.""" - solution = build_mixed_solution() - # one entry per row from the start, empty until something is recorded - assert post_values(solution, 0) == [None, None, None] - assert post_values(solution, 1) == [None, None, None] - - solution._set_post_values(-1, [1.0, 2.0, 3.0]) - assert post_values(solution, 1) == [None, None, [1.0, 2.0, 3.0]] - - # overwriting the row's states makes its recorded values stale - solution._replace_last(descent_row(5, fill=[9.0] * 6)) - assert post_values(solution, 1) == [None, None, None] - - solution._set_post_values(-1, [4.0, 5.0, 6.0]) - # a row inserted just before the last one leaves a gap for its own values, - # and the last row keeps the values that belong to it - solution._insert_before_last(descent_row(4.5)) - assert post_values(solution, 1) == [None, None, None, [4.0, 5.0, 6.0]] - - solution._set_post_values(-2, [7.0, 8.0, 9.0]) - assert post_values(solution, 1) == [ - None, - None, - [7.0, 8.0, 9.0], - [4.0, 5.0, 6.0], - ] - solution._drop_last() - assert post_values(solution, 1) == [None, None, [7.0, 8.0, 9.0]] - - -def test_post_values_stay_the_same_length_as_the_rows(): +def test_controls_stay_the_same_length_as_the_rows(): solution = build_mixed_solution() for mutate in ( lambda: solution._append(descent_row(6)), - lambda: solution._insert(0, canonical_row(-1)), - lambda: solution._pop(0), lambda: solution._insert_before_last(descent_row(5.5)), solution._drop_last, - lambda: solution._set_row(-1, descent_row(9)), + lambda: solution._replace_last(descent_row(9)), ): mutate() - assert len(solution._post_values) == len(solution) - - -def test_recording_values_does_not_disturb_the_cached_states(): - """Values are not part of the flight's states, so nothing is rebuilt.""" - solution = build_mixed_solution() - before = solution.canonical_array - solution._set_post_values(-1, [1.0, 2.0, 3.0]) - assert solution.canonical_array is before - - -def test_set_post_values_outside_the_rows_raises(): - solution = Solution() - solution._start_phase(SIX_DOF_DYNAMICS, tuple([0.0] * 13)) - with pytest.raises(IndexError): - solution._set_post_values(-1, [1.0]) - solution._append(canonical_row(0)) - with pytest.raises(IndexError): - solution._set_post_values(1, [1.0]) + assert len(solution._controls) == len(solution) def test_the_last_row_is_read_through_the_phase_that_owns_it(): @@ -778,11 +698,11 @@ def test_value_at_unknown_state_raises(): # --------------------------------------------------------------------------- -# PostProcessSolution: reading the post-process variables +# The post-process variables, read by name like the states # --------------------------------------------------------------------------- -def replay_derivative(flight, t, u, post_processing=False): # pylint: disable=unused-argument +def replay_derivative(flight, t, u, controls, post_processing=False): # pylint: disable=unused-argument """Report values that say which row they came from, so replay is visible.""" return [t, 2 * t, 3 * t] if post_processing else list(u) @@ -795,7 +715,7 @@ def replay_derivative(flight, t, u, post_processing=False): # pylint: disable=u ) -def replay_thrust_derivative(flight, t, u, post_processing=False): # pylint: disable=unused-argument +def replay_thrust_derivative(flight, t, u, controls, post_processing=False): # pylint: disable=unused-argument """Like :func:`replay_derivative`, for a phase that also reports thrust.""" return [t, 2 * t, 3 * t, 100.0] if post_processing else list(u) @@ -838,61 +758,26 @@ def build_replay_solution(ascent=False): def test_post_names_gather_every_phase_variable(): """Phases need not compute the same variables, and all of them are listed.""" solution = build_mixed_solution() - assert solution.post.names == FULL_POST_PROCESS_VARS - assert "net_thrust" in solution.post + assert solution.post_process_names == FULL_POST_PROCESS_VARS + assert "net_thrust" in solution + assert "net_thrust" in solution.names and "vz" in solution.names # the descent computes only three of them assert solution.phases[1].dynamics.post_process_vars == ("ax", "ay", "az") -def test_values_recorded_during_the_flight_are_read_back_by_name(): - solution = build_replay_solution() - solution.records_post_values = True - for index, values in enumerate([[7.0, 8.0, 9.0], [1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]): - solution._set_post_values(index, values) - assert solution.post["ay"].tolist() == [[0.0, 8.0], [1.0, 2.0], [2.0, 5.0]] - - -def test_a_recording_flight_is_never_worked_out_again(): - """Replaying would read the rocket as it ended, so it must not happen.""" +def test_values_are_worked_out_from_the_stored_states(): solution = build_replay_solution() - solution.records_post_values = True - for index in range(len(solution)): - solution._set_post_values(index, [99.0, 99.0, 99.0]) - # the stub dynamics would give 0, 1, 2 if it were replayed - assert solution.post["ax"][:, 1].tolist() == [99.0, 99.0, 99.0] - - -def test_a_gap_in_a_recording_flight_is_an_error(): - """A row with nothing recorded is a bug, not a reason to replay.""" - solution = build_replay_solution() - solution.records_post_values = True - solution._set_post_values(0, [1.0, 2.0, 3.0]) - with pytest.raises(ValueError, match="row 1 has none"): - _ = solution.post["ax"] - with pytest.raises(ValueError, match="row 1 has none"): - solution.post.at_index(1) - - -def test_values_not_recorded_are_worked_out_from_the_stored_states(): - """A flight that recorded nothing replays its own states instead.""" - solution = build_replay_solution() - assert solution.post["ax"].tolist() == [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]] - assert solution.post["az"].tolist() == [[0.0, 0.0], [1.0, 3.0], [2.0, 6.0]] - - -def test_a_partly_recorded_phase_is_worked_out_again(): - """A flight that does not record is replayed, whatever is left lying in it.""" - solution = build_replay_solution() - solution._set_post_values(1, [99.0, 99.0, 99.0]) - assert solution.post["ax"].tolist() == [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]] + assert solution["ax"].tolist() == [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]] + assert solution.az.tolist() == [[0.0, 0.0], [1.0, 3.0], [2.0, 6.0]] + assert "ax" in dir(solution) def test_a_phase_that_does_not_compute_a_variable_reports_zero(): """A parachute descent really has no thrust, so zero is the right answer.""" solution = build_replay_solution(ascent=True) - assert solution.post.names == ("ax", "ay", "az", "net_thrust") + assert solution.post_process_names == ("ax", "ay", "az", "net_thrust") # the ascent is the first two rows, the descent the last three - assert solution.post["net_thrust"].tolist() == [ + assert solution.net_thrust.tolist() == [ [0.0, 100.0], [1.0, 100.0], [0.0, 0.0], @@ -904,40 +789,43 @@ def test_a_phase_that_does_not_compute_a_variable_reports_zero(): def test_the_replay_is_kept_until_something_changes(): """The replayed tables are cached; a history is a cheap slice of them.""" solution = build_replay_solution() - first = solution.post["ax"] - tables = solution.post._phase_tables() - assert solution.post._phase_tables() is tables - assert solution.post["ax"].tolist() == first.tolist() - # recording a value replaces what was worked out for that phase - solution.records_post_values = True - for index, values in enumerate([[7.0, 8.0, 9.0], [1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]): - solution._set_post_values(index, values) - assert solution.post._phase_tables() is not tables - assert solution.post["ax"].tolist() == [[0.0, 7.0], [1.0, 1.0], [2.0, 4.0]] - solution.records_post_values = False - # so does storing a new row + first = solution.ax + tables = solution._phase_tables() + assert solution._phase_tables() is tables + # a second variable, and the same one again, come from the same tables + assert solution.ay.shape == (3, 2) + assert solution._phase_tables() is tables + assert solution.ax.tolist() == first.tolist() + # storing a new row replaces what was worked out solution._append(descent_row(3)) - assert solution.post["ax"].shape == (4, 2) + assert solution._phase_tables() is not tables + assert solution.ax.shape == (4, 2) def test_reading_one_row_does_not_work_out_the_whole_flight(): solution = build_replay_solution() - solution._set_post_values(-1, [4.0, 5.0, 6.0]) - assert solution.post.at_index(-1) == {"ax": 4.0, "ay": 5.0, "az": 6.0} - # a row with nothing recorded is worked out on its own - assert solution.post.at_index(0) == {"ax": 0.0, "ay": 0.0, "az": 0.0} - assert solution.post.at(1.0) == {"ax": 1.0, "ay": 2.0, "az": 3.0} + assert solution._post_at_index(-1) == {"ax": 2.0, "ay": 4.0, "az": 6.0} + assert solution._post_at_index(0) == {"ax": 0.0, "ay": 0.0, "az": 0.0} + assert solution._post_tables is None # nothing worked out for the whole flight + # at(t) gives the states and the post-process variables together + values = solution.at(1.0) + assert {name: values[name] for name in ("ax", "ay", "az")} == { + "ax": 1.0, + "ay": 2.0, + "az": 3.0, + } + assert values["vz"] == solution.value_at(1, "vz") def test_reading_a_row_outside_the_flight_raises(): solution = build_replay_solution() with pytest.raises(IndexError): - solution.post.at_index(3) + solution._post_at_index(3) def test_phase_values_gives_one_phase_at_a_time(): solution = build_replay_solution() - assert solution.post.phase_values(0).tolist() == [ + assert solution.phase_values(0).tolist() == [ [0.0, 0.0, 0.0], [1.0, 2.0, 3.0], [2.0, 4.0, 6.0], @@ -946,8 +834,10 @@ def test_phase_values_gives_one_phase_at_a_time(): def test_an_unknown_variable_says_what_the_flight_computes(): solution = build_replay_solution() - with pytest.raises(KeyError, match="No flight phase computed"): - _ = solution.post["not_a_variable"] + with pytest.raises(KeyError, match="nothing named 'not_a_variable'. It has: x, y"): + _ = solution["not_a_variable"] + with pytest.raises(AttributeError, match="nothing named 'not_a_variable'"): + _ = solution.not_a_variable def test_a_solution_read_back_from_a_file_cannot_report_them(): @@ -958,17 +848,19 @@ def test_a_solution_read_back_from_a_file_cannot_report_them(): ) solution._append(descent_row(0)) with pytest.raises(KeyError, match="read back from a saved file"): - _ = solution.post["ax"] - with pytest.raises(KeyError, match="read back from a saved file"): - solution.post.at_index(0) + _ = solution["ax"] + assert solution._post_at_index(0) == {} + assert "ax" not in solution.at(0.0) def test_a_flight_with_no_rows_has_nothing_to_report(): solution = Solution() solution._start_phase(REPLAY_DYNAMICS.bind(None), start_canonical=tuple([0.0] * 13)) - assert solution.post.names == ("ax", "ay", "az") + assert solution.post_process_names == ("ax", "ay", "az") with pytest.raises(KeyError, match="no stored states yet"): - _ = solution.post["ax"] + _ = solution["ax"] + with pytest.raises(AttributeError, match="no stored states yet"): + _ = solution.ax def test_canonical_row_fills_in_what_the_phase_does_not_integrate(): @@ -1193,3 +1085,71 @@ def test_saving_a_flight_keeps_every_phase_width(): assert restored.canonical_array.tolist() == solution.canonical_array.tolist() with pytest.warns(UserWarning, match="not defined during"): assert restored["heading"][:, 1].tolist() == [4.0, 5.0] + + +def controlled_derivative(flight, t, u, controls, post_processing=False): # pylint: disable=unused-argument + """Report the row's time and the trim value it was given.""" + return [t, controls["tab.trim"], 0.0] if post_processing else list(u) + + +def test_a_replayed_row_is_given_the_controls_stored_with_it(): + """A row worked out again after the flight reads its own controls.""" + dynamics = _PhaseDynamics( + "controlled", + controlled_derivative, + ("x", "y", "z", "vx", "vy", "vz"), + ("ax", "ay", "az"), + ) + solution = Solution() + solution._start_phase( + dynamics.bind(None), t_start=0.0, start_canonical=tuple([0.0] * 13) + ) + for t, trim in enumerate([0.0, 0.25, 0.5]): + solution._append(descent_row(t)) + solution._set_controls(-1, {"tab.trim": trim}) + + assert solution.ay.tolist() == [[0.0, 0.0], [1.0, 0.25], [2.0, 0.5]] + assert solution.at(1.0)["ay"] == 0.25 + # a rolled-back row loses its controls until they are stored again + solution._replace_last(descent_row(1.5)) + assert solution._controls[-1] is None + + +def test_the_controls_are_read_apart_from_the_states(): + solution = build_mixed_solution() + for index, deflection in enumerate([0.0, 0.0, 0.1, 0.1, 0.2, 0.2]): + solution._set_controls(index, {"canards.deflection": deflection}) + + assert solution.control_names == ("canards.deflection",) + history = solution.controls.canards.deflection + assert history.shape == (len(solution), 2) + assert history[:, 0].tolist() == solution.time.tolist() + assert history[:, 1].tolist() == [0.0, 0.0, 0.1, 0.1, 0.2, 0.2] + # the same series by its name, as given or in parts + assert solution["canards.deflection"].tolist() == history.tolist() + assert solution.controls["Canards"]["deflection"].tolist() == history.tolist() + assert list(solution.controls) == ["canards"] + assert list(solution.controls.canards) == ["deflection"] + assert "canards.deflection" in solution.names + assert solution.at(2.0)["canards.deflection"] == 0.1 + assert isinstance(solution.controls, dict) + assert list(solution.controls.items())[0][0] == "canards" + + +def test_a_solution_without_controls_has_no_control_inputs(): + solution = build_mixed_solution() + assert solution.control_names == () + assert len(solution.controls) == 0 + assert list(solution.controls) == [] + assert "controls" not in solution.to_dict() + + +def test_controls_round_trip_through_dict(): + solution = build_mixed_solution() + for index in range(len(solution)): + solution._set_controls(index, {"a.x": float(index), "b.y": -1.0}) + + restored = Solution.from_dict(solution.to_dict()) + + assert restored._controls == solution._controls + assert restored.controls.a.x.tolist() == solution.controls.a.x.tolist() diff --git a/tests/unit/simulation/test_surface_activation.py b/tests/unit/simulation/test_surface_activation.py index d95f69b4d..824cbc1e3 100644 --- a/tests/unit/simulation/test_surface_activation.py +++ b/tests/unit/simulation/test_surface_activation.py @@ -112,7 +112,7 @@ def test_surface_commands_are_queued_and_mark_a_trajectory_change(): commands.activate_surface(deployable) assert commands.surface_switches == [(removable, False), (deployable, True)] - # the forces change, so the solver has to restart from the switch + # the forces change, so the flight rolls back to the switch assert commands.changes_trajectory is True commands.reset() diff --git a/tests/unit/stochastic/test_stochastic_aero_surfaces.py b/tests/unit/stochastic/test_stochastic_aero_surfaces.py index d63feb76c..c25f84611 100644 --- a/tests/unit/stochastic/test_stochastic_aero_surfaces.py +++ b/tests/unit/stochastic/test_stochastic_aero_surfaces.py @@ -1,4 +1,6 @@ +from rocketpy import AirBrakes from rocketpy.rocket.aero_surface import NoseCone, RailButtons, Tail, TrapezoidalFins +from rocketpy.stochastic import StochasticAirBrakes ## NOSE CONE @@ -90,3 +92,24 @@ class creates a StochasticRailButtons object from the randomly generated """ obj = stochastic_rail_buttons.create_object() assert isinstance(obj, RailButtons) + + +## AIR BRAKES + + +def test_stochastic_air_brakes_scale_the_drag_and_keep_the_settings(): + """The drag curve factor reaches the drag flown, and the motor phase the + air brakes act in and their switch are carried over.""" + brakes = AirBrakes( + "data/rockets/calisto/air_brakes_cd.csv", + 0.01, + active_during="power_off", + active=False, + ) + obj = StochasticAirBrakes( + brakes, drag_coefficient_curve_factor=(2.0, 0) + ).create_object() + assert obj.cA(0, 0, 0.5, 0, 0, 0, 0, 1.0) == 2 * brakes.cA( + 0, 0, 0.5, 0, 0, 0, 0, 1.0 + ) + assert obj.active_during == "power_off" and obj.active is False diff --git a/tests/unit/stochastic/test_stochastic_rocket.py b/tests/unit/stochastic/test_stochastic_rocket.py index bef344cca..dbfdf6e95 100644 --- a/tests/unit/stochastic/test_stochastic_rocket.py +++ b/tests/unit/stochastic/test_stochastic_rocket.py @@ -1,6 +1,10 @@ import pytest from rocketpy import ( + Accelerometer, + Barometer, + ControlFins, + Controller, FreeFormFins, GenericSurface, StochasticNoseCone, @@ -113,3 +117,151 @@ def surfaces(r): assert surfaces(generated) == surfaces(rocket) assert generated.static_margin(0) == pytest.approx(rocket.static_margin(0)) + + +def test_added_effectors_are_carried_over( + stochastic_calisto, calisto_robust, push_effector, gimbal +): + """Thrust and force effectors have no stochastic + version; each generated rocket keeps them and their channels.""" + calisto_robust.add_effector(gimbal) + calisto_robust.add_effector(push_effector) + obj = stochastic_calisto.create_object() + assert obj.effectors.get_components() == [gimbal, push_effector] + assert obj.control_names[-2:] == ("gimbal.pitch", "push.on") + + +def test_air_brakes_are_dispersed_once(stochastic_calisto, calisto_air_brakes_clamp_on): + """The base rocket's air brakes are a surface; the stochastic rocket + replaces them with its dispersed copy rather than carrying both over.""" + (brakes,) = calisto_air_brakes_clamp_on.air_brakes + (controller,) = calisto_air_brakes_clamp_on.controllers + stochastic_calisto.add_air_brakes(brakes, controller) + obj = stochastic_calisto.create_object() + + (dispersed,) = obj.air_brakes + assert dispersed is not brakes + assert obj._is_at_center_of_dry_mass( + dispersed + ) == calisto_air_brakes_clamp_on._is_at_center_of_dry_mass(brakes) + assert obj.control_names == ("air_brakes.deployment_level",) + assert len(obj.controllers) == 1 and obj.controllers[0] is not controller + + +def test_every_controller_is_carried_as_a_copy(stochastic_calisto, calisto_robust): + """Each sampled rocket flies its own copy of every controller of the + rocket, in the order they were added, with the surface they turn.""" + fin = TrapezoidalFin( + angular_position=0, + root_chord=0.08, + tip_chord=0.04, + span=0.06, + rocket_radius=0.0635, + ) + calisto_robust.add_surfaces(ControlFins(fin, n=4, name="Canards"), 0.8) + first = Controller(lambda context: None, sampling_rate=10, name="Roll loop") + second = Controller(lambda context: None, sampling_rate=50, name="Pitch loop") + calisto_robust.add_controller(first) + calisto_robust.add_controller(second) + + one = stochastic_calisto.create_object() + other = stochastic_calisto.create_object() + + for sampled in (one, other): + assert [c.name for c in sampled.controllers] == ["Roll loop", "Pitch loop"] + assert [c.sampling_rate for c in sampled.controllers] == [10, 50] + assert sampled.control_names[-4:] == calisto_robust.control_names[-4:] + # Copies: a flight of one sample leaves the base rocket's and the other + # sample's controllers as they were + assert not {first, second} & {*one.controllers, *other.controllers} + assert not set(one.controllers) & set(other.controllers) + assert calisto_robust.controllers == (first, second) + + +def test_the_air_brakes_controller_is_carried_once( + stochastic_calisto, calisto_air_brakes_clamp_on +): + """The controller of the air brakes is one of the rocket's controllers: + it is not added a second time for having been given to add_air_brakes.""" + (brakes,) = calisto_air_brakes_clamp_on.air_brakes + (brakes_controller,) = calisto_air_brakes_clamp_on.controllers + calisto_air_brakes_clamp_on.add_controller( + Controller(lambda context: None, sampling_rate=20, name="Logger") + ) + stochastic_calisto.add_air_brakes(brakes, brakes_controller) + + sampled = stochastic_calisto.create_object() + + assert [c.name for c in sampled.controllers] == [brakes_controller.name, "Logger"] + + +def test_sensors_are_carried_as_copies(stochastic_calisto, calisto_robust): + """Each sampled rocket has the rocket's sensors, at their positions, as + its own copies. A sensor added in two positions stays one sensor.""" + barometer = Barometer(sampling_rate=50, name="Barometer") + accelerometer = Accelerometer(sampling_rate=100, name="Accelerometer") + calisto_robust.add_sensor(barometer, 0.5) + calisto_robust.add_sensor(accelerometer, (0, 0.05, 0.2)) + calisto_robust.add_sensor(accelerometer, (0, -0.05, 0.2)) + barometer.measured_data.append((0.0, 101325.0)) # as after a flight + + one = stochastic_calisto.create_object() + other = stochastic_calisto.create_object() + + for sampled in (one, other): + copies = sampled.sensors.get_components() + assert [type(sensor) for sensor in copies] == [ + Barometer, + Accelerometer, + Accelerometer, + ] + assert sampled.sensors.get_positions() == calisto_robust.sensors.get_positions() + assert copies[1] is copies[2] + assert copies[0] is not barometer and copies[1] is not accelerometer + assert copies[0].sampling_rate == 50 and copies[0].measured_data == [] + # Each copy knows the sampled rocket alone + assert copies[0]._attached_rockets == {sampled: 1} + assert copies[1]._attached_rockets == {sampled: 2} + assert len(sampled._sensor_events) == 3 + assert one.sensors.get_components()[0] is not other.sensors.get_components()[0] + # The rocket's own sensors do not keep the sampled rockets + assert barometer._attached_rockets == {calisto_robust: 1} + assert accelerometer._attached_rockets == {calisto_robust: 2} + assert barometer.measured_data == [(0.0, 101325.0)] + + +def test_air_brakes_not_given_are_carried_as_they_are( + stochastic_calisto, calisto_air_brakes_clamp_on +): + """Without add_air_brakes the sampled rocket still has the rocket's air + brakes, so the controller carried with it has something to set.""" + (brakes,) = calisto_air_brakes_clamp_on.air_brakes + + sampled = stochastic_calisto.create_object() + + assert sampled.air_brakes == [brakes] + assert sampled.control_names == ("air_brakes.deployment_level",) + assert len(sampled.controllers) == 1 + assert sampled._is_at_center_of_dry_mass( + brakes + ) == calisto_air_brakes_clamp_on._is_at_center_of_dry_mass(brakes) + + +def test_a_plain_surface_is_accepted_and_wrapped(calisto_robust): + """add_nose, add_tail and the fins take the surface itself as well as its + stochastic version.""" + surfaces = {type(s).__name__: s for s, _ in calisto_robust.aerodynamic_surfaces} + stochastic = StochasticRocket(calisto_robust) + + stochastic.add_nose(surfaces["NoseCone"], position=0.001) + stochastic.add_trapezoidal_fins(surfaces["TrapezoidalFins"], position=0.001) + stochastic.add_tail(surfaces["Tail"], position=0.001) + + wrapped = [ + type(s).__name__ for s in stochastic.aerodynamic_surfaces.get_components() + ] + assert wrapped == [ + "StochasticNoseCone", + "StochasticTrapezoidalFins", + "StochasticTail", + ] diff --git a/tests/unit/test_flight_data_exporter.py b/tests/unit/test_flight_data_exporter.py index 76fbcecd7..1548c6dcd 100644 --- a/tests/unit/test_flight_data_exporter.py +++ b/tests/unit/test_flight_data_exporter.py @@ -57,8 +57,11 @@ def __init__(self, name): self.name = name s1 = DummySensor("DummySensor") + # the rows are worked out from the flight's readings, so they are + # replaced for this test monkeypatch.setattr( - flight_calisto, "sensor_data", {s1: [1.0, 2.0, 3.0]}, raising=False + "rocketpy.simulation.flight_data_exporter._sensor_rows", + lambda _: {s1: [1.0, 2.0, 3.0]}, ) out = tmp_path / "sensors.json"