> ## Documentation Index
> Fetch the complete documentation index at: https://code.dcycle.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Step 2 - Calculate Scope 1 Emissions

> Learn how to calculate direct emissions from stationary combustion, mobile combustion, process emissions, and fugitive emissions

## Understanding Scope 1 Emissions

**Scope 1 emissions** are direct greenhouse gas emissions from sources owned or controlled by your organization. According to the [GHG Protocol Corporate Standard](https://ghgprotocol.org/corporate-standard), these include:

* **Stationary combustion**: Burning fuels in boilers, furnaces, heaters, and other fixed equipment
* **Mobile combustion**: Burning fuels in company-owned or controlled vehicles
* **Process emissions**: Emissions from industrial processes (e.g., chemical reactions)
* **Fugitive emissions**: Intentional or unintentional releases (e.g., refrigerant leaks, CH₄ from wastewater treatment)

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                           SCOPE 1: Direct Emissions                         │
├─────────────────────┬─────────────────────┬─────────────────────────────────┤
│  Stationary         │  Mobile             │  Process & Fugitive             │
│  Combustion         │  Combustion         │  Emissions                      │
├─────────────────────┼─────────────────────┼─────────────────────────────────┤
│  • Boilers          │  • Company cars     │  • Industrial processes         │
│  • Furnaces         │  • Trucks           │  • Refrigerant leaks            │
│  • Generators       │  • Forklifts        │  • Wastewater treatment CH₄     │
│  • Heaters          │  • Company fleet    │  • Natural gas leaks            │
└─────────────────────┴─────────────────────┴─────────────────────────────────┘
```

<Note>
  **GHG Protocol Calculation Formula**

  For most Scope 1 sources, emissions are calculated using:

  **CO₂e = Activity Data × Emission Factor × GWP**

  Where:

  * **Activity Data**: Quantity of fuel consumed (liters, kg, m³, kWh)
  * **Emission Factor**: kg CO₂, CH₄, or N₂O per unit of fuel
  * **GWP**: Global Warming Potential to convert to CO₂ equivalent
</Note>

## Prerequisites

Before starting, ensure you have:

* Dcycle API credentials ([get them here](/docs/quickstart#step-1-get-your-api-key))
* At least one **facility** configured in your organization
* Access to your facility data: fuel consumption records, stationary combustion equipment details, and fleet information

<Tip>
  **Using the Dcycle App?**

  You can also manage your carbon footprint through our web interface:

  * [Create facilities](https://app.dcycle.io) - Set up your emission sources
  * [Upload invoices](https://app.dcycle.io) - Track fuel consumption
  * [Manage vehicles](https://app.dcycle.io) - Fleet management and consumption tracking
</Tip>

## Calculating Stationary Combustion

Stationary combustion emissions come from burning fuels in fixed equipment at your facilities. In Dcycle, these are tracked through **invoices** linked to **facility fuels**.

### Emission Sources Covered

| Source Type               | Invoice Type     | Examples                                                |
| ------------------------- | ---------------- | ------------------------------------------------------- |
| **Combustion (heat)**     | `heat`           | Natural gas boilers, diesel generators, propane heaters |
| **Recharges**             | `recharge`       | Refrigerant refills, fire suppression systems           |
| **Process emissions**     | `process`        | Industrial furnaces, VOCs                               |
| **Waste water treatment** | Special endpoint | CH₄ and N₂O from wastewater facilities                  |

### Calculation Methods by Country

Dcycle automatically applies the appropriate calculation methodology based on your facility's country:

<Tabs>
  <Tab title="Spain (MITECO)">
    For facilities located in **Spain**, Dcycle uses emission factors from **MITECO** (Ministerio para la Transición Ecológica y el Reto Demográfico).

    ```
    Facility (ES) → Invoice → MITECO Emission Factors → CO₂e
          ↓              ↓                ↓                ↓
      Country: ES    Fuel type     Spanish-specific    Compliant with
                     + quantity    factors by year     Spanish regulations
    ```

    **Key characteristics:**

    * Emission factors specific to Spain, updated annually
    * Fuel types mapped to MITECO categories (e.g., `natural_gas`, `gas_oil_b`, `lpg`)
    * Required for Spanish regulatory compliance (ISO 14064, EINF)
    * Includes factors for CO₂, CH₄, and N₂O

    <Tip>
      Access MITECO emission factors [here](https://share.google/W1lMiBNVV6qWyZxA5).
    </Tip>

    <AccordionGroup>
      <Accordion title="Emission Factor Sources - Spain (MITECO)">
        For Spanish facilities, Dcycle uses emission factors from:

        * **MITECO** (Ministerio para la Transición Ecológica y el Reto Demográfico)
        * Updated annually with Spanish-specific factors
        * Source: [Factores de emisión](https://share.google/W1lMiBNVV6qWyZxA5)

        Factors are automatically selected based on:

        * Fuel type (mapped to MITECO categories)
        * Unit of measurement
        * Invoice year
      </Accordion>

      <Accordion title="Calculation Details - Spain (MITECO)">
        For Spanish facilities, stationary combustion emissions are calculated as:

        **CO₂e = Fuel Quantity × (EF\_CO₂ × GWP\_CO₂ + EF\_CH₄ × GWP\_CH₄ + EF\_N₂O × GWP\_N₂O)**

        Where:

        * **Fuel Quantity**: Amount consumed (liters, m³, kg, kWh)
        * **EF\_XXX**: MITECO emission factor for the specific GHG gas (CO₂, CH₄, N₂O) and fuel, unit, and year
        * **GWP\_XXX**: Global Warming Potential for the specific GHG gas (CO₂, CH₄, N₂O) (IPCC AR6 GWP values)

        **Example (Natural Gas):**

        ```
        5,000 KWH × (0.182 kg CO₂/KWH x 1 + 0.000016 kg CH₄/KWH x 27.9 + 0.000000 kg N₂O/KWH x 273) = 912.23 kg CO₂e
        ```
      </Accordion>
    </AccordionGroup>
  </Tab>

  <Tab title="Other Countries (GHG Protocol)">
    For facilities in **any other country**, Dcycle uses emission factors from the [**IPCC/GHG Protocol** database](https://ghgprotocol.org/calculation-tools-and-guidance).

    ```
    Facility (non-ES) → Invoice → IPCC Emission Factors → CO₂e
          ↓                 ↓                ↓                ↓
      Country: XX       Fuel type     Global default      GHG Protocol
                        + quantity    factors (IPCC)      compliant
    ```

    **Key characteristics:**

    * IPCC-based emission factors (globally recognized)
    * Fuel types follow GHG Protocol naming conventions
    * Compatible with international reporting standards
    * Includes Net Calorific Value (NCV) calculations

    <Tip>
      Access GHG Protocol emission factors [here](https://ghgprotocol.org/sites/default/files/2024-10/Stationary_combustion_tool_Version4-2.xlsx).
    </Tip>

    <AccordionGroup>
      <Accordion title="Emission Factor Sources - Other Countries (GHG Protocol)">
        For non-Spanish facilities, Dcycle uses emission factors from:

        * **IPCC** (Intergovernmental Panel on Climate Change)
        * **GHG Protocol** Stationary Combustion Tool
        * Source: [GHG Protocol Calculation Tools](https://ghgprotocol.org/sites/default/files/2024-10/Stationary_combustion_tool_Version4-2.xlsx)

        Factors are automatically selected based on:

        * Fuel type (GHG Protocol naming conventions)
        * Net Calorific Value (NCV) of the fuel
        * Country-specific adjustments where available
      </Accordion>

      <Accordion title="Calculation Details - Other Countries (GHG Protocol)">
        For non-Spanish facilities, stationary combustion emissions follow the GHG Protocol methodology:

        **CO₂e = Fuel Quantity × Density × NCV × EF\_IPCC × GWP**

        Where:

        * **Fuel Quantity**: Amount consumed (converted to mass in Gg)
        * **Density**: Density of the fuel
        * **NCV**: Net Calorific Value (TJ/Gg) - energy content per unit mass
        * **EF\_IPCC**: IPCC emission factor (kg gas/TJ)
        * **GWP\_XXX**: Global Warming Potential for the specific GHG gas (CO₂, CH₄, N₂O) (IPCC AR6 GWP values)

        The calculation process:

        1. Convert fuel quantity to energy (TJ) using NCV
        2. Apply emission factors for CO₂, CH₄, and N₂O
        3. Convert each gas to CO₂e using GWP factors
        4. Sum all gases for total CO₂e

        **Example (Natural Gas):**

        ```
        Step 1: 5,000 m³ × 0.7 kg/m³ (density) *0.001 (to convert to Gg)→ mass in Gg
        Step 2: mass × 48.0 TJ/Gg (NCV) → energy in TJ
        Step 3: energy × 56,100 kg CO₂/TJ → CO₂ emissions
        Step 4: Add CH₄ and N₂O contributions and convert to CO₂e using GWP factors → total CO₂e
        ```
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

<Note>
  **Automatic Method Selection**

  You don't need to specify which calculation method to use. Dcycle automatically detects the facility's country and applies the correct emission factors:

  * `country: "ES"` → MITECO factors
  * Any other country → GHG Protocol/IPCC factors
</Note>

What you'll track:

```
Facility Setup → Invoice Creation → Emissions Calculation
      ↓                ↓                      ↓
  Facility config   Fuel consumption    CO2e per invoice
  (with country)    records (invoices)  (method auto-selected)
```

### Data Flow

<Steps>
  <Step title="Set Up Facilities">
    Configure your facilities and link them to fuel types
  </Step>

  <Step title="Automatic Method Selection">
    Dcycle detects the facility country and applies MITECO (Spain) or GHG Protocol (other) emission factors
  </Step>

  <Step title="Create Invoices">
    Record fuel consumption, recharges, or process emissions via invoices
  </Step>

  <Step title="Calculate Emissions">
    CO₂e emissions are calculated using the appropriate country-specific factors
  </Step>

  <Step title="Generate Reports">
    View emissions by facility, fuel type, or period
  </Step>
</Steps>

### Step 2.1: Create a Fuel Consumption Invoice

<Accordion title="📋 Data Map: Fuel Consumption Invoice">
  | Field                       | Type   | Required | Description                 | Example               |
  | --------------------------- | ------ | -------- | --------------------------- | --------------------- |
  | `type`                      | string | ✅        | Invoice type                | `"heat"`              |
  | `facility_id`               | UUID   | ✅        | Target facility             | `"abc-123-..."`       |
  | `facility_fuel_id`          | UUID   | ✅        | Fuel type for this facility | `"def-456-..."`       |
  | `base_quantity`             | number | ✅        | Amount of fuel consumed     | `5000`                |
  | `unit_id`                   | UUID   | ✅        | Unit of measurement         | `"2a09be22-..."` (m³) |
  | `start_date`                | date   | ✅        | Consumption period start    | `"2024-01-01"`        |
  | `end_date`                  | date   | ✅        | Consumption period end      | `"2024-01-31"`        |
  | `invoice_id`                | string | ✅        | Your internal reference     | `"INV-2024-001"`      |
  | `uploaded_by`               | UUID   | ✅        | User uploading the data     | `"user-uuid"`         |
  | `custom_emission_factor_id` | UUID   | ❌        | Custom EF override          | `"custom-ef-uuid"`    |

  **Where to get this data:**

  * **Facility ID**: From Step 1 (company structure setup) or `GET /api/v1/facilities`
  * **Facility Fuel ID**: `GET /api/v1/facility_fuels/{facility_id}`
  * **Unit ID**: `GET /api/v1/units`
  * **Quantity**: From utility bills, fuel purchase records, or meter readings
</Accordion>

Record fuel consumption at a facility by creating an invoice:

<CodeGroup>
  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import requests
  import os
  from datetime import datetime, timedelta

  headers = {
      "Authorization": f"Bearer {os.getenv('DCYCLE_API_KEY')}",
      "Content-Type": "application/json",
      "x-organization-id": os.getenv("DCYCLE_ORG_ID"),
      "x-user-id": os.getenv("DCYCLE_USER_ID"),
  }

  # Get facility fuels for your facility
  facility_id = "your-facility-uuid"
  facility_fuels = requests.get(
      f"https://api.dcycle.io/v1/facility_fuels/{facility_id}",
      headers=headers,
  ).json()

  # Find the natural gas fuel option
  natural_gas_fuel = next(
      (ff for ff in facility_fuels if "natural gas" in ff["fuel_name"].lower()),
      None
  )

  # Create invoice for natural gas consumption
  invoice_data = {
      "type": "heat",  # Stationary combustion
      "facility_percentages": [
          {
              "organization_id": os.getenv("DCYCLE_ORG_ID"),
              "facility_id": facility_id,
              "percentage": 1.0,  # 100% to this facility
          }
      ],
      "base_quantity": 5000,  # 5,000 m³ of natural gas
      "unit_id": "2a09be22-a6e2-4317-a680-94aaa1048765",  # m³
      "facility_fuel_id": natural_gas_fuel["id"],
      "start_date": "2024-01-01",
      "end_date": "2024-01-31",
      "invoice_id": "INV-2024-001",
      "uploaded_by": os.getenv("DCYCLE_USER_ID"),
      # Optional: apply a custom emission factor
      # "custom_emission_factor_id": "your-custom-ef-id",
  }

  response = requests.post(
      "https://api.dcycle.io/v1/invoices",
      headers=headers,
      json=invoice_data,
  )

  invoice = response.json()
  print(f"✅ Invoice created: {invoice['id']}")
  print(f"   Quantity: {invoice['quantity']} m³")
  print(f"   CO₂e: {invoice.get('co2e', 'Calculating...')} kg")
  ```

  <Tip>
    **Use Custom Emission Factors**

    If you want to use custom emission factors, include `custom_emission_factor_id` in the invoice payload. See [Custom Emission Factors](https://code.dcycle.io/guides/advanced/custom-emission-factors) for how to create and apply them.
  </Tip>

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const axios = require('axios');

  const headers = {
    Authorization: `Bearer ${process.env.DCYCLE_API_KEY}`,
    'Content-Type': 'application/json',
    'x-organization-id': process.env.DCYCLE_ORG_ID,
    'x-user-id': process.env.DCYCLE_USER_ID,
  };

  // Get facility fuels for your facility
  const facilityId = 'your-facility-uuid';
  const facilityFuelsResponse = await axios.get(
    `https://api.dcycle.io/v1/facility_fuels/${facilityId}`,
    { headers }
  );
  const facilityFuels = facilityFuelsResponse.data;

  // Find the natural gas fuel option
  const naturalGasFuel = facilityFuels.find(
    ff => ff.fuel_name.toLowerCase().includes('natural gas')
  );

  // Create invoice for natural gas consumption
  const invoiceData = {
    type: 'heat', // Stationary combustion
    facility_percentages: [
      {
        organization_id: process.env.DCYCLE_ORG_ID,
        facility_id: facilityId,
        percentage: 1.0, // 100% to this facility
      },
    ],
    base_quantity: 5000, // 5,000 m³ of natural gas
    unit_id: '2a09be22-a6e2-4317-a680-94aaa1048765', // m³
    facility_fuel_id: naturalGasFuel.id,
    start_date: '2024-01-01',
    end_date: '2024-01-31',
    invoice_id: 'INV-2024-001',
    uploaded_by: process.env.DCYCLE_USER_ID,
  };

  const response = await axios.post(
    'https://api.dcycle.io/v1/invoices',
    invoiceData,
    { headers }
  );

  const invoice = response.data;
  console.log(`✅ Invoice created: ${invoice.id}`);
  console.log(`   Quantity: ${invoice.quantity} m³`);
  console.log(`   CO₂e: ${invoice.co2e || 'Calculating...'} kg`);
  ```
</CodeGroup>

### Step 2.2: Track Refrigerant Recharges

<Accordion title="📋 Data Map: Refrigerant Recharges">
  | Field                       | Type   | Required | Description                             | Example               |
  | --------------------------- | ------ | -------- | --------------------------------------- | --------------------- |
  | `type`                      | string | ✅        | Invoice type                            | `"recharge"`          |
  | `facility_id`               | UUID   | ✅        | Facility with the equipment             | `"abc-123-..."`       |
  | `facility_fuel_id`          | UUID   | ✅        | Refrigerant type (R-410A, R-134a, etc.) | `"ref-456-..."`       |
  | `base_quantity`             | number | ✅        | Amount recharged (= amount leaked)      | `15`                  |
  | `unit_id`                   | UUID   | ✅        | Unit (typically kg)                     | `"61743a63-..."` (kg) |
  | `start_date`                | date   | ✅        | Recharge date                           | `"2024-03-15"`        |
  | `end_date`                  | date   | ✅        | Recharge date (same as start)           | `"2024-03-15"`        |
  | `invoice_id`                | string | ✅        | Service invoice reference               | `"RECHARGE-2024-001"` |
  | `uploaded_by`               | UUID   | ✅        | User uploading                          | `"user-uuid"`         |
  | `custom_emission_factor_id` | UUID   | ❌        | Custom EF override                      | `"custom-ef-uuid"`    |

  **Where to get this data:**

  * **Refrigerant type**: From HVAC maintenance records or service invoices
  * **Quantity**: From recharge receipts (amount refilled = amount leaked)
  * **Equipment register**: Maintain a list of all cooling equipment and their refrigerant types
</Accordion>

Refrigerant leaks (HFCs, PFCs) are **fugitive emissions** and often significant for organizations with cooling systems:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Create invoice for refrigerant recharge (fugitive emissions)
recharge_data = {
    "type": "recharge",
    "facility_percentages": [
        {
            "organization_id": os.getenv("DCYCLE_ORG_ID"),
            "facility_id": facility_id,
            "percentage": 1.0,
        }
    ],
    "base_quantity": 15,  # 15 kg of R-410A refrigerant
    "unit_id": "61743a63-ff70-459c-9567-5eee8f7dfd5c",  # kg
    "facility_fuel_id": refrigerant_fuel_id,  # R-410A fuel ID
    "start_date": "2024-03-15",
    "end_date": "2024-03-15",
    "invoice_id": "RECHARGE-2024-001",
    "uploaded_by": os.getenv("DCYCLE_USER_ID"),
    # "custom_emission_factor_id": "your-custom-ef-id",
}

response = requests.post(
    "https://api.dcycle.io/v1/invoices",
    headers=headers,
    json=recharge_data,
)

print(f"✅ Recharge recorded: {response.json()['id']}")
print(f"   R-410A has GWP of ~2,088 - high impact!")
```

<Tip>
  **Custom Factors for Recharges**

  Use `custom_emission_factor_id` when you want to apply custom emissions data for a refrigerant. Learn how in the [Custom Emission Factors guide](https://code.dcycle.io/guides/advanced/custom-emission-factors).
</Tip>

<Warning>
  **High-GWP Refrigerants**

  Some refrigerants have extremely high Global Warming Potentials:

  * **R-410A**: GWP = 2,088
  * **R-404A**: GWP = 3,922
  * **R-134a**: GWP = 1,430

  Even small leaks can represent a significant portion of your Scope 1 footprint. Track all recharges carefully.
</Warning>

### Step 2.3: Track Process Emissions

<Accordion title="📋 Data Map: Process Emissions">
  | Field                       | Type   | Required | Description                | Example               |
  | --------------------------- | ------ | -------- | -------------------------- | --------------------- |
  | `type`                      | string | ✅        | Invoice type               | `"process"`           |
  | `facility_id`               | UUID   | ✅        | Facility with the process  | `"abc-123-..."`       |
  | `facility_fuel_id`          | UUID   | ✅        | Process source/fuel type   | `"proc-456-..."`      |
  | `base_quantity`             | number | ✅        | Emission quantity          | `250`                 |
  | `unit_id`                   | UUID   | ✅        | Unit (typically kg)        | `"61743a63-..."` (kg) |
  | `start_date`                | date   | ✅        | Period start               | `"2024-01-01"`        |
  | `end_date`                  | date   | ✅        | Period end                 | `"2024-03-31"`        |
  | `invoice_id`                | string | ✅        | Internal reference         | `"PROCESS-2024-Q1"`   |
  | `uploaded_by`               | UUID   | ✅        | User uploading             | `"user-uuid"`         |
  | `custom_emission_factor_id` | UUID   | ⚠️       | Custom EF (often required) | `"custom-ef-uuid"`    |

  **Where to get this data:**

  * **Process type**: From environmental permits, process flow diagrams
  * **Quantity**: From production records, mass balance calculations, or direct measurements
  * **Custom EF**: Industry-specific factors from permits, sector guidelines, or IPCC
</Accordion>

**Process emissions** arise from industrial activities where the emissions are not from fuel combustion, but from chemical or physical transformations. Common examples include:

* **Chemical manufacturing**: CO₂ from calcination (e.g., cement, lime production)
* **Metal production**: CO₂ from reduction processes
* **Volatile organic compounds (VOCs)**: Emissions from solvents, coatings, and industrial cleaning
* **Industrial furnaces**: Non-combustion emissions from high-temperature processes

Process emissions are tracked as invoices with `type: "process"`:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Create invoice for process emissions (e.g., VOC from painting operations)
process_data = {
    "type": "process",
    "facility_percentages": [
        {
            "organization_id": os.getenv("DCYCLE_ORG_ID"),
            "facility_id": facility_id,
            "percentage": 1.0,
        }
    ],
    "base_quantity": 250,  # 250 kg of VOC emissions
    "unit_id": "61743a63-ff70-459c-9567-5eee8f7dfd5c",  # kg
    "facility_fuel_id": process_fuel_id,  # Fuel/source associated with the process
    "start_date": "2024-01-01",
    "end_date": "2024-03-31",
    "invoice_id": "PROCESS-2024-Q1",
    "uploaded_by": os.getenv("DCYCLE_USER_ID"),
    # "custom_emission_factor_id": "your-custom-ef-id",
}

response = requests.post(
    "https://api.dcycle.io/v1/invoices",
    headers=headers,
    json=process_data,
)

print(f"✅ Process emissions recorded: {response.json()['id']}")
```

<Tip>
  **Use Custom Emission Factors for Process Emissions**

  Process emissions often require facility-specific or industry-specific emission factors. Use `custom_emission_factor_id` to apply factors from your environmental permits or industry calculations. See [Custom Emission Factors](https://code.dcycle.io/guides/advanced/custom-emission-factors) for setup instructions.
</Tip>

<Note>
  **When to Use Process vs. Heat Invoices**

  * Use `type: "heat"` when emissions come from **burning fuel** (combustion)
  * Use `type: "process"` when emissions come from **chemical/physical transformations** not related to combustion

  Example: A cement plant would use `heat` for fuel burned in kilns, but `process` for CO₂ released from limestone calcination.
</Note>

### Step 2.4: Track Waste Water Treatment Emissions

<Accordion title="📋 Data Map: Waste Water Treatment">
  | Field                       | Type   | Required | Description                    | Example            |
  | --------------------------- | ------ | -------- | ------------------------------ | ------------------ |
  | `facility_id`               | UUID   | ✅        | WWT facility                   | `"wwt-123-..."`    |
  | `name`                      | string | ✅        | Record identifier              | `"WWT-2024-01-01"` |
  | `measurement_date`          | date   | ✅        | Measurement date               | `"2024-01-01"`     |
  | `m3_water_in`               | number | ✅        | Daily influent volume (m³)     | `10000`            |
  | `m3_water_out`              | number | ✅        | Daily effluent volume (m³)     | `9500`             |
  | `kg_bod_per_m3_wwt_line`    | number | ✅        | BOD concentration in treatment | `0.25`             |
  | `kg_n_per_m3_wwt_line`      | number | ✅        | Nitrogen concentration         | `0.04`             |
  | `kg_sludge`                 | number | ✅        | Sludge produced (kg)           | `500`              |
  | `kg_bod_per_kg_sludge_line` | number | ✅        | BOD in sludge                  | `0.6`              |
  | `kg_bod_per_m3_wwd_line`    | number | ✅        | BOD in discharge               | `0.02`             |
  | `kg_n_per_m3_wwd_line`      | number | ✅        | Nitrogen in discharge          | `0.01`             |
  | `m3_biogas_engine`          | number | ❌        | Biogas to engine (m³)          | `200`              |
  | `m3_biogas_flare`           | number | ❌        | Biogas flared (m³)             | `50`               |
  | `m3_biogas_boiler`          | number | ❌        | Biogas to boiler (m³)          | `100`              |
  | `st`                        | number | ❌        | Solids content                 | `0.25`             |
  | `methane`                   | number | ❌        | Methane content in biogas      | `0.65`             |

  **Where to get this data:**

  * **Flow data**: SCADA systems, flow meters at inlet/outlet
  * **BOD/Nitrogen**: Laboratory analyses, online sensors
  * **Sludge**: Weighing systems, sludge removal records
  * **Biogas**: Gas meters on digesters, engines, flares
</Accordion>

Wastewater treatment facilities generate **CH₄ (methane)** and **N₂O (nitrous oxide)** emissions through biological processes. Dcycle provides a specialized bulk upload endpoint:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import requests
import os
from datetime import date, timedelta

headers = {
    "Authorization": f"Bearer {os.getenv('DCYCLE_API_KEY')}",
    "Content-Type": "application/json",
    "x-organization-id": os.getenv("DCYCLE_ORG_ID"),
    "x-user-id": os.getenv("DCYCLE_USER_ID"),
}

# Prepare daily waste water treatment data
daily_data = []
base_date = date(2024, 1, 1)

for i in range(31):  # January 2024
    measurement_date = base_date + timedelta(days=i)
    daily_data.append({
        "name": f"WWT-{measurement_date.isoformat()}",
        "measurement_date": measurement_date.isoformat(),
        "m3_water_in": 10000 + (i * 100),  # Daily influent (m³)
        "m3_water_out": 9500 + (i * 95),   # Daily effluent (m³)
        "kg_bod_per_m3_wwt_line": 0.25,    # BOD concentration
        "kg_n_per_m3_wwt_line": 0.04,      # Nitrogen concentration
        "kg_sludge": 500 + (i * 10),       # Sludge produced (kg)
        "kg_bod_per_kg_sludge_line": 0.6,
        "kg_bod_per_m3_wwd_line": 0.02,
        "kg_n_per_m3_wwd_line": 0.01,
        "m3_biogas_engine": 200,           # Biogas to engine (m³)
        "m3_biogas_flare": 50,             # Biogas flared (m³)
        "m3_biogas_boiler": 100,           # Biogas to boiler (m³)
        "st": 0.25,                        # Solids content
        "methane": 0.65,                   # Methane content in biogas
    })

wwt_data = {
    "facility_id": "your-wwt-facility-uuid",
    "daily_waste_water_treatment_data": daily_data,
}

response = requests.post(
    "https://api.dcycle.io/v1/bulk/waste_water_treatments",
    headers=headers,
    json=wwt_data,
)

wwt_records = response.json()
print(f"✅ Created {len(wwt_records)} waste water treatment records")
print(f"   Emissions calculated from CH₄ and N₂O")
```

<Note>
  **Waste Water Treatment Calculations**

  Dcycle calculates emissions from:

  * **CH₄ from anaerobic treatment**: Based on BOD removal and MCF (Methane Correction Factor)
  * **N₂O from biological processes**: Based on nitrogen load and EF
  * **Biogas combustion**: CO₂ from burning recovered biogas (often biogenic)

  The endpoint handles data imputation for missing values using moving averages.
</Note>

## Calculating Mobile Combustion

Mobile combustion emissions come from company-owned or controlled vehicles. In Dcycle, these are tracked through **vehicles** and **vehicle consumptions**.

<Tip>
  **Prefer using the Dcycle App?**

  If you want to manage your fleet through our web interface instead of the API, check out these guides:

  * [Create vehicles automatically](https://scribehow.com/shared/How_to_create_vehicles_automatically__hxPg44MXTU2TAijQ27hU9g) ([ES](https://scribehow.com/shared/Como_crear_vehiculos_automaticamente__2IIdCktxRz2PdA7RwyCHkg))
  * [Create vehicles manually](https://scribehow.com/shared/Create_a_Passenger_Car_Rental_in_Dcycle_App__7XDk79piShC-z5hI4vG1Mg) ([ES](https://scribehow.com/shared/Como_crear_vehiculos_propios_o_alquilados__zgj1fnDiQQa8CufLTvS6Vw))
  * [Create agricultural vehicles](https://scribehow.com/shared/How_to_create_an_agricultural_or_industrial_vehicle_and_add_its_consumptions__l7kVW3XNQQ6PTA9jfcuuHA) ([ES](https://scribehow.com/shared/Guia_Como_crear_un_vehiculo_tipo_agricola_o_industrial_y_agregar_sus_consumos__HbnfPmuBR_qgHteLkh9DFA))
</Tip>

What you'll track:

```
Vehicle Registration → Fuel Consumption → Emissions Calculation
      ↓                      ↓                    ↓
  Fleet database      Monthly records        CO2e per vehicle
```

<AccordionGroup>
  <Accordion title="Supported Units for Vehicle Consumption">
    *This part of the documentation is still in progress.*
  </Accordion>

  <Accordion title="Emission Factor Sources">
    Dcycle uses country-specific emission factors from:

    * **DEFRA** (UK Department for Environment, Food & Rural Affairs) *Comming soon!*
    * **MITECO** (Spanish Ministry for Ecological Transition)

    Factors are automatically selected based on vehicle country and fuel type.
  </Accordion>

  <Accordion title="Calculation Details">
    Mobile combustion emissions are calculated as:

    **CO₂e = Fuel Quantity × (EF\_CO₂ × GWP\_CO₂ + EF\_CH₄ × GWP\_CH₄ + EF\_N₂O × GWP\_N₂O)**

    Where emission factors (EF) are specific to:

    * Fuel type (diesel, petrol, LPG, etc.)
    * Vehicle type (passenger car, light truck, heavy truck)
    * Country (regional emission factors)
    * Unit (liters, kilometers, etc.)
  </Accordion>
</AccordionGroup>

### Data Flow

<Steps>
  <Step title="Register Vehicles">
    Add all company vehicles to Dcycle
  </Step>

  <Step title="Track Fuel Consumption">
    Upload fuel purchases (manually or from fuel cards)
  </Step>

  <Step title="Calculate Emissions">
    Dcycle automatically calculates CO2e emissions
  </Step>

  <Step title="Generate Reports">
    View emissions by vehicle, driver, or period
  </Step>
</Steps>

### Step 2.5: Create a Vehicle

<Accordion title="📋 Data Map: Vehicle Registration">
  | Field             | Type   | Required | Description                | Example                     |
  | ----------------- | ------ | -------- | -------------------------- | --------------------------- |
  | `name`            | string | ✅        | Vehicle identifier         | `"Delivery Truck 01"`       |
  | `type`            | string | ✅        | Vehicle category           | `"truck"`, `"car"`, `"van"` |
  | `license_plate`   | string | ✅        | License plate number       | `"1234ABC"`                 |
  | `country`         | string | ✅        | Registration country (ISO) | `"ES"`, `"FR"`, `"PT"`      |
  | `vehicle_fuel_id` | UUID   | ✅        | Fuel type                  | `"diesel-uuid"`             |
  | `ownership`       | string | ✅        | Ownership type             | `"owned"` or `"rented"`     |

  **Where to get this data:**

  * **Vehicle details**: Fleet management system, vehicle registration documents
  * **Fuel type**: Vehicle specifications, fuel cards
  * **Vehicle fuel ID**: `GET /api/v1/vehicle_fuels`
  * **Vehicle type**: `GET /api/v1/unknown_vehicles` (for generic vehicle types)
</Accordion>

First, register your company vehicle:

<Info>
  **Using the Dcycle App?**

  You can also register vehicles through our web interface:

  * For known vehicles: [Create vehicles automatically](https://scribehow.com/shared/How_to_create_vehicles_automatically__hxPg44MXTU2TAijQ27hU9g) by entering license plate (works in Spain, Portugal, France)
  * For any vehicle: [Create vehicles manually](https://scribehow.com/shared/Create_a_Passenger_Car_Rental_in_Dcycle_App__7XDk79piShC-z5hI4vG1Mg) with custom specifications
</Info>

<CodeGroup>
  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import requests
  import os

  headers = {
      "Authorization": f"Bearer {os.getenv('DCYCLE_API_KEY')}",
      "Content-Type": "application/json",
      "x-organization-id": os.getenv("DCYCLE_ORG_ID"),
      "x-user-id": os.getenv("DCYCLE_USER_ID"),
  }

  # Get available vehicle fuels
  vehicle_fuels = requests.get(
      "https://api.dcycle.io/v1/vehicle_fuels",
      headers=headers,
  ).json()

  diesel_fuel = next(
      (vf for vf in vehicle_fuels["items"] if "diesel" in vf["name"].lower()),
      None
  )

  # Get vehicles (vehicle types)
  vehicle_types = requests.get(
      "https://api.dcycle.io/v1/unknown_vehicles",
      headers=headers,
  ).json()

  medium_truck = next(
      (
          vt
          for vt in vehicle_types["items"]
          if "medium" in vt["name"].lower() and "truck" in vt["name"].lower()
      ),
      None
  )

  # Create vehicle via bulk CSV upload (get presigned URL)
  bulk_upload = requests.post(
      "https://api.dcycle.io/v1/vehicles/bulk/csv",
      headers=headers,
      json={"file_name": "company_vehicles.csv"},
  ).json()

  print(f"✅ Upload URL generated: {bulk_upload['upload_url'][:50]}...")
  print(f"   Upload your CSV with columns:")
  print(f"   name, type, license_plate, country, vehicle_fuel_id, ownership, unknown_vehicle_id")
  ```

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const axios = require('axios');

  const headers = {
    Authorization: `Bearer ${process.env.DCYCLE_API_KEY}`,
    'Content-Type': 'application/json',
    'x-organization-id': process.env.DCYCLE_ORG_ID,
    'x-user-id': process.env.DCYCLE_USER_ID,
  };

  // Get available vehicle fuels
  const vehicleFuelsResponse = await axios.get(
    'https://api.dcycle.io/v1/vehicle_fuels',
    { headers }
  );
  const vehicleFuels = vehicleFuelsResponse.data;

  const dieselFuel = vehicleFuels.items.find(
    vf => vf.name.toLowerCase().includes('diesel')
  );

  // Get vehicles (vehicle types)
  const vehicleTypesResponse = await axios.get(
    'https://api.dcycle.io/v1/unknown_vehicles',
    { headers }
  );
  const vehicleTypes = vehicleTypesResponse.data;

  const mediumTruck = vehicleTypes.items.find(
    vt =>
      vt.name.toLowerCase().includes('medium') &&
      vt.name.toLowerCase().includes('truck')
  );

  // Create vehicle via bulk CSV upload (get presigned URL)
  const bulkUploadResponse = await axios.post(
    'https://api.dcycle.io/v1/vehicles/bulk/csv',
    { file_name: 'company_vehicles.csv' },
    { headers }
  );

  const bulkUpload = bulkUploadResponse.data;
  console.log(`✅ Upload URL generated: ${bulkUpload.upload_url.slice(0, 50)}...`);
  console.log('   Upload your CSV with columns:');
  console.log('   name, type, license_plate, country, vehicle_fuel_id, ownership, unknown_vehicle_id');
  ```
</CodeGroup>

### Step 2.6: Record Vehicle Fuel Consumption

<Accordion title="📋 Data Map: Vehicle Fuel Consumption">
  | Field                   | Type   | Required | Description              | Example          |
  | ----------------------- | ------ | -------- | ------------------------ | ---------------- |
  | `vehicle_license_plate` | string | ✅        | Vehicle identifier       | `"1234ABC"`      |
  | `start_date_recharge`   | date   | ✅        | Consumption period start | `"2024-01-01"`   |
  | `end_date_recharge`     | date   | ✅        | Consumption period end   | `"2024-01-31"`   |
  | `quantity`              | number | ✅        | Fuel amount              | `450`            |
  | `unit_measure`          | string | ✅        | Unit of measurement      | `"l"`, `"km"`    |
  | `organization_id`       | UUID   | ✅        | Organization identifier  | `"org-uuid"`     |
  | `description`           | string | ❌        | Optional note            | `"January fuel"` |

  **Supported units:**

  * **Volume**: `l` (liters) - for fuel purchases
  * **Distance**: `km` (kilometers) - when using average consumption

  **Where to get this data:**

  * **Fuel cards**: Automatic reports from fuel card providers
  * **Fuel receipts**: Manual collection of fuel purchase receipts
  * **Odometer readings**: For distance-based calculations
  * **Charging records**: For electric vehicles (charging station data)
</Accordion>

Once vehicles are created, track their fuel consumption:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Get presigned URL for bulk vehicle consumption upload
consumption_upload = requests.post(
    "https://api.dcycle.io/v1/vehicle_consumptions/bulk/csv",
    headers=headers,
    json={"file_name": "vehicle_consumptions_q1_2024.csv"},
).json()

print(f"✅ Upload URL generated for consumptions")
print(f"   CSV columns required:")
print(f"   description(optional), vehicle_license_plate, start_date_recharge,")
print(f"   end_date_recharge, quantity, unit_measure, organization_id")
```

### CSV Format for Vehicle Consumptions

```csv theme={"theme":{"light":"github-light","dark":"github-dark"}}
description(optional),vehicle_license_plate,start_date_recharge,end_date_recharge,quantity,unit_measure,organization_id
January fuel,1234ABC,2024-01-01,2024-01-31,450,l,your-org-uuid
February fuel,1234ABC,2024-02-01,2024-02-29,420,l,your-org-uuid
Q1 fuel,5678XYZ,2024-01-01,2024-03-31,1250,l,your-org-uuid
```

### Query Vehicle Consumptions

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Get vehicle consumptions for a specific vehicle
vehicle_id = "your-vehicle-uuid"

consumptions = requests.get(
    f"https://api.dcycle.io/v1/vehicle_consumptions/vehicle/{vehicle_id}",
    headers=headers,
    params={
        "page": 1,
        "size": 50,
        "start_date": 1704067200,  # 2024-01-01 timestamp
        "end_date": 1711929600,    # 2024-04-01 timestamp
    },
).json()

print(f"📊 Vehicle Consumptions:")
for consumption in consumptions["items"]:
    print(f"   {consumption['start_date']} - {consumption['end_date']}")
    print(f"   Quantity: {consumption['quantity']} {consumption['unit_name']}")
    print(f"   CO₂e: {consumption.get('co2e', 'N/A')} kg")
    print()
```

<Tip>
  **Best Practice: Track All Company Vehicles**

  For complete Scope 1 accounting:

  1. **Owned vehicles**: Full emissions count toward Scope 1
  2. **Leased vehicles (operational control)**: Include in Scope 1
  3. **Employee-owned vehicles for business**: May be Scope 3 (business travel)

  Use the `ownership` field (`owned` or `rented`) to distinguish.
</Tip>
