{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 5-MapReduce\n", "This tutorial demonstrates how to use Map and Reduce to count the number of atoms in a structure." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from pyspark.sql import SparkSession\n", "from mmtfPyspark.io import mmtfReader" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Configure Spark" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "spark = SparkSession.builder.appName(\"5-MapReduce\").getOrCreate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Read PDB structures" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "path = \"../resources/mmtf_full_sample\"\n", "\n", "pdb = mmtfReader.read_sequence_file(path)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Map\n", "Use a lambda expression to get the number of atoms for each entry.\n", "The variable t represents a tuple (PDB ID, mmtfStructure)\n", "\n", "* t[0]: PDB ID\n", "* t[1]: mtfStructure" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "num_atoms = pdb.map(lambda t: t[1].num_atoms)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Print the number of atoms for 10 entries" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1793, 2731, 3056, 2275, 4238, 5436, 3596, 4310, 1386, 1139]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num_atoms.take(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reduce\n", "Use the reduce method with a summation function defined as a lambda expression" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "34248081" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num_atoms.reduce(lambda a, b: a+b)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "spark.stop()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 4 }