\[ \begin{align}\begin{aligned}\newcommand\blank{~\underline{\hspace{1.2cm}}~}\\% Bold symbols (vectors) \newcommand\bs[1]{\mathbf{#1}}\\% Differential \newcommand\dd[2][]{\mathrm{d}^{#1}{#2}} % use as \dd, \dd{x}, or \dd[2]{x}\\% Poor man's siunitx \newcommand\unit[1]{\mathrm{#1}} \newcommand\num[1]{#1} \newcommand\qty[2]{#1~\unit{#2}}\\\newcommand\per{/} \newcommand\squared{{}^2} \newcommand\cubed{{}^3} % % Scale \newcommand\milli{\unit{m}} \newcommand\centi{\unit{c}} \newcommand\kilo{\unit{k}} \newcommand\mega{\unit{M}} % % Percent \newcommand\percent{\unit{{\kern-4mu}\%}} % % Angle \newcommand\radian{\unit{rad}} \newcommand\degree{\unit{{\kern-4mu}^\circ}} % % Time \newcommand\second{\unit{s}} \newcommand\s{\second} \newcommand\minute{\unit{min}} \newcommand\hour{\unit{h}} % % Distance \newcommand\meter{\unit{m}} \newcommand\m{\meter} \newcommand\inch{\unit{in}} \newcommand\foot{\unit{ft}} % % Force \newcommand\newton{\unit{N}} \newcommand\kip{\unit{kip}} % kilopound in "freedom" units - edit made by Sri % % Mass \newcommand\gram{\unit{g}} \newcommand\g{\gram} \newcommand\kilogram{\unit{kg}} \newcommand\kg{\kilogram} \newcommand\grain{\unit{grain}} \newcommand\ounce{\unit{oz}} % % Temperature \newcommand\kelvin{\unit{K}} \newcommand\K{\kelvin} \newcommand\celsius{\unit{{}^\circ C}} \newcommand\C{\celsius} \newcommand\fahrenheit{\unit{{}^\circ F}} \newcommand\F{\fahrenheit} % % Area \newcommand\sqft{\unit{sq\,\foot}} % square foot % % Volume \newcommand\liter{\unit{L}} \newcommand\gallon{\unit{gal}} % % Frequency \newcommand\hertz{\unit{Hz}} \newcommand\rpm{\unit{rpm}} % % Voltage \newcommand\volt{\unit{V}} \newcommand\V{\volt} \newcommand\millivolt{\milli\volt} \newcommand\mV{\milli\volt} \newcommand\kilovolt{\kilo\volt} \newcommand\kV{\kilo\volt} % % Current \newcommand\ampere{\unit{A}} \newcommand\A{\ampere} \newcommand\milliampereA{\milli\ampere} \newcommand\mA{\milli\ampere} \newcommand\kiloampereA{\kilo\ampere} \newcommand\kA{\kilo\ampere} % % Resistance \newcommand\ohm{\Omega} \newcommand\milliohm{\milli\ohm} \newcommand\kiloohm{\kilo\ohm} % correct SI spelling \newcommand\kilohm{\kilo\ohm} % "American" spelling used in siunitx \newcommand\megaohm{\mega\ohm} % correct SI spelling \newcommand\megohm{\mega\ohm} % "American" spelling used in siunitx % % Capacitance \newcommand\farad{\unit{F}} \newcommand\F{\farad} \newcommand\microfarad{\micro\farad} \newcommand\muF{\micro\farad} % % Inductance \newcommand\henry{\unit{H}} \newcommand\H{\henry} \newcommand\millihenry{\milli\henry} \newcommand\mH{\milli\henry} % % Power \newcommand\watt{\unit{W}} \newcommand\W{\watt} \newcommand\milliwatt{\milli\watt} \newcommand\mW{\milli\watt} \newcommand\kilowatt{\kilo\watt} \newcommand\kW{\kilo\watt} % % Energy \newcommand\joule{\unit{J}} \newcommand\J{\joule} % % Composite units % % Torque \newcommand\ozin{\unit{\ounce}\,\unit{in}} \newcommand\newtonmeter{\unit{\newton\,\meter}} % % Pressure \newcommand\psf{\unit{psf}} % pounds per square foot \newcommand\pcf{\unit{pcf}} % pounds per cubic foot \newcommand\pascal{\unit{Pa}} \newcommand\Pa{\pascal} \newcommand\ksi{\unit{ksi}} % kilopound per square inch % NOTE: do NOT define \bar -- it is the built-in LaTeX accent used by \bar{x}, % \bar{y} (sample means). Redefining it made those render as the word "bar". \newcommand\barunit{\unit{bar}} \end{aligned}\end{align} \]

Nov 16, 2026 | 2182 words | 22 min read

19.4. Milestone 4 - Iteration #2: Greenhouse Controller (Team)#

At a Glance

What you will do: Build your Milestone 3 design as a set of Python functions and test it against the acceptance test. In Milestone 4, respond to the GHU-2 commissioning report, write an analysis script that measures your controller sol by sol across several missions, and improve the controller through documented tuning cycles.

What you will submit: One team submission: your student_controller/ package, your analysis script (analyze_mission.py), its per-sol metrics file (per_sol_metrics.csv), your plots, and your tuning log (with the AI Use Log).

This task spans Milestones 3 and 4

You build your controller in two passes, which match the two iteration cycles in your report.

  • Milestone 3, Iteration #1: Complete Steps 1 to 2. Write your first draft from your flowchart and run it until the crop survives the mission. Submit the working first draft at TP3.

  • Milestone 4, Iteration #2: Complete Steps 3 to 5. Respond to the commissioning report, analyze the controller with your own script and plots, and tune it until it is efficient and reliable. Submit the tuned final version at TP4.

19.4.1. How Your Controller Works#

Your controller is a small package, a folder named student_controller/ that holds one function per actuator and a main.py that runs them.

The folder holds these files.

  • heater.py, leds.py, co2.py, pump.py: one control function each, for example def control_heater(readings, setpoints, dt, state). Each returns a command from 0 to 100 for its actuator.

  • main.py: a given control_all(readings, setpoints, dt, state) that calls your four functions and packages their outputs.

    You fill in the four actuator functions AND leave main.py and __init__.py as they are.

  • hardware.py: your team’s hardware selection, two lines that name the glazing and the heater (GLAZING and HEATER_W). The simulator and the acceptance test both read it.

Each control function receives four arguments. readings holds the current sensor values, such as readings.temperature_c. setpoints holds the current targets, such as setpoints.temperature_c, which follows the day and night schedule. dt is the length of one tick in seconds, 60 by default, and is the dt in the integral and derivative equations of the Control Strategies Primer. state is described below.

Some strategies must remember a value between ticks. PI remembers its integral, and PID also remembers the previous error. These values are stored in a plain dictionary named state that is passed to your functions on every tick. Your function reads the old value and writes the new value back, so the new value is available on the next call. The example below shows the mechanism with a running total.

def running_total(amount, state):
    # state is a plain dict handed in from outside, so it survives between calls
    state["total"] = state.get("total", 0.0) + amount
    return state["total"]

state = {}                       # created once, outside the function
print(running_total(1, state))   # 1.0
print(running_total(1, state))   # 2.0  <- state kept the total from the first call

A value stored in state is kept from tick to tick. A local variable created inside the function starts over on every call. Your PI integral needs only this mechanism. All four actuator files share one state dictionary, so start every key with your actuator’s name, such as state["heater_total"]. Two files that both write state["total"] overwrite each other without any error message. The template package already has the four function files in place, and you write the control logic in them.

19.4.2. Step 1: Implement Your Design#

Do this work inside your unzipped sandbox folder, which is the same kit you used to operate the greenhouse in Milestone 2. It contains the student_controller_template/ folder, the martian_greenhouse_sim/ package, and two practice acceptance checks: practice_test_m3.py for Milestone 3 and practice_test_m4.py for Milestone 4.

Important

If your sandbox folder has a file named practice_test_config.py instead of these two files, it is an older copy. Download greenhouse_sandbox.zip again, unzip it to a new folder, and copy your student_controller/ folder into it.

  1. Copy the student_controller_template/ folder to a folder named student_controller/ in that same place. You fill in the four actuator functions. Leave main.py and __init__.py as they are.

  2. Assign GLAZING and HEATER_W in hardware.py to the hardware your Milestone 3 design memo chose.

  3. Translate your Milestone 3 flowchart into your four control functions. Every box in the flowchart should be recognizable in the code. Your code must follow professional programming standards.

  4. Start with the parameter values from your M3 parameter table.

  5. Divide the work by actuator, as the roles table in section II of your report assigns it. Each of the four actuators (heater, LEDs, CO2 valve, pump) has its own file and a named owner. The owner is responsible for that function, its rows in the parameter table, and its tuning cycles. Mark the owner at the top of that file. The team jointly owns the integrated behavior in main.py and the CO2 sensor-trust rule. Integrate and review the code together.

Run a first mission from inside your sandbox folder:

# quick_run.py, saved next to your student_controller/ folder
from martian_greenhouse_sim.simulation import (
    load_student_controller,
    load_student_hardware,
    run_simulation,
)

controller = load_student_controller(search_dirs=["."])
hardware = load_student_hardware(search_dirs=["."])
result = run_simulation(days=30, seed=42, controller_cls=controller, hardware=hardware)
print(result.summary())

result.summary() prints the mission report: sols survived, temperature error, CO2 and humidity performance, any safety events, and your hardware’s worst-sol energy and launch mass.

19.4.3. Step 2: Run the Practice Acceptance Check#

Your sandbox folder includes a practice copy of the client’s Milestone 3 acceptance test, practice_test_m3.py. It scores the same criteria as the graded test on one 30-sol mission. With your student_controller/ package in place, run the practice check from inside your sandbox folder.

python practice_test_m3.py

The practice check runs the following tests.

  • the hardware is declared and on the menu

  • the file loads

  • the mission completes

  • no CO2 toxic event

  • plants survive >= 28 of 30 sols

  • mean temperature error \(< 2.5\ ^\circ\text{C}\)

  • CO2 in band \(\geq 65\%\) of the time

  • relative humidity in \(40\) to \(60\%\) at least \(25\%\) of the time

  • deterministic repeat runs

  • launch mass (glazing, heater, and battery) \(\leq 600\ \text{kg}\)

The graded test flies several 30-sol missions that you cannot see. Each one has a dust storm and K30 freezes at different times, and every test must pass on every mission. The practice check flies the mission with seed 42. To fly a different mission, give the practice check another seed.

python practice_test_m3.py --seed 7

Important

The acceptance test runs your controller on the hardware declared in student_controller/hardware.py. If the declaration is missing or names hardware that is not on the menu, the hardware test fails and the mission runs on the as-built hardware (twin-wall glazing, \(2000\ \text{W}\) heater) instead. You do not modify the simulation files.

Warning

A controller that hard-codes an action sequence against the practice run will likely fail the graded test. Your program must respond to your sensor readings, and it must not depend on one specific set of circumstances.

Read these two notes before you tune:

  • Gap analysis (graded, in the tuning log): Before tuning, compare these acceptance criteria with the criteria for success your team wrote in Milestone 1 (report section III.b). Identify where they differ and which set is stricter. The gap analysis helps you understand the contract you are held to. It does not replace your numbers with the client’s. Compare what the acceptance test asks of humidity with the client’s original \(40\) to \(60\%\) requirement, and connect it to your M3 achievability assessment. Compare the worst-sol energy and launch mass that the practice check reports with your Milestone 2 estimate, and explain the difference.

  • Test on several missions: Run the practice check on several seeds of your own choosing before you submit. A controller tuned to one specific storm is not a viable solution, and none of the graded missions is the practice mission.

19.4.4. Step 3: Respond to the Commissioning Report#

Milestone 4 starts with new information from the client. Read the GHU-2 Commissioning Report and download its telemetry log. Commissioning found two CO2 sensor faults, and the Milestone 4 acceptance test includes both. The flight unit carries no reference analyzer, so your controller still reads only the K30 and the SCD41.

  1. Characterize each fault from the log. For every fault event in the log, record when it began and ended, which sensor failed, what that sensor reported, and how its readings during the event differ from its readings when it works. Support each claim with a plot or a number from the log. Use the reference samples to confirm which sensor was wrong. Your controller has no access to them.

  2. Run your Milestone 3 controller against the new faults. practice_test_m4.py scores the same criteria on a mission with the commissioning faults. Record which tests fail, and explain each failure with your fault characterization.

  3. Revise the CO2 sensor-trust logic. Update the CO2 branch of your flowchart first, then co2.py. On every tick your logic decides which reading to act on, using the current readings and any values your code stored in state on earlier ticks. Start each state key in co2.py with co2_.

  4. Show that the revision works. Run practice_test_m4.py on several seeds and record each result.

python practice_test_m4.py
python practice_test_m4.py --seed 7

Record the fault characterization (a table with one row per fault event), the revised flowchart branch, and the practice results before and after the revision in your tuning log under Commissioning Findings. The graded Milestone 4 test flies several missions that you cannot see, all with these faults, and every test must pass on every mission.

19.4.5. Step 4: Write Your Analysis Script#

A score reports whether the controller worked. The mission log shows why and where it did not. Write analyze_mission.py so that one command from your sandbox folder regenerates every metric and plot in your tuning log.

  1. Fly several missions and save each log. Use at least three seeds, including 42, with the Milestone 4 faults on. This code runs the missions and saves the logs.

    from martian_greenhouse_sim.constants import M4_SENSOR_FAULTS
    from martian_greenhouse_sim.simulation import (
        load_student_controller,
        load_student_hardware,
        run_simulation,
    )
    
    controller = load_student_controller(search_dirs=["."])
    hardware = load_student_hardware(search_dirs=["."])
    for seed in (42, 7, 1234):
        result = run_simulation(days=30, seed=seed, controller_cls=controller,
                                hardware=hardware, log_records=True,
                                sensor_overrides=M4_SENSOR_FAULTS)
        with open(f"mission_log_{seed}.csv", "w") as f:
            f.write(result.to_csv())
    
  2. Compute per-sol metrics with your own functions. Load each log with pandas. Define at least these three functions, each with a docstring, and call them inside loops over the missions and over the sols of each mission.

    • setpoint_c(time_s) returns the temperature setpoint at a time. The log does not record the setpoint. It is \(23\ ^\circ\text{C}\) during the day and \(18\ ^\circ\text{C}\) at night. The simulator counts a moment as day when math.sin(2 * math.pi * time_s / SOL_SECONDS - math.pi / 2) > 0, where SOL_SECONDS comes from martian_greenhouse_sim.constants.

    • find_windows(flags, times) returns the start and end time of every run of True values in a column such as dust_storm_active, co2_freeze_active, or scd41_drift_active.

    • summarize_sol(rows) returns the metrics in the table below for one complete sol.

    Write the results to per_sol_metrics.csv, with one row per complete sol of each mission and these columns.

    Column

    Meaning

    seed

    The mission

    sol

    The sol number, starting at 0

    mean_temp_error_c

    Mean absolute difference between t_in_c and the setpoint

    pct_temp_in_band

    Percent of ticks within \(\pm 2\ ^\circ\text{C}\) of the setpoint

    pct_co2_in_band

    Percent of ticks with co2_ppm from 800 to 1000

    energy_kwh

    Heater and LED energy in kWh: the sum over the sol of electrical_w times the row’s interval length in seconds, divided by 3,600,000

    storm

    Whether the dust storm was active during the sol

    k30_frozen_min

    Minutes the K30 was frozen

    scd41_drift_min

    Minutes the SCD41 was drifting

  3. Plot. Produce at least these four plots with matplotlib and save each as a PNG, formatted to the course’s professional standards, with titles, axis labels with units, and legends.

    • Temperature tracking: t_in_c vs sol, with the day and night setpoints, the dust-storm window, and the \(\pm 2\ ^\circ\text{C}\) band shaded or marked.

    • CO2 data: co2_ppm (actual), co2_k30_reading, and co2_scd41_reading vs sol on one chart, with the K30 freeze and SCD41 drift windows marked. The chart shows how your sensor-trust logic performs during each fault.

    • Effort: at least one actuator trace (for example heater_pct vs sol).

    • Per-sol comparison: one column of per_sol_metrics.csv (for example pct_temp_in_band or energy_kwh) vs sol, one line per mission.

  4. Print a scoreboard. Print one line per mission with the headline metrics from result (mean temperature error, percent CO2 in band, sols survived, launch mass), then one line with the worst value of each across your missions. The graded test scores each criterion on its worst mission.

Note

Each log row records the greenhouse state at the start of its 60-second interval. The acceptance test scores the state at the end of each interval. Per-sol numbers computed from a log therefore differ slightly from the headline metrics in result. Label which numbers come from the log and which come from result.

19.4.6. Step 5: Tune and Log at Least Two Cycles#

Record every tuning cycle in your tuning log. For each cycle, the log records these items.

  • Who ran the cycle

  • The parameter or parameters changed, and why (cite a plot or metric)

  • The expected effect on a named metric

  • The new values

  • The resulting metrics, next to what you expected

  • The verdict: keep, revert, or adjust further

Write down the expected effect before you run the cycle. At least one full cycle per team member is required, and every member runs and documents at least one.

At least one cycle targets the CO2 sensor-trust logic from Step 3. Every cycle cites a plot or a row of per_sol_metrics.csv, and every result comes from your analysis script on all of its missions.

Use the diagnostic table at the end of the primer to read your plots. Sawtooth, offset, overshoot just after sunrise, and noise-chasing each have a recognizable signature.

Optional stretch: Use mission logs from several seeds to calculate the mean and standard deviation of your temperature error. Then use the normal model to estimate the probability that a random minute stays within 2 C of setpoint. This value shows how reliable your controller is across missions.

19.4.7. Submission#

Make one team submission to 19.3 Milestone 4 - Iteration #2: Greenhouse Controller (Team) in Gradescope, with all members added. The submission contains these items:

  • Your student_controller/ package, including hardware.py, which passes practice_test_m4.py on several seeds.

  • analyze_mission.py, which runs from your sandbox folder and regenerates your metrics and plots.

  • per_sol_metrics.csv.

  • Your plot PNGs (at least four).

  • The tuning log (PDF): gap analysis, commissioning findings, all cycles, final parameter table, and your updated AI Use Log.

Do not upload the mission logs. Each one is about 11 MB, and your script regenerates them.

Submit before the deadline on the Course Schedule.

Learning Objectives

PR01:

Programming Standards - Develop code that follows established programming standards and conventions.

PR02:

Data Storage - Store and access data appropriately.

PR04:

Modular Programming - Create and use modular code components, including scripts and user-defined functions.

PR05:

Code Structures - Understand and write sequential and non-sequential code structures to achieve a programming objective.

PR06:

Translate Program Descriptions - Translate written descriptions or flowcharts into working code.

PR07:

Test Cases and Tracking - Test and track information through flowcharts and programs.

PR08:

Debugging - Debug and refine code so that it achieves its objective without dynamic or semantic errors.

EB05:

Iterative Improvement - Present findings from iterative testing or optimization efforts.

DV01:

Table and Plot Formatting - Prepare tables and plots for technical presentation with proper formatting. Include descriptive titles, axis labels with units, appropriately scaled axes, and visible legends.

AI05:

Communicate clearly and effectively about AI usage and the choices surrounding it in a given field.