Post · 6 min read· pp. 39–48

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! diagram

ipynb
import matplotlib.pyplot as plt
import pandas as pd

import pypsa

import matplotlib.pyplot as plt import pandas as pd import pypsa

As time index, we use a 24 hour period.

In [3]:

Copied! diagram

ipynb
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! diagram

ipynb
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! diagram

ipynb
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! diagram

ipynb
charger_p_max_pu = pd.Series(0, index=index)
charger_p_max_pu["2016-01-01 09:00":"2016-01-01 16:00"] = 1

charger_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! diagram

ipynb
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);

No description has been provided for this image

Now initialise the network and add the relevant components. Then optimise:

In [8]:

Copied! diagram

ipynb
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);

text
/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! diagram

ipynb
n.optimize()
print("Objective:", n.objective)

n.optimize() print("Objective:", n.objective)

text
/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')
text
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')
text
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')
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.07s
text
Set parameter WLSAccessID
text
Set parameter WLSSecret
text
Set parameter LicenseID to value 2537914
text
Academic license 2537914 - for non-commercial use only - registered to l.___@tu-berlin.de
text
Read LP format model from file /tmp/linopy-problem-6tphm3tw.lp
text
Reading time = 0.00 seconds
text
obj: 265 rows, 121 columns, 373 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO: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: 2
text
INFO: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.
text
Objective: 7017.543859649121

The optimal panel size in kW is:

In [10]:

Copied! diagram

ipynb
n.generators.p_nom_opt["PV panel"]

n.generators.p_nom_opt["PV panel"]

Out[10]:

text
np.float64(7.0175438596491215)

In [11]:

Copied! diagram

ipynb
n.generators_t.p.plot.area()

n.generators_t.p.plot.area()

Out[11]:

text
<Axes: xlabel='snapshot'>

No description has been provided for this image

The battery operation is optimised to follow:

In [12]:

Copied! diagram

ipynb
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]:

text
<matplotlib.legend.Legend at 0x717b94110050>

No description has been provided for this image

The losses in kWh per pay are:

In [13]:

Copied! diagram

ipynb
(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]:

text
np.float64(3.999999999999986)

In [14]:

Copied! diagram

ipynb
n.links_t.p0.plot.area()

n.links_t.p0.plot.area()

Out[14]:

text
<Axes: xlabel='snapshot'>

No description has been provided for this image

diagram 2026-08-05

diagram 2020-02-28