Electric Vehicles
In this example, a battery electric vehicle (BEV) is driven 100 km in the morning and 100 km in the evening, to simulate commuting, and charged during the day by a solar panel at the driver's place of work. The size of the panel is computed by the optimisation.
The BEV has a battery of size 100 kWh and an electricity consumption of 0.18 kWh/km.
This example will use units of kW and kWh, unlike the PyPSA defaults. This is unproblematic as long as no power flow simulations are performed.
In [2]:
Copied!
import matplotlib.pyplot as plt
import pandas as pd
import pypsaimport matplotlib.pyplot as plt import pandas as pd import pypsa
As time index, we use a 24 hour period.
In [3]:
Copied!
index = pd.date_range("2016-01-01 00:00", "2016-01-01 23:00", freq="h")index = pd.date_range("2016-01-01 00:00", "2016-01-01 23:00", freq="h")
The consumption pattern in kW of the BEV is defined as follows
In [4]:
Copied!
bev_usage = pd.Series([0] * 7 + [9] * 2 + [0] * 8 + [9] * 2 + [0] * 5, index)bev_usage = pd.Series([0] * 7 + [9] * 2 + [0] * 8 + [9] * 2 + [0] * 5, index)
The capacity factor profile of the solar panel in per-unit of capacity is given by:
In [5]:
Copied!
pv_pu = pd.Series(
[0.0] * 7
+ [0.2, 0.4, 0.6, 0.75, 0.85, 0.9, 0.85, 0.75, 0.6, 0.4, 0.2, 0.1]
+ [0.0] * 5,
index,
)pv_pu = pd.Series( [0.0] * 7
- [0.2, 0.4, 0.6, 0.75, 0.85, 0.9, 0.85, 0.75, 0.6, 0.4, 0.2, 0.1]
- [0.0] * 5, index, )
The availability of charging - i.e. only when parked at office - is constrained as follows:
In [6]:
Copied!
charger_p_max_pu = pd.Series(0, index=index)
charger_p_max_pu["2016-01-01 09:00":"2016-01-01 16:00"] = 1charger_p_max_pu = pd.Series(0, index=index) charger_p_max_pu["2016-01-01 09:00":"2016-01-01 16:00"] = 1
Together, this gives:
In [7]:
Copied!
df = pd.concat({"BEV": bev_usage, "PV": pv_pu, "Charger": charger_p_max_pu}, axis=1)
df.plot.area(subplots=True);df = pd.concat({"BEV": bev_usage, "PV": pv_pu, "Charger": charger_p_max_pu}, axis=1) df.plot.area(subplots=True);

Now initialise the network and add the relevant components. Then optimise:
In [8]:
Copied!
n = pypsa.Network()
n.set_snapshots(index)
n.add("Bus", "place of work")
n.add("Bus", "car battery")
n.add(
"Generator",
"PV panel",
bus="place of work",
p_nom_extendable=True,
p_max_pu=pv_pu,
capital_cost=1000, # dummy cost value
)
n.add("Load", "driving", bus="car battery", p_set=bev_usage)
n.add(
"Link",
"charger",
bus0="place of work",
bus1="car battery",
p_nom=120,
p_max_pu=charger_p_max_pu,
efficiency=0.9,
)
n.add("Store", "battery", bus="car battery", e_cyclic=True, e_nom=100);n = pypsa.Network() n.set_snapshots(index) n.add("Bus", "place of work") n.add("Bus", "car battery") n.add( "Generator", "PV panel", bus="place of work", p_nom_extendable=True, p_max_pu=pv_pu, capital_cost=1000, # dummy cost value ) n.add("Load", "driving", bus="car battery", p_set=bev_usage) n.add( "Link", "charger", bus0="place of work", bus1="car battery", p_nom=120, p_max_pu=charger_p_max_pu, efficiency=0.9, ) n.add("Store", "battery", bus="car battery", e_cyclic=True, e_nom=100);
/tmp/ipykernel_2686/1011949240.py:1: PyPSA2Warning: pandas reads strings as `str` dtype since 3.0. PyPSA converts them back to object dtype on import, but keeps `str` from PyPSA 2.0 on. Set `pypsa.options.future.string_dtype` to True to opt in now or to False to keep the current behaviour.
n = pypsa.Network()In [9]:
Copied!
n.optimize()
print("Objective:", n.objective)n.optimize() print("Objective:", n.objective)
/tmp/ipykernel_2686/1147324918.py:1: PyPSA2Warning: From PyPSA 2.0 on, the objective leaves out the capital costs of existing capacity on extendable assets, which improves LP conditioning. Pass `include_objective_constant` to `n.optimize` to choose per call. Set `pypsa.options.future.exclude_objective_constant` to True to opt in now or to False to keep the current behaviour.
n.optimize()
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['place of work', 'car battery'], dtype='object', name='name')WARNING:pypsa.consistency:The following links have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['charger'], dtype='object', name='name')WARNING:pypsa.consistency:The following stores have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['battery'], dtype='object', name='name')INFO:linopy.model: Solve problem using Gurobi solverINFO:linopy.model:Solver options:
- log_to_console: FalseINFO:linopy.io: Writing time: 0.07sSet parameter WLSAccessIDSet parameter WLSSecretSet parameter LicenseID to value 2537914Academic license 2537914 - for non-commercial use only - registered to l.___@tu-berlin.deRead LP format model from file /tmp/linopy-problem-6tphm3tw.lpReading time = 0.00 secondsobj: 265 rows, 121 columns, 373 nonzerosSet parameter LogToConsole to value 0INFO:linopy.constants: Optimization successful:
Status: ok
Termination condition: optimal
Solution: 121 primals, 313 duals
Objective: 7.02e+03
Solver: gurobi
Runtime: 0.00s
Dual bound: 7.02e+03
Solver model: available
Solver message: 2INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-ext-p-lower, Generator-ext-p-upper, Link-fix-p-lower, Link-fix-p-upper, Store-fix-e-lower, Store-fix-e-upper, Store-fix-p-lower, Store-fix-p-upper, Store-fix-p_store-lower, Store-fix-p_store-upper, Store-energy_balance were not assigned to the network.Objective: 7017.543859649121The optimal panel size in kW is:
In [10]:
Copied!
n.generators.p_nom_opt["PV panel"]n.generators.p_nom_opt["PV panel"]
Out[10]:
np.float64(7.0175438596491215)In [11]:
Copied!
n.generators_t.p.plot.area()n.generators_t.p.plot.area()
Out[11]:
<Axes: xlabel='snapshot'>
The battery operation is optimised to follow:
In [12]:
Copied!
df = pd.DataFrame({attr: n.stores_t[attr]["battery"] for attr in ["p", "e"]})
df.plot(grid=True, ylim=(-10, 40))
plt.legend(labels=["Energy output", "State of charge"])df = pd.DataFrame({attr: n.stores_t[attr]["battery"] for attr in ["p", "e"]}) df.plot(grid=True, ylim=(-10, 40)) plt.legend(labels=["Energy output", "State of charge"])
Out[12]:
<matplotlib.legend.Legend at 0x717b94110050>
The losses in kWh per pay are:
In [13]:
Copied!
(n.generators_t.p.loc[:, "PV panel"].sum() - n.loads_t.p.loc[:, "driving"].sum())(n.generators_t.p.loc[:, "PV panel"].sum() - n.loads_t.p.loc[:, "driving"].sum())
Out[13]:
np.float64(3.999999999999986)In [14]:
Copied!
n.links_t.p0.plot.area()n.links_t.p0.plot.area()
Out[14]:
<Axes: xlabel='snapshot'>
2026-08-05
2020-02-28