
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/11_reblocking_calculated_attributes.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_auto_examples_11_reblocking_calculated_attributes.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_11_reblocking_calculated_attributes.py:


Reblocking with Calculated Aggregation Inputs
=============================================

Use schema-defined calculated attributes in reblocking configuration. In this
example ``tonnes`` and ``contained_metal`` are defined in Pandera ``df-eval``
metadata and materialized for downsampling.

.. GENERATED FROM PYTHON SOURCE LINES 9-27

.. code-block:: Python


    import tempfile
    from pathlib import Path

    import numpy as np

    from parq_blockmodel import ParquetBlockModel
    from parq_blockmodel.utils.demo_block_model import create_demo_blockmodel

    try:
        import df_eval  # noqa: F401
        from pandera import Column, DataFrameSchema
    except ImportError:
        print("Install parq-blockmodel[schema] to run this example.")
        raise SystemExit(0)

    # sphinx_gallery_thumbnail_path = "../docs/_static/branding/parq-blockmodel-gallery-thumbnail.svg"








.. GENERATED FROM PYTHON SOURCE LINES 28-29

Build a small demo model with persisted base attributes.

.. GENERATED FROM PYTHON SOURCE LINES 29-44

.. code-block:: Python


    temp_dir = Path(tempfile.gettempdir()) / "reblocking_calculated_example"
    temp_dir.mkdir(parents=True, exist_ok=True)

    df = create_demo_blockmodel(
        shape=(4, 4, 4),
        block_size=(10.0, 10.0, 5.0),
        corner=(0.0, 0.0, 0.0),
        index_type="world_centroids",
    )

    df["grade"] = np.linspace(0.2, 1.2, len(df))
    df["density"] = np.linspace(2.0, 3.0, len(df))









.. GENERATED FROM PYTHON SOURCE LINES 45-46

Define calculated attributes in schema metadata.

.. GENERATED FROM PYTHON SOURCE LINES 46-77

.. code-block:: Python


    schema = DataFrameSchema(
        columns={
            "grade": Column(float, coerce=True, nullable=True),
            "density": Column(float, coerce=True, nullable=True),
            "tonnes": Column(
                float,
                coerce=True,
                nullable=True,
                required=False,
                metadata={"df-eval": {"expr": "density * volume"}},
            ),
            "contained_metal": Column(
                float,
                coerce=True,
                nullable=True,
                required=False,
                metadata={"df-eval": {"expr": "tonnes * grade"}},
            ),
        },
        strict=False,
    )

    pbm = ParquetBlockModel.from_dataframe(
        df[["grade", "density"]],
        filename=temp_dir / "reblocking_calculated_inputs.parquet",
        schema=schema,
        overwrite=True,
    )









.. GENERATED FROM PYTHON SOURCE LINES 78-79

Downsample using calculated attributes as aggregation inputs.

.. GENERATED FROM PYTHON SOURCE LINES 79-90

.. code-block:: Python


    downsampled = pbm.downsample(
        new_block_size=(20.0, 20.0, 10.0),
        aggregation_config={
            "grade": {"method": "mean"},
            "contained_metal": {"method": "weighted_mean", "basis": "tonnes"},
        },
    )

    result = downsampled.read(columns=["grade", "contained_metal"], index="ijk", dense=True)
    result.head()





.. raw:: html

    <div class="output_subarea output_html rendered_html output_result">
    <div>
    <style scoped>
        .dataframe tbody tr th:only-of-type {
            vertical-align: middle;
        }

        .dataframe tbody tr th {
            vertical-align: top;
        }

        .dataframe thead th {
            text-align: right;
        }
    </style>
    <table border="1" class="dataframe">
      <thead>
        <tr style="text-align: right;">
          <th></th>
          <th></th>
          <th></th>
          <th>grade</th>
          <th>contained_metal</th>
        </tr>
        <tr>
          <th>i</th>
          <th>j</th>
          <th>k</th>
          <th></th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th rowspan="4" valign="top">0</th>
          <th rowspan="2" valign="top">0</th>
          <th>0</th>
          <td>0.366667</td>
          <td>415.873016</td>
        </tr>
        <tr>
          <th>1</th>
          <td>0.398413</td>
          <td>456.691707</td>
        </tr>
        <tr>
          <th rowspan="2" valign="top">1</th>
          <th>0</th>
          <td>0.493651</td>
          <td>585.177513</td>
        </tr>
        <tr>
          <th>1</th>
          <td>0.525397</td>
          <td>630.016416</td>
        </tr>
        <tr>
          <th>1</th>
          <th>0</th>
          <th>0</th>
          <td>0.874603</td>
          <td>1189.615514</td>
        </tr>
      </tbody>
    </table>
    </div>
    </div>
    <br />
    <br />


.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 0.047 seconds)


.. _sphx_glr_download_auto_examples_11_reblocking_calculated_attributes.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: 11_reblocking_calculated_attributes.ipynb <11_reblocking_calculated_attributes.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: 11_reblocking_calculated_attributes.py <11_reblocking_calculated_attributes.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: 11_reblocking_calculated_attributes.zip <11_reblocking_calculated_attributes.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
