hello

Hey! How can I help you today?

why proteus shows swarming motility

Reading File
Finding Sources
Searching the Web

Proteus mirabilis swarming motility mechanism flagella differentiation

Reading File
Here is a thorough breakdown of why Proteus shows swarming motility:

Swarming Motility in Proteus mirabilis

What is Swarming?

Swarming is a coordinated, multicellular form of movement across solid or semi-solid surfaces. It is distinct from "swimming," which occurs in liquid environments. Proteus mirabilis is the classic example of swarming bacteria and has been studied since it was first described by Gustav Hauser in 1885.

The Core Mechanism: Swimmer → Swarmer Cell Differentiation

In liquid broth, Proteus exists as short "swimmer cells" (~2 µm long) with 4-10 peritrichous flagella. When these cells encounter a solid surface, a dramatic transformation occurs:
FeatureSwimmer CellSwarmer Cell
Length~2 µm60-80 µm
Flagella4-10Thousands (hyperflagellated)
NucleoidsNormal, separatedMultinucleated (no septation)
EnvironmentLiquidSolid/semi-solid surfaces

Step-by-Step: How Swarming is Triggered

  1. Surface sensing - When flagellar rotation is physically inhibited by a solid surface (increased viscosity/resistance), the bacterium "senses" it is on a solid surface. This impedance of flagellar rotation acts as the trigger signal.
  2. Gene upregulation - The master regulator operon flhDC is upregulated. This drives overexpression of flagellin genes, resulting in massive flagella synthesis. Hundreds to thousands of flagella are produced.
  3. Cell elongation - Cell division is suppressed (septation is inhibited), but DNA replication continues. This creates long, multinucleated cells.
  4. Collective migration - Swarmer cells align and move together in coordinated waves, propelled by their bundled flagella.
  5. Consolidation - After a period of migration, swarmer cells consolidate back into swimmer cells. The cycle then repeats, creating the characteristic concentric ring (bull's-eye) pattern on agar plates.

Other Signals That Regulate Swarming

  • Putrescine (a polyamine) acts as an extracellular signal; its biosynthesis genes (speA, speB) are needed for timely swarmer differentiation
  • Quorum sensing - Cell density signals contribute to coordinating the collective migration
  • Surface wetness - A thin fluid film on the surface is required for flagellar function

Why Does it Matter Clinically?

  • Swarming is directly linked to virulence - swarmer cells co-express urease, hemolysin, and fimbriae at higher levels
  • It facilitates catheter-associated UTIs (CAUTIs) - Proteus can literally swarm up urinary catheters to reach the bladder and upper urinary tract
  • Swarmer cells can invade epithelial cells in vitro
  • The urease produced (very potent compared to other Enterobacteriaceae) alkalinizes urine and contributes to struvite/urinary stone formation

Laboratory Recognition

  • On agar plates: spreading, concentric ring growth (bull's-eye pattern) that can overgrow other organisms in culture, delaying isolation of other pathogens - a common frustration for microbiologists
  • Distinct ammoniac odor due to urease activity
  • Lactose-negative, H₂S positive, indole-negative (P. mirabilis) or indole-positive (P. vulgaris)
Sources: Sherris & Ryan's Medical Microbiology 8E; Harrison's Principles of Internal Medicine 22E; Frontiers in Cellular and Infection Microbiology (2022)

A helpful video demonstrating the swarming pattern:

tell me why alchol causes acute pancreatitis

Finding Sources
Searching the Web

alcohol induced acute pancreatitis pathophysiology mechanism 2024

Reading File
Reading File
Finding Sources
Reading File
Reading File
Reading File
Loading Image
Here is a complete explanation of how alcohol causes acute pancreatitis:

How Alcohol Causes Acute Pancreatitis

The pathogenesis diagram from Robbins below shows all three converging pathways:
Pathogenesis of Acute Pancreatitis - Robbins

The Central Event: Premature Trypsin Activation

Under normal conditions, pancreatic digestive enzymes are synthesized as inactive zymogens (e.g., trypsinogen) and are only activated after reaching the duodenum by enterokinase. Acute pancreatitis occurs when trypsinogen is prematurely converted to active trypsin inside acinar cells, which then activates a cascade of other destructive enzymes - elastase, phospholipase, lipase - causing autodigestion of the pancreas.
Alcohol triggers this through three overlapping mechanisms:

Mechanism 1: Duct Obstruction

  • Alcohol causes transient spasm of the sphincter of Oddi (the muscle at the papilla of Vater), increasing intraductal pressure
  • Chronic alcohol consumption leads to the secretion of protein-rich pancreatic juice that is prone to forming inspissated protein plugs - these physically obstruct small pancreatic ducts
  • Obstruction raises intrapancreatic ductal pressure → enzyme-rich fluid leaks into the interstitium → lipase (secreted in active form) causes local fat necrosis → "danger signals" trigger leukocyte infiltration and microvascular leak → edema → ischemic injury to acinar cells

Mechanism 2: Direct Acinar Cell Injury (Toxic/Metabolic)

This is the most important mechanism for alcohol specifically:
  • Ethanol is metabolized in acinar cells via oxidative (alcohol dehydrogenase/CYP2E1) and non-oxidative pathways, generating toxic metabolites:
    • Acetaldehyde - directly damages cell membranes and mitochondria
    • Fatty acid ethyl esters (FAEEs) - non-oxidative metabolites that are cytotoxic
    • Reactive oxygen species (ROS) - cause lipid peroxidation and membrane damage
  • This oxidative stress damages mitochondria, which raises intracellular calcium (Ca²⁺)
  • Elevated intracellular Ca²⁺ is a critical trigger: normally low Ca²⁺ allows trypsin to self-inactivate (autoinhibition), but when Ca²⁺ rises, this protection is lost and trypsin auto-activation is favored
  • Activated trypsin then sets off a proteolytic cascade activating elastase, phospholipase A₂, etc., causing autodigestion

Mechanism 3: Defective Intracellular Transport (Lysosomal Co-localization)

  • Alcohol promotes the aberrant fusion of lysosomes and zymogen granules within acinar cells
  • Lysosomal hydrolases (especially cathepsins) then come in contact with trypsinogen and activate it intracellularly
  • This bypasses the normal secretory pathway and results in enzyme activation before reaching the duodenum

The Final Cascade: What the Activated Enzymes Do

Activated EnzymeDamage Caused
Trypsin / ProteasesProtein degradation, parenchymal injury, coagulation pathway activation
ElastaseDigests vessel walls → hemorrhage
Phospholipase A₂Destroys cell membranes; damages alveolar surfactant (→ ARDS)
LipaseFat necrosis (chalky white deposits - calcium saponification)
The local injury then triggers a systemic inflammatory response via TNF-α, IL-1, IL-6, and IL-8 release, which can progress to SIRS, ARDS, and multiorgan failure in severe cases.

Why Don't All Alcoholics Get Pancreatitis?

This is an important clinical question. Only a minority (~10%) of heavy drinkers develop pancreatitis, and usually only after 5-15 years of chronic use. Genetic susceptibility plays a role - notably:
  • CLDN2 gene variant (claudin-2, a tight junction protein on X chromosome) - nearly doubles risk in males with alcoholic pancreatitis
  • Mutations in PRSS1, SPINK1, CFTR increase susceptibility when combined with alcohol
  • Smoking potentiates alcohol-induced pancreatic microcirculatory damage

Sources: Robbins, Cotran & Kumar Pathologic Basis of Disease (Fig. 19.2, p. 819); Schwartz's Principles of Surgery 11E; StatPearls - Acute Pancreatitis; PMC - Pathophysiology of Alcoholic Pancreatitis

explain me whole renal physiology from standard physiology textbook

Finding Sources
Finding Sources
Reading File
Finding Sources
Reading File
Reading File
Finding Sources
Finding Sources
Reading File
Finding Sources
Finding Sources
Finding Sources
Reading File
Loading Image
Loading Image
Finding Sources
Here is a complete, textbook-level walkthrough of renal physiology, primarily sourced from Guyton & Hall Textbook of Medical Physiology (the standard physiology reference), with supporting material from Ganong's and Costanzo.

Renal Physiology - Complete Overview


1. Functional Anatomy of the Nephron

Each kidney contains approximately 1 million nephrons. Each nephron consists of:
  • Glomerulus (~200 µm) - a tuft of capillaries inside Bowman's capsule
  • Bowman's capsule - collects the filtrate
  • Proximal convoluted tubule (PCT)
  • Loop of Henle (descending thin limb → ascending thin → ascending thick limb)
  • Distal convoluted tubule (DCT)
  • Collecting duct (cortical → medullary → duct of Bellini → renal pelvis)
Nephron anatomy and blood supply - Guyton & Hall

Two types of nephrons:

TypeLocationLoop of HenleRole
Cortical nephrons (~75%)Outer cortexShort, barely enters medullaGeneral filtration
Juxtamedullary nephrons (~25%)Near corticomedullary junctionLong, dips deep into medullaUrine concentration via countercurrent

Blood Supply (critical to understand):

  • Renal artery → interlobar → arcuate → interlobular arteries → afferent arteriole
  • Afferent arteriole → glomerular capillariesefferent arteriole
  • Efferent arteriole → peritubular capillaries (cortex) and vasa recta (medulla)
  • Peritubular capillaries → interlobular veins → renal vein
The presence of two capillary beds in series (glomerular + peritubular) is unique to the kidney and fundamental to its physiology.

2. The Three Core Renal Processes

Basic kidney processes - Guyton & Hall
The fundamental equation:
Urinary Excretion = Filtration - Reabsorption + Secretion
All substances in urine are accounted for by these three processes.

3. Glomerular Filtration

What is Filtered?

The glomerular filtrate is essentially plasma minus proteins. All small molecules (electrolytes, glucose, urea, creatinine, amino acids) pass freely. Proteins and protein-bound substances are retained.

GFR - Glomerular Filtration Rate

  • Normal GFR = 125 mL/min (180 L/day filtered!)
  • Of this, only ~1.5 L/day is excreted as urine - meaning >99% of filtrate is reabsorbed

Starling Forces Governing Filtration

The net filtration pressure is determined by:
ForceValueDirection
Glomerular capillary hydrostatic pressure (Pgc)~60 mmHgPromotes filtration
Bowman's capsule hydrostatic pressure (Pbs)~18 mmHgOpposes filtration
Glomerular oncotic pressure (πgc)~32 mmHgOpposes filtration
Net filtration pressure~10 mmHgNet = promotes filtration
GFR = Kf × Net filtration pressure
where Kf = filtration coefficient (product of capillary permeability × surface area)

Factors that Alter GFR:

Increases GFR:
  • Increased afferent arteriole dilation (e.g., prostaglandins, ANP)
  • Increased blood pressure (within autoregulatory range)
  • Decreased plasma oncotic pressure
Decreases GFR:
  • Afferent arteriole constriction (sympathetic activity, angiotensin II at high doses)
  • Efferent arteriole dilation (ACE inhibitors - reduce efferent constriction)
  • Increased Bowman's capsule pressure (urinary obstruction)
  • Decreased Kf (glomerular disease)

Renal Autoregulation

The kidney maintains near-constant GFR over a wide range of mean arterial pressure (80-180 mmHg) via two mechanisms:
  1. Myogenic mechanism - stretch of afferent arteriole wall → vasoconstriction
  2. Tubuloglomerular feedback (TGF) - macula densa senses NaCl delivery; if high → afferent arteriole constricts → reduces GFR

Measuring GFR - Clearance Concept

Clearance = volume of plasma completely cleared of a substance per unit time
Clearance = (Urine concentration × Urine flow) / Plasma concentration = U×V/P
Inulin clearance = gold standard for GFR (freely filtered, not reabsorbed or secreted) Creatinine clearance ≈ GFR clinically (slightly overestimates because creatinine is secreted a little)

4. Tubular Reabsorption and Secretion

Proximal Convoluted Tubule (PCT)

The PCT reabsorbs ~65-70% of filtered Na⁺, water, Cl⁻, K⁺, HCO₃⁻ and nearly 100% of glucose and amino acids.
Mechanism of sodium reabsorption in PCT:
  • Basolateral Na⁺/K⁺-ATPase is the primary engine - pumps 3 Na⁺ out, 2 K⁺ in, maintaining low intracellular Na⁺
  • This creates a gradient driving Na⁺ into the cell from the lumen via:
    • Na⁺-glucose cotransporter (SGLT2) - reabsorbs glucose with Na⁺ (site of action of SGLT2 inhibitors)
    • Na⁺-amino acid cotransporters
    • Na⁺/H⁺ antiporter (couples Na⁺ entry with H⁺ secretion → HCO₃⁻ reabsorption)
  • Water follows passively through aquaporin-1 (AQP1) channels (PCT is always water permeable)
  • The reabsorption here is isosmotic - fluid remains at 300 mOsm/L
Glucose reabsorption - Tm concept:
  • All filtered glucose is normally reabsorbed (normal plasma glucose ~100 mg/dL)
  • Transport maximum (Tm) for glucose ≈ 375 mg/min
  • Renal threshold for glucose ≈ plasma glucose of 180-200 mg/dL
  • Above this: glucosuria occurs (e.g., in diabetes mellitus)

Loop of Henle

This is where the filtrate becomes separated from its water to create the concentrated medullary interstitium.
SegmentNa⁺/SoluteWaterNet Effect
Thin descending limbNo active transportPermeable (AQP1)Fluid becomes hypertonic (water leaves)
Thin ascending limbSome passive NaCl outImpermeableFluid dilutes slightly
Thick ascending limbActive Na⁺/K⁺/2Cl⁻ cotransport (NKCC2)ImpermeableFluid becomes hypotonic (~100 mOsm/L); medulla becomes concentrated
The thick ascending limb is the diluting segment - it pumps out solute without water. This is the site of action of loop diuretics (furosemide), which block NKCC2.

Distal Convoluted Tubule (DCT)

  • Reabsorbs Na⁺ and Cl⁻ via NaCl cotransporter (NCC) - blocked by thiazide diuretics
  • Begins to become regulated (responds to aldosterone in late DCT)
  • Early DCT: water impermeable - continues dilution
  • Fluid entering DCT is ~100 mOsm/L (hypotonic)

Collecting Duct (CD) - the "fine-tuning" segment

This is where the final urine composition is determined, under hormonal control.
Principal cells (main cell type):
  • Reabsorb Na⁺ via ENaC (epithelial sodium channels) on apical membrane
  • Secrete K⁺ via ROMK channels
  • Regulated by aldosterone (increases ENaC and K⁺-ATPase expression)
  • Water reabsorption regulated by ADH/vasopressin (inserts AQP2 on apical membrane)
Alpha-intercalated cells:
  • Secrete H⁺ (via H⁺-ATPase) → important for acid-base regulation
  • Reabsorb HCO₃⁻

5. Concentration and Dilution of Urine

This is one of the most important and elegant mechanisms in physiology.

The Countercurrent Multiplier (Loop of Henle)

The medullary interstitium has a progressive osmolarity gradient from cortex (300 mOsm/L) to papilla (up to 1200-1400 mOsm/L). This is built and maintained by:
  1. Active NaCl pumping out of the thick ascending limb (impermeable to water) → deposits solute into medullary interstitium
  2. Urea recycling - urea diffuses out of the inner medullary collecting duct into the interstitium (especially in the presence of ADH), adding ~500 mOsm/L to the inner medulla
  3. The descending limb (permeable to water) equilibrates with the hypertonic interstitium - water leaves, fluid inside becomes concentrated
  4. The cycle multiplies the gradient with each loop - hence "multiplier"

The Countercurrent Exchanger (Vasa Recta)

The vasa recta (blood vessels of the medulla) run in hairpin loops alongside the loop of Henle. As blood descends, it picks up solute and loses water; as it ascends, it loses solute and gains water. This prevents washout of the medullary gradient, preserving it.

How ADH Controls Final Urine Concentration

Without ADH:
  • Collecting duct is water-impermeable
  • Hypotonic fluid (100 mOsm/L) coming from DCT passes through without losing water
  • Dilute urine is produced (as low as 50 mOsm/L)
With ADH (high plasma osmolarity or low blood volume):
  • ADH binds V2 receptors on principal cells → activates adenylyl cyclase → ↑ cAMP → PKA activation → AQP2 vesicles fuse with apical membrane
  • Collecting duct becomes highly water permeable
  • Water rushes out into the hypertonic medullary interstitium
  • Concentrated urine is produced (up to 1200-1400 mOsm/L)
This is the basis of diabetes insipidus - absent ADH (central DI) or non-functioning V2 receptors (nephrogenic DI) → massive dilute urine output.

6. Hormonal Regulation of Kidney Function

Renin-Angiotensin-Aldosterone System (RAAS)

StepWhereWhat Happens
Low BP / low Na delivery to macula densa / sympathetic activityJuxtaglomerular (JG) cellsRelease renin
Renin acts on angiotensinogen (liver)PlasmaAngiotensin I
ACE (lung endothelium)PlasmaAngiotensin II
Ang II → adrenal cortexZona glomerulosa→ releases aldosterone
Aldosterone → collecting duct principal cellsKidney↑ ENaC + Na⁺/K⁺-ATPase → ↑ Na⁺ reabsorption, ↑ K⁺ excretion
Ang II also acts directly on PCTPCT↑ Na⁺/H⁺ antiporter → ↑ Na⁺ reabsorption
Net effect: Increases blood volume and blood pressure; retains Na⁺ and water.

ADH (Vasopressin)

  • Produced in hypothalamus (supraoptic and paraventricular nuclei), released from posterior pituitary
  • Stimulated by: ↑ plasma osmolarity, ↓ blood volume
  • Actions: Water retention (collecting duct AQP2), vasoconstriction (V1 receptor)

Atrial Natriuretic Peptide (ANP)

  • Released by atria when stretched (high blood volume)
  • Effects: ↑ GFR (dilates afferent, constricts efferent arteriole), ↓ renin, ↓ aldosterone, ↓ ADH
  • Net: Natriuresis + diuresis → reduces blood volume

Parathyroid Hormone (PTH)

  • Increases Ca²⁺ reabsorption in DCT
  • Decreases phosphate reabsorption in PCT
  • Stimulates 1α-hydroxylase in kidney (activates Vitamin D → 1,25-(OH)₂D₃)

7. Renal Handling of Specific Substances

SubstanceFilteredPCTLoopDCT/CDNet
SodiumYes65-70% reabsorbed25% (thick ALH)~5% (regulated)<1% excreted
GlucoseYes100% reabsorbed (Tm-limited)--0 excreted normally
PotassiumYes65% reabsorbed25% reabsorbedSecreted (aldosterone)Variable
UreaYes50% reabsorbedSecreted (thin)Reabsorbed (IMCD)~50% excreted
CreatinineYesNot reabsorbed-Small secretion~100% excreted
HCO₃⁻Yes80-90% reabsorbed~5%Final regulationMinimal excretion
H⁺-Secreted (Na/H antiporter)-Secreted (H⁺-ATPase)Acid-base balance
PhosphateYes85% reabsorbed (PTH inhibits)--15% excreted
CalciumYes65% passive25% (TAL)Active (PTH)<2% excreted

8. Renal Control of Acid-Base Balance

The kidney is the long-term regulator of pH (lungs handle the short-term CO₂).
Three mechanisms:
  1. HCO₃⁻ reabsorption - PCT reabsorbs ~80-90% via Na⁺/H⁺ antiporter. H⁺ secreted reacts with filtered HCO₃⁻ → H₂CO₃ → CO₂ + H₂O (carbonic anhydrase) → CO₂ enters cell → reformed as HCO₃⁻ → basolateral exit to blood. Net: HCO₃⁻ is "reclaimed."
  2. Titratable acid excretion - H⁺ secreted in collecting duct combines with HPO₄²⁻ → H₂PO₄⁻, which is excreted. This excretes fixed acid.
  3. Ammonium (NH₄⁺) excretion - PCT generates NH₃ from glutamine (glutaminase); NH₃ + H⁺ → NH₄⁺, which is trapped in the tubular lumen and excreted. This is the most important mechanism in chronic acidosis.

9. Renal Clearance - Key Values to Know

SubstanceClearanceMeaning
Glucose0 mL/minFully reabsorbed
Sodium~0.9 mL/minMostly reabsorbed
Potassium~12 mL/minReabsorbed + some net secretion
Inulin125 mL/min= GFR (gold standard)
Creatinine~140 mL/minSlightly secreted, overestimates GFR
PAH (para-aminohippuric acid)~650 mL/min= Renal plasma flow (RPF); fully secreted
Filtration fraction = GFR/RPF = 125/650 ≈ 0.19 (19%)

10. Summary: Flow of Fluid Through the Nephron

Plasma → Glomerular filtration → Bowman's capsule (300 mOsm/L)
         ↓
   PCT: isosmotic reabsorption (Na⁺, glucose, AA, HCO₃⁻, water) → 65-70% reabsorbed
         ↓
   Descending LOH: water leaves → fluid concentrates to ~1200 mOsm at tip
         ↓
   Ascending LOH (thin): NaCl passively diffuses out, no water → dilutes slightly
         ↓
   Thick ALH: active NaCl pump, NO water → fluid dilutes to ~100 mOsm
         ↓
   DCT: further NaCl reabsorption (NCC), starts aldosterone response
         ↓
   Collecting duct:
      + ADH → AQP2 inserted → water reabsorbed → concentrated urine (up to 1200 mOsm)
      - ADH → water stays → dilute urine (~50-100 mOsm)
      + Aldosterone → more Na⁺ reabsorbed, K⁺ secreted
         ↓
   Final urine → renal pelvis → ureter → bladder → excreted

Sources: Guyton and Hall Textbook of Medical Physiology 14E (primary); Ganong's Review of Medical Physiology 26E; Costanzo Physiology 7E; Brenner and Rector's The Kidney

Create a comprehensive study guide PDF on renal physiology with diagrams and tables

Reading File
Reading File
Reading File
Running Command

ls /home/daytona/workspace/ 2>/dev/null && mkdir -p /home/daytona/workspace/rena…

Writing File

~/renal-physiology-guide/create_pdf.py

#!/usr/bin/env python3
"""
Comprehensive Renal Physiology Study Guide PDF
Generated with ReportLab
"""

import json, subprocess, base64, os
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm, mm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    PageBreak, HRFlowable, Image, KeepTogether
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.platypus.flowables import HRFlowable
from reportlab.graphics.shapes import Drawing, Rect, String, Line, Arrow, Polygon, Circle
from reportlab.graphics import renderPDF
from reportlab.graphics.shapes import Drawing, Rect, String, Line, Group
from io import BytesIO

# ─────────────────────────────────────────────────────────
# Colour Palette
# ─────────────────────────────────────────────────────────
NAVY      = colors.HexColor("#1a3a5c")
TEAL      = colors.HexColor("#2980b9")
LIGHT_BLUE= colors.HexColor("#d6eaf8")
GOLD      = colors.HexColor("#f39c12")
ORANGE    = colors.HexColor("#e67e22")
GREEN     = colors.HexColor("#27ae60")
LIGHT_GREEN = colors.HexColor("#d5f5e3")
RED       = colors.HexColor("#c0392b")
LIGHT_RED = colors.HexColor("#fadbd8")
PURPLE    = colors.HexColor("#8e44ad")
LIGHT_PURPLE = colors.HexColor("#e8daef")
GRAY      = colors.HexColor("#7f8c8d")
LIGHT_GRAY= colors.HexColor("#f2f3f4")
WHITE     = colors.white
DARK      = colors.HexColor("#2c3e50")

# ─────────────────────────────────────────────────────────
# Page setup
# ─────────────────────────────────────────────────────────
OUTPUT = "/home/daytona/workspace/renal-physiology-guide/Renal_Physiology_Study_Guide.pdf"
PAGE_W, PAGE_H = A4
MARGIN = 2 * cm

doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=MARGIN, rightMargin=MARGIN,
    topMargin=2.2*cm, bottomMargin=2*cm,
    title="Renal Physiology – Comprehensive Study Guide",
    author="Orris Medical Education",
    subject="Renal Physiology"
)

# ─────────────────────────────────────────────────────────
# Styles
# ─────────────────────────────────────────────────────────
styles = getSampleStyleSheet()

def make_style(name, parent="Normal", **kwargs):
    return ParagraphStyle(name, parent=styles[parent], **kwargs)

ST_TITLE    = make_style("MyTitle",    "Title",   fontSize=26, textColor=NAVY,
                          spaceAfter=6, leading=32, alignment=TA_CENTER)
ST_SUBTITLE = make_style("MySubtitle","Normal",   fontSize=13, textColor=TEAL,
                          spaceAfter=4, alignment=TA_CENTER, italic=True)
ST_H1       = make_style("H1",        "Heading1", fontSize=15, textColor=WHITE,
                          spaceAfter=6, spaceBefore=14, leading=18)
ST_H2       = make_style("H2",        "Heading2", fontSize=12, textColor=NAVY,
                          spaceAfter=4, spaceBefore=10, leading=15)
ST_H3       = make_style("H3",        "Heading3", fontSize=10.5, textColor=TEAL,
                          spaceAfter=3, spaceBefore=6, leading=13)
ST_BODY     = make_style("Body",      "Normal",   fontSize=9.5, leading=14,
                          spaceAfter=4, alignment=TA_JUSTIFY)
ST_BULLET   = make_style("Bullet",    "Normal",   fontSize=9.5, leading=13,
                          spaceAfter=2, leftIndent=14, bulletIndent=4)
ST_BOX      = make_style("Box",       "Normal",   fontSize=9, leading=13,
                          spaceAfter=2, leftIndent=6, textColor=DARK)
ST_CAPTION  = make_style("Caption",   "Normal",   fontSize=8.5, italic=True,
                          textColor=GRAY, alignment=TA_CENTER, spaceAfter=4)
ST_KEY      = make_style("Key",       "Normal",   fontSize=9.5, textColor=RED,
                          leading=13, spaceAfter=2, leftIndent=14,
                          fontName="Helvetica-Bold")
ST_FORMULA  = make_style("Formula",   "Normal",   fontSize=10,
                          textColor=NAVY, fontName="Helvetica-Bold",
                          alignment=TA_CENTER, spaceAfter=6, spaceBefore=4)

# ─────────────────────────────────────────────────────────
# Helper: section header with coloured band
# ─────────────────────────────────────────────────────────
def section_header(text, color=NAVY, num=""):
    label = f"{num}  {text}" if num else text
    p = Paragraph(f"<font color='white'><b>{label}</b></font>", ST_H1)
    t = Table([[p]], colWidths=[PAGE_W - 2*MARGIN])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), color),
        ("TOPPADDING",  (0,0), (-1,-1), 6),
        ("BOTTOMPADDING",(0,0),(-1,-1), 6),
        ("LEFTPADDING", (0,0), (-1,-1), 10),
        ("ROUNDEDCORNERS", [4]),
    ]))
    return t

def sub_header(text, color=TEAL):
    p = Paragraph(f"<b>{text}</b>", ST_H2)
    return p

def key_point(text):
    return Paragraph(f"<b>&#9733;</b>  {text}", ST_KEY)

def bullet(text, indent=0):
    style = ParagraphStyle("bul", parent=ST_BULLET, leftIndent=14+indent*12)
    return Paragraph(f"&#8226;  {text}", style)

def body(text):
    return Paragraph(text, ST_BODY)

def formula(text):
    return Paragraph(text, ST_FORMULA)

def spacer(h=0.3):
    return Spacer(1, h*cm)

def hr(color=TEAL, thickness=0.5):
    return HRFlowable(width="100%", thickness=thickness, color=color, spaceAfter=4, spaceBefore=4)

# ─────────────────────────────────────────────────────────
# Helper: styled table
# ─────────────────────────────────────────────────────────
def make_table(header, rows, col_widths=None, header_color=NAVY, alt_color=LIGHT_BLUE):
    data = [[Paragraph(f"<b><font color='white'>{h}</font></b>", ST_BOX) for h in header]]
    for i, row in enumerate(rows):
        data.append([Paragraph(str(c), ST_BOX) for c in row])

    if col_widths is None:
        avail = PAGE_W - 2*MARGIN
        col_widths = [avail / len(header)] * len(header)

    t = Table(data, colWidths=col_widths, repeatRows=1)
    style = [
        ("BACKGROUND", (0,0), (-1,0), header_color),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, alt_color]),
        ("GRID", (0,0), (-1,-1), 0.4, colors.HexColor("#bdc3c7")),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 6),
        ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
    ]
    t.setStyle(TableStyle(style))
    return t

# ─────────────────────────────────────────────────────────
# Helper: info box
# ─────────────────────────────────────────────────────────
def info_box(title, lines, bg=LIGHT_BLUE, border=TEAL):
    content = [Paragraph(f"<b>{title}</b>", ST_H3)]
    for l in lines:
        content.append(Paragraph(f"&#8226;  {l}", ST_BOX))
    t = Table([[content]], colWidths=[PAGE_W - 2*MARGIN])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), bg),
        ("BOX", (0,0), (-1,-1), 1.5, border),
        ("TOPPADDING",  (0,0), (-1,-1), 8),
        ("BOTTOMPADDING",(0,0),(-1,-1), 8),
        ("LEFTPADDING", (0,0), (-1,-1), 10),
        ("RIGHTPADDING",(0,0), (-1,-1), 10),
    ]))
    return t

# ─────────────────────────────────────────────────────────
# Diagram helpers (pure ReportLab Drawing objects)
# ─────────────────────────────────────────────────────────
def nephron_flow_diagram():
    """Simple flow diagram of nephron segments"""
    d = Drawing(480, 200)
    segments = [
        ("Bowman's\nCapsule", 0,   TEAL,  "300 mOsm"),
        ("PCT",               90,  GREEN, "~300 mOsm\n65% reabs."),
        ("Loop of\nHenle",   180,  ORANGE,"100 mOsm\n(exit)"),
        ("DCT",              270,  PURPLE,"~100 mOsm"),
        ("Collecting\nDuct", 360,  RED,   "50-1400\nmOsm"),
    ]
    for (label, x, col, osm) in segments:
        # box
        d.add(Rect(x+2, 60, 78, 70, fillColor=col, strokeColor=WHITE, strokeWidth=1.5, rx=6, ry=6))
        # label
        for i, line in enumerate(label.split("\n")):
            d.add(String(x+41, 115 - i*12, line, fontSize=8, fillColor=WHITE,
                         textAnchor="middle", fontName="Helvetica-Bold"))
        # osmolarity below
        for i, line in enumerate(osm.split("\n")):
            d.add(String(x+41, 52 - i*11, line, fontSize=7.5, fillColor=col,
                         textAnchor="middle"))
        # arrow between boxes
        if x < 360:
            d.add(Line(x+82, 95, x+90, 95, strokeColor=GRAY, strokeWidth=1.5))
            d.add(Polygon([x+88, 99, x+88, 91, x+94, 95], fillColor=GRAY, strokeColor=GRAY))

    # Labels at top
    d.add(String(240, 185, "Nephron Segment Flow & Osmolarity",
                 fontSize=11, textAnchor="middle", fontName="Helvetica-Bold", fillColor=NAVY))
    d.add(String(240, 170, "(Numbers = approximate tubular fluid osmolarity)",
                 fontSize=8, textAnchor="middle", fillColor=GRAY))
    return d


def starling_forces_diagram():
    """Starling forces at the glomerulus"""
    d = Drawing(480, 160)
    # Glomerulus circle
    d.add(Circle(120, 80, 55, fillColor=colors.HexColor("#f5cba7"),
                 strokeColor=ORANGE, strokeWidth=2))
    d.add(String(120, 78, "Glomerular", fontSize=9, textAnchor="middle",
                 fontName="Helvetica-Bold", fillColor=DARK))
    d.add(String(120, 66, "Capillary", fontSize=9, textAnchor="middle", fillColor=DARK))

    # Forces arrows and labels
    forces = [
        # (x1,y1,x2,y2, label, value, color, direction)
        (180, 80, 300, 80, "Pgc (hydrostatic)", "60 mmHg", GREEN, "→ promotes"),
        (120, 140, 120, 170, "Pbs (capsule P)", "18 mmHg", RED, "↑ opposes"),
        (60,  80, -30, 80, "πgc (oncotic)", "32 mmHg", PURPLE, "← opposes"),
    ]
    # Net
    d.add(Rect(310, 50, 160, 65, fillColor=LIGHT_GREEN, strokeColor=GREEN, strokeWidth=1.5, rx=4, ry=4))
    d.add(String(390, 105, "NET FILTRATION", fontSize=9, textAnchor="middle",
                 fontName="Helvetica-Bold", fillColor=GREEN))
    d.add(String(390, 91, "PRESSURE", fontSize=9, textAnchor="middle",
                 fontName="Helvetica-Bold", fillColor=GREEN))
    d.add(String(390, 77, "60 - 18 - 32", fontSize=10, textAnchor="middle", fillColor=DARK))
    d.add(String(390, 63, "= ~10 mmHg", fontSize=11, textAnchor="middle",
                 fontName="Helvetica-Bold", fillColor=NAVY))

    # Force labels on left
    labels = [
        (10, 148, "Pgc = 60 mmHg  (promotes filtration)", GREEN),
        (10, 134, "Pbs = 18 mmHg  (opposes filtration)", RED),
        (10, 120, "pgc = 32 mmHg  (opposes filtration)", PURPLE),
    ]
    for (x, y, txt, col) in labels:
        d.add(String(x, y, txt, fontSize=8, fillColor=col))

    d.add(String(240, 10, "Starling Forces at the Glomerulus",
                 fontSize=10, textAnchor="middle", fontName="Helvetica-Bold", fillColor=NAVY))
    return d


def countercurrent_diagram():
    """Simplified countercurrent multiplier"""
    d = Drawing(480, 230)
    d.add(String(240, 218, "Countercurrent Multiplier – Osmolarity Gradient",
                 fontSize=10, textAnchor="middle", fontName="Helvetica-Bold", fillColor=NAVY))

    # Cortex / Medulla labels
    d.add(Rect(0, 150, 480, 60, fillColor=colors.HexColor("#fef9e7"),
               strokeColor=GOLD, strokeWidth=1))
    d.add(String(10, 192, "CORTEX", fontSize=9, fontName="Helvetica-Bold", fillColor=GOLD))

    d.add(Rect(0, 0, 480, 150, fillColor=colors.HexColor("#eaf2ff"),
               strokeColor=TEAL, strokeWidth=1))
    d.add(String(10, 8, "MEDULLA (inner)", fontSize=9, fontName="Helvetica-Bold", fillColor=TEAL))

    # Descending limb (left column, water permeable)
    dl_x = 120
    d.add(Rect(dl_x, 10, 50, 195, fillColor=colors.HexColor("#aed6f1"),
               strokeColor=TEAL, strokeWidth=1.5))
    d.add(String(dl_x+25, 205, "DESC.", fontSize=8, textAnchor="middle",
                 fontName="Helvetica-Bold", fillColor=TEAL))
    d.add(String(dl_x+25, 195, "LIMB", fontSize=8, textAnchor="middle", fillColor=TEAL))
    # osmolarity values descending
    osm_vals = [(190, "300"), (160, "600"), (130, "900"), (100, "1200"), (70, "1200")]
    for (y, val) in osm_vals:
        d.add(String(dl_x+25, y, val, fontSize=8, textAnchor="middle", fillColor=NAVY))

    # Ascending limb (right column, impermeable to water)
    al_x = 200
    d.add(Rect(al_x, 10, 50, 195, fillColor=colors.HexColor("#a9dfbf"),
               strokeColor=GREEN, strokeWidth=1.5))
    d.add(String(al_x+25, 205, "ASC.", fontSize=8, textAnchor="middle",
                 fontName="Helvetica-Bold", fillColor=GREEN))
    d.add(String(al_x+25, 195, "LIMB", fontSize=8, textAnchor="middle", fillColor=GREEN))
    osm_asc = [(185, "100"), (158, "300"), (128, "600"), (98, "900"), (68, "1200")]
    for (y, val) in osm_asc:
        d.add(String(al_x+25, y, val, fontSize=8, textAnchor="middle", fillColor=DARK))
    d.add(String(al_x+25, 45, "Active NaCl", fontSize=7, textAnchor="middle", fillColor=GREEN))
    d.add(String(al_x+25, 35, "pump (NKCC2)", fontSize=7, textAnchor="middle", fillColor=GREEN))
    d.add(String(al_x+25, 25, "NO water", fontSize=7, textAnchor="middle",
                 fontName="Helvetica-Bold", fillColor=RED))

    # Collecting duct
    cd_x = 300
    d.add(Rect(cd_x, 10, 50, 195, fillColor=colors.HexColor("#f9ebea"),
               strokeColor=RED, strokeWidth=1.5))
    d.add(String(cd_x+25, 205, "COLL.", fontSize=8, textAnchor="middle",
                 fontName="Helvetica-Bold", fillColor=RED))
    d.add(String(cd_x+25, 195, "DUCT", fontSize=8, textAnchor="middle", fillColor=RED))
    for (y, val) in [(185,"1200"),(130,"ADH→"), (110,"water"), (90,"leaves")]:
        d.add(String(cd_x+25, y, val, fontSize=8, textAnchor="middle", fillColor=RED))

    # Medullary gradient arrow
    d.add(String(400, 190, "300", fontSize=9, fillColor=NAVY, fontName="Helvetica-Bold"))
    d.add(String(400, 100, "900", fontSize=9, fillColor=NAVY, fontName="Helvetica-Bold"))
    d.add(String(400, 20,  "1200", fontSize=9, fillColor=NAVY, fontName="Helvetica-Bold"))
    d.add(Line(420, 185, 420, 25, strokeColor=NAVY, strokeWidth=2))
    d.add(Polygon([416,25, 424,25, 420,15], fillColor=NAVY, strokeColor=NAVY))
    d.add(String(435, 100, "mOsm/L\ngradient", fontSize=8, fillColor=NAVY))

    return d


def raas_diagram():
    """RAAS cascade"""
    d = Drawing(480, 200)
    d.add(String(240, 190, "Renin-Angiotensin-Aldosterone System (RAAS)",
                 fontSize=10, textAnchor="middle", fontName="Helvetica-Bold", fillColor=NAVY))

    steps = [
        ("Low BP / Low Na+\nSymp. activity",  20,  130, TEAL),
        ("RENIN\n(JG cells)",                  110, 130, NAVY),
        ("Angiotensin I",                       200, 130, GRAY),
        ("Angiotensin II\n(ACE, lung)",         290, 130, ORANGE),
        ("ALDOSTERONE\n(adrenal cortex)",       380, 130, RED),
    ]

    for i, (label, x, y, col) in enumerate(steps):
        lines = label.split("\n")
        box_h = 12 * len(lines) + 14
        d.add(Rect(x, y - box_h//2, 82, box_h,
                   fillColor=col, strokeColor=WHITE, strokeWidth=1, rx=4, ry=4))
        for j, ln in enumerate(lines):
            d.add(String(x+41, y + (len(lines)-1)*6 - j*12,
                         ln, fontSize=7.5, textAnchor="middle",
                         fillColor=WHITE, fontName="Helvetica-Bold"))
        if i < len(steps)-1:
            d.add(Line(x+84, y, x+92, y, strokeColor=GRAY, strokeWidth=1.5))
            d.add(Polygon([x+90, y+3, x+90, y-3, x+96, y],
                          fillColor=GRAY, strokeColor=GRAY))

    # Effects of Ang II and Aldosterone
    d.add(Rect(200, 30, 170, 60, fillColor=LIGHT_GREEN, strokeColor=GREEN, strokeWidth=1, rx=4))
    effects = ["Na+ reabsorption (PCT, CD)",
               "K+ secretion (CD)",
               "Blood volume & BP"]
    d.add(String(285, 87, "NET EFFECTS:", fontSize=8,
                 textAnchor="middle", fontName="Helvetica-Bold", fillColor=GREEN))
    for i, e in enumerate(effects):
        d.add(String(285, 75 - i*11, f"+ {e}", fontSize=7.5,
                     textAnchor="middle", fillColor=DARK))

    return d


# ─────────────────────────────────────────────────────────
# Build PDF content
# ─────────────────────────────────────────────────────────
story = []

# ══════════════════════ COVER PAGE ══════════════════════
story.append(spacer(2))
# Coloured banner
banner = Table([[Paragraph("<font color='white'><b>RENAL PHYSIOLOGY</b></font>",
                            ParagraphStyle("bn", fontSize=30, alignment=TA_CENTER, leading=36))]],
               colWidths=[PAGE_W - 2*MARGIN])
banner.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,-1), NAVY),
    ("TOPPADDING", (0,0), (-1,-1), 22),
    ("BOTTOMPADDING", (0,0), (-1,-1), 22),
    ("ROUNDEDCORNERS", [8]),
]))
story.append(banner)
story.append(spacer(0.4))
story.append(Paragraph("Comprehensive Study Guide", ST_SUBTITLE))
story.append(Paragraph("Based on Guyton &amp; Hall | Ganong's | Costanzo Physiology", ST_SUBTITLE))
story.append(spacer(0.6))

toc_items = [
    ("1", "Functional Anatomy of the Nephron"),
    ("2", "Glomerular Filtration &amp; GFR"),
    ("3", "Tubular Reabsorption &amp; Secretion"),
    ("4", "Loop of Henle &amp; Countercurrent Mechanism"),
    ("5", "Urine Concentration &amp; Dilution (ADH)"),
    ("6", "Hormonal Regulation (RAAS, ANP, PTH)"),
    ("7", "Renal Handling of Key Substances"),
    ("8", "Acid–Base Balance"),
    ("9", "Renal Clearance"),
    ("10", "Quick-Reference Tables &amp; Key Values"),
]
toc_data = [[Paragraph(f"<b>{n}.</b>  {t}", ST_BODY)] for n, t in toc_items]
toc_table = Table(toc_data, colWidths=[PAGE_W - 2*MARGIN])
toc_table.setStyle(TableStyle([
    ("ROWBACKGROUNDS", (0,0), (-1,-1), [WHITE, LIGHT_BLUE]),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 14),
    ("BOX", (0,0), (-1,-1), 1, TEAL),
]))
story.append(Paragraph("<b>Contents</b>", ST_H2))
story.append(toc_table)
story.append(spacer(1))

source_box = Table([[Paragraph(
    "<b>Primary Sources:</b>  Guyton &amp; Hall Textbook of Medical Physiology 14E  •  "
    "Ganong's Review of Medical Physiology 26E  •  Costanzo Physiology 7E  •  "
    "Brenner &amp; Rector's The Kidney",
    ParagraphStyle("src", fontSize=8.5, textColor=GRAY, alignment=TA_CENTER)
)]], colWidths=[PAGE_W - 2*MARGIN])
source_box.setStyle(TableStyle([
    ("BOX", (0,0), (-1,-1), 0.5, GRAY),
    ("TOPPADDING", (0,0), (-1,-1), 6),
    ("BOTTOMPADDING", (0,0), (-1,-1), 6),
]))
story.append(source_box)
story.append(PageBreak())

# ══════════════════════ SECTION 1: ANATOMY ══════════════════════
story.append(section_header("1.  Functional Anatomy of the Nephron", NAVY, ""))
story.append(spacer(0.3))
story.append(body(
    "Each kidney contains approximately <b>1 million nephrons</b>. The nephron is the "
    "functional unit of the kidney. Each nephron consists of a renal corpuscle (glomerulus + "
    "Bowman's capsule) and a renal tubule. The tubule drains sequentially through the "
    "proximal convoluted tubule (PCT), loop of Henle, distal convoluted tubule (DCT), and "
    "collecting duct system."
))
story.append(spacer(0.2))

story.append(sub_header("Types of Nephrons"))
story.append(make_table(
    ["Type", "Location", "Loop of Henle", "Key Role"],
    [
        ["Cortical nephrons (~75%)",
         "Outer cortex", "Short; barely enters medulla",
         "General filtration; isoosmotic reabsorption"],
        ["Juxtamedullary nephrons (~25%)",
         "Near corticomedullary junction", "Long; extends deep into medulla",
         "Urine concentration via countercurrent mechanism"],
    ],
    col_widths=[3.5*cm, 3.5*cm, 5*cm, 5.5*cm]
))
story.append(spacer(0.3))

story.append(sub_header("Blood Supply – The Two-Capillary-Bed System"))
story.append(body(
    "Renal artery → interlobar arteries → arcuate arteries → interlobular arteries → "
    "<b>afferent arteriole</b> → <b>glomerular capillaries</b> (high-pressure, filtration) → "
    "<b>efferent arteriole</b> → <b>peritubular capillaries / vasa recta</b> (low-pressure, "
    "reabsorption) → renal vein."
))
story.append(info_box("Why Two Capillary Beds Matter", [
    "Glomerular capillaries: high hydrostatic pressure (~60 mmHg) drives filtration",
    "Efferent arteriole resistance: fine-tunes GFR and peritubular reabsorption",
    "Peritubular capillaries: low pressure + high oncotic pressure drives reabsorption",
    "Vasa recta: countercurrent exchanger preserving medullary osmotic gradient",
], bg=LIGHT_BLUE, border=TEAL))
story.append(spacer(0.3))

story.append(sub_header("Nephron Flow Diagram"))
story.append(nephron_flow_diagram())
story.append(Paragraph(
    "Fig 1. Simplified nephron segments with approximate tubular fluid osmolarity at each stage",
    ST_CAPTION
))
story.append(PageBreak())

# ══════════════════════ SECTION 2: GFR ══════════════════════
story.append(section_header("2.  Glomerular Filtration &amp; GFR", TEAL, ""))
story.append(spacer(0.2))
story.append(key_point("Normal GFR = 125 mL/min = 180 L/day filtered. Only ~1.5 L excreted as urine – >99% reabsorbed!"))
story.append(spacer(0.2))

story.append(sub_header("The Filtration Barrier"))
story.append(body(
    "The glomerular filtration barrier has three layers: <b>(1)</b> fenestrated capillary "
    "endothelium (prevents cells), <b>(2)</b> glomerular basement membrane (GBM, blocks large "
    "proteins), <b>(3)</b> podocytes with slit diaphragms (prevents albumin). Substances "
    "freely filtered: electrolytes, glucose, urea, creatinine, amino acids. Proteins and "
    "protein-bound molecules are retained."
))
story.append(spacer(0.2))

story.append(sub_header("Starling Forces – Net Filtration Pressure"))
story.append(starling_forces_diagram())
story.append(Paragraph("Fig 2. Starling forces governing net glomerular filtration pressure (~10 mmHg)", ST_CAPTION))
story.append(spacer(0.2))

story.append(make_table(
    ["Force", "Value", "Direction", "Altered by"],
    [
        ["Glomerular capillary hydrostatic pressure (Pgc)", "~60 mmHg",
         "Promotes filtration", "Afferent/efferent arteriole tone, BP"],
        ["Bowman's capsule hydrostatic pressure (Pbs)", "~18 mmHg",
         "Opposes filtration", "Urinary obstruction, ureteral stones"],
        ["Glomerular oncotic pressure (pgc)", "~32 mmHg",
         "Opposes filtration", "Plasma protein levels, filtration fraction"],
        ["Net filtration pressure", "~10 mmHg",
         "Promotes filtration", "Sum of above"],
        ["GFR = Kf x NFP", "~125 mL/min",
         "—", "Kf reduced in glomerular disease"],
    ],
    col_widths=[5.5*cm, 2.5*cm, 3.5*cm, 5*cm]
))
story.append(formula("GFR = Kf × (Pgc – Pbs – πgc)  =  Kf × ~10 mmHg  =  ~125 mL/min"))
story.append(spacer(0.2))

story.append(sub_header("Renal Autoregulation (MAP 80–180 mmHg)"))
story.append(make_table(
    ["Mechanism", "Trigger", "Response"],
    [
        ["Myogenic", "Stretch of afferent arteriole wall from ↑BP",
         "Vasoconstriction of afferent arteriole → maintains GFR"],
        ["Tubuloglomerular feedback (TGF)", "Macula densa senses ↑NaCl delivery to DCT",
         "ATP/adenosine → afferent arteriolar constriction → ↓GFR"],
    ],
    col_widths=[4*cm, 6*cm, 6.5*cm]
))
story.append(spacer(0.2))

story.append(sub_header("Factors Altering GFR"))
story.append(make_table(
    ["Increases GFR", "Decreases GFR"],
    [
        ["Afferent arteriole dilation (prostaglandins, ANP)",
         "Afferent arteriole constriction (sympathetic NS, Ang II high dose)"],
        ["↑ Blood pressure (within autoregulation)",
         "Efferent arteriole dilation (ACE inhibitors → ↓ efferent resistance)"],
        ["↓ Plasma oncotic pressure",
         "↑ Bowman's capsule pressure (obstruction)"],
        ["Efferent arteriole constriction (low-dose Ang II)",
         "↓ Kf (glomerulonephritis, diabetic nephropathy)"],
    ],
    col_widths=[8*cm, 8.5*cm]
))
story.append(PageBreak())

# ══════════════════════ SECTION 3: TUBULAR FUNCTION ══════════════════════
story.append(section_header("3.  Tubular Reabsorption &amp; Secretion", GREEN, ""))
story.append(spacer(0.2))
story.append(formula("Urinary Excretion = Glomerular Filtration − Reabsorption + Secretion"))
story.append(spacer(0.2))

story.append(sub_header("Proximal Convoluted Tubule (PCT)"))
story.append(info_box("PCT Reabsorbs ~65–70% of Filtered Load", [
    "Na+, Cl-, K+, HCO3-, water (all ~65-70%)",
    "Glucose: ~100% (via SGLT1/SGLT2 cotransporters with Na+)",
    "Amino acids: ~100% (via Na+-amino acid cotransporters)",
    "Urea: ~50% (passive diffusion)",
    "Reabsorption is ISOSMOTIC – fluid remains ~300 mOsm/L throughout PCT",
], bg=LIGHT_GREEN, border=GREEN))
story.append(spacer(0.2))
story.append(body(
    "<b>Mechanism:</b> Basolateral Na+/K+-ATPase pumps 3 Na+ out and 2 K+ in, maintaining "
    "low intracellular Na+. This gradient drives Na+ entry from lumen via: "
    "(1) Na+-glucose cotransporter (SGLT2) – site of SGLT2 inhibitor action; "
    "(2) Na+/H+ antiporter – couples Na+ entry with H+ secretion, reclaiming HCO3-; "
    "(3) Na+-amino acid cotransporters. Water follows Na+ via AQP1 channels (always open)."
))
story.append(spacer(0.2))
story.append(key_point("Glucose Tm: Transport maximum ~375 mg/min. Renal threshold ~180 mg/dL plasma glucose → glucosuria in diabetes."))
story.append(spacer(0.2))

story.append(sub_header("Loop of Henle"))
story.append(make_table(
    ["Segment", "Na+/Solute Transport", "Water Permeability", "Net Effect on Fluid"],
    [
        ["Thin descending limb", "No active transport; some Na+ entry",
         "High (AQP1 present)", "Water leaves; fluid becomes HYPERTONIC (up to 1200 mOsm)"],
        ["Thin ascending limb", "Passive NaCl diffusion out",
         "Impermeable", "Solute out, no water – slight dilution"],
        ["THICK ascending limb (TAL)", "Active Na+/K+/2Cl- cotransport (NKCC2) – FUROSEMIDE site",
         "IMPERMEABLE (no AQP)", "Fluid dilutes to ~100 mOsm (DILUTING SEGMENT)"],
    ],
    col_widths=[3.5*cm, 5*cm, 3.5*cm, 5*cm]
))
story.append(spacer(0.2))

story.append(sub_header("Distal Convoluted Tubule (DCT)"))
story.append(body(
    "Reabsorbs Na+ and Cl- via the <b>NaCl cotransporter (NCC)</b> on the apical membrane – "
    "this is the site of action of <b>thiazide diuretics</b>. The DCT is water-impermeable "
    "in its early portion, continuing the dilution of tubular fluid. Late DCT responds to "
    "aldosterone. Fluid enters DCT at ~100 mOsm/L."
))
story.append(spacer(0.2))

story.append(sub_header("Collecting Duct – Final Fine-Tuning"))
story.append(make_table(
    ["Cell Type", "Apical Transporter", "Hormone", "Function"],
    [
        ["Principal cell", "ENaC (Na+ in), ROMK (K+ out), AQP2 (water)",
         "Aldosterone (Na+); ADH (water)", "Na+ reabsorption, K+ secretion, water reabsorption"],
        ["Alpha-intercalated cell", "H+-ATPase (H+ out), Cl-/HCO3- exchanger",
         "Acidosis stimulates", "H+ secretion; acid-base regulation"],
        ["Beta-intercalated cell", "Cl-/HCO3- exchanger (apical)",
         "Alkalosis stimulates", "HCO3- secretion; acid-base regulation"],
    ],
    col_widths=[3.5*cm, 5.5*cm, 3.5*cm, 4*cm]
))
story.append(PageBreak())

# ══════════════════════ SECTION 4: COUNTERCURRENT ══════════════════════
story.append(section_header("4.  Loop of Henle &amp; Countercurrent Mechanism", ORANGE, ""))
story.append(spacer(0.2))
story.append(body(
    "The countercurrent system creates and maintains a <b>hyperosmotic renal medullary "
    "interstitium</b> (up to 1200–1400 mOsm/L at the papillary tip vs. 300 mOsm/L in the "
    "cortex). This gradient is the essential prerequisite for producing concentrated urine."
))
story.append(spacer(0.3))
story.append(countercurrent_diagram())
story.append(Paragraph(
    "Fig 3. Countercurrent multiplier showing osmolarity values (mOsm/L) in each tubular segment",
    ST_CAPTION
))
story.append(spacer(0.2))

story.append(sub_header("How the Gradient is Built – Four Factors"))
story.append(make_table(
    ["Factor", "Mechanism", "Contribution"],
    [
        ["NKCC2 pump in thick ALH",
         "Active Na+/K+/2Cl- transport out of the thick ascending limb (impermeable to water)",
         "Primary driver – adds solute without water to medulla"],
        ["Urea recycling",
         "Inner medullary collecting duct (with ADH) reabsorbs urea via UT-A1/UT-A3 transporters",
         "Adds ~500 mOsm to inner medulla"],
        ["Thin descending limb",
         "Water exits down osmotic gradient into hypertonic interstitium via AQP1",
         "Concentrates tubular fluid delivered to bend"],
        ["Vasa recta (countercurrent exchanger)",
         "Descending vasa recta takes up solute; ascending loses it back – hairpin arrangement",
         "Prevents washout of medullary gradient"],
    ],
    col_widths=[3.5*cm, 7*cm, 6*cm]
))
story.append(spacer(0.3))
story.append(info_box("Clinical Pearl", [
    "Loop diuretics (furosemide, bumetanide) block NKCC2 in the thick ALH",
    "This destroys the medullary concentration gradient",
    "Collecting duct cannot concentrate urine even with maximal ADH → massive diuresis",
    "Also causes K+ wasting (reduces K+ recycling in TAL driving ROMK secretion)",
], bg=LIGHT_RED, border=RED))
story.append(PageBreak())

# ══════════════════════ SECTION 5: ADH / CONCENTRATION ══════════════════════
story.append(section_header("5.  Urine Concentration &amp; Dilution (ADH)", PURPLE, ""))
story.append(spacer(0.2))
story.append(sub_header("ADH (Vasopressin) Mechanism"))
story.append(body(
    "ADH is produced in the <b>supraoptic and paraventricular nuclei of the hypothalamus</b> "
    "and released from the posterior pituitary. It acts via V2 receptors on collecting duct "
    "principal cells → activates adenylyl cyclase → ↑cAMP → PKA → phosphorylation of "
    "AQP2 vesicles → insertion of <b>aquaporin-2 (AQP2)</b> into the apical membrane → "
    "collecting duct becomes water-permeable → water moves out into hypertonic medulla."
))
story.append(spacer(0.2))

story.append(make_table(
    ["Condition", "ADH Level", "Collecting Duct", "Urine Osmolarity", "Urine Volume"],
    [
        ["Dehydration / ↑plasma osmolarity", "HIGH", "Permeable (AQP2 inserted)",
         "Up to 1200–1400 mOsm/L", "Low (~500 mL/day)"],
        ["Overhydration / ↓plasma osmolarity", "LOW", "Impermeable (AQP2 absent)",
         "As low as 50–100 mOsm/L", "High (up to 20 L/day)"],
    ],
    col_widths=[4.5*cm, 2*cm, 4*cm, 4*cm, 3*cm]
))
story.append(spacer(0.2))

story.append(sub_header("Stimuli for ADH Release"))
story.append(make_table(
    ["Stimulus", "Sensor", "Effect"],
    [
        ["↑ Plasma osmolarity (>280 mOsm)", "Osmoreceptors in anterior hypothalamus",
         "Primary regulator – even 1–2% change triggers ADH"],
        ["↓ Blood volume/pressure", "Baroreceptors (carotid, atria)", 
         "Requires >8–10% volume loss; more potent override"],
        ["Nausea, pain, stress", "CNS", "Stimulate ADH even at normal osmolarity"],
        ["Alcohol", "Hypothalamus", "INHIBITS ADH → diuresis (hence frequent urination with alcohol)"],
    ],
    col_widths=[5*cm, 5*cm, 6.5*cm]
))
story.append(spacer(0.2))

story.append(info_box("Diabetes Insipidus (DI) – Key Distinction", [
    "Central DI: ADH not produced/released (hypothalamic/pituitary damage) → massive hypotonic polyuria",
    "Nephrogenic DI: ADH present but collecting duct V2 receptors/AQP2 dysfunctional",
    "SIADH: Excess ADH → water retention → dilutional hyponatremia → concentrated urine",
    "Desmopressin (synthetic ADH) treats Central DI; corrects urine in CDI but not nephrogenic DI",
], bg=LIGHT_PURPLE, border=PURPLE))
story.append(PageBreak())

# ══════════════════════ SECTION 6: HORMONES ══════════════════════
story.append(section_header("6.  Hormonal Regulation of Renal Function", RED, ""))
story.append(spacer(0.2))
story.append(sub_header("Renin-Angiotensin-Aldosterone System (RAAS)"))
story.append(raas_diagram())
story.append(Paragraph("Fig 4. RAAS cascade from renin release to aldosterone effects", ST_CAPTION))
story.append(spacer(0.2))

story.append(make_table(
    ["Step", "Location", "What Happens"],
    [
        ["Renin release", "JG cells of afferent arteriole",
         "Triggered by: ↓ BP (stretch), ↓ NaCl at macula densa, ↑ sympathetic (beta-1)"],
        ["Angiotensinogen → Ang I", "Liver (angiotensinogen) + plasma",
         "Renin cleaves angiotensinogen to Ang I (inactive decapeptide)"],
        ["Ang I → Ang II", "Lung endothelium (ACE)",
         "ACE converts Ang I to Ang II (active octapeptide). ACE inhibitors block here"],
        ["Ang II effects", "Multiple organs",
         "(1) PCT: ↑ Na+/H+ antiporter → ↑ Na+ reabsorption; (2) Adrenal: → aldosterone; "
         "(3) Vasoconstriction; (4) ↑ ADH; (5) Thirst"],
        ["Aldosterone", "Collecting duct principal cells",
         "↑ ENaC and Na+/K+-ATPase → ↑ Na+ reabsorption, ↑ K+ secretion, water follows → ↑ BP"],
    ],
    col_widths=[3.5*cm, 4*cm, 9*cm]
))
story.append(spacer(0.2))

story.append(sub_header("Other Key Hormones"))
story.append(make_table(
    ["Hormone", "Source", "Renal Action", "Net Effect"],
    [
        ["ANP (Atrial Natriuretic Peptide)", "Atria (↑stretch)",
         "Dilates afferent, constricts efferent → ↑GFR; ↓ renin; ↓ aldosterone; ↓ ADH",
         "Natriuresis + diuresis → ↓ blood volume"],
        ["PTH (Parathyroid Hormone)", "Parathyroid glands",
         "↑ Ca2+ reabsorption (DCT); ↓ phosphate reabsorption (PCT); "
         "activates 1α-hydroxylase → active Vit D",
         "↑ serum Ca2+, ↓ serum phosphate"],
        ["Dopamine", "Proximal tubule cells",
         "↓ Na+/K+-ATPase and NHE3 in PCT; ↓ aldosterone",
         "Natriuresis; used in low doses for renal protection"],
        ["Prostaglandins (PGE2)", "Renal medulla",
         "Dilate afferent arteriole → maintain GFR; antagonize ADH in collecting duct",
         "NSAIDs block → ↓ GFR, water retention"],
    ],
    col_widths=[3.5*cm, 3.5*cm, 6.5*cm, 3*cm]
))
story.append(PageBreak())

# ══════════════════════ SECTION 7: SPECIFIC SUBSTANCES ══════════════════════
story.append(section_header("7.  Renal Handling of Key Substances", NAVY, ""))
story.append(spacer(0.2))
story.append(make_table(
    ["Substance", "Filtered?", "PCT", "Loop of Henle", "DCT / CD", "Net Excretion"],
    [
        ["Sodium (Na+)", "Yes", "65-70% reabsorbed (Na+/K+-ATPase, NHE3, SGLT)",
         "25% TAL (NKCC2)", "~5% (aldosterone-regulated ENaC)", "<1%"],
        ["Glucose", "Yes", "~100% (SGLT1/2, Tm-limited)",
         "–", "–", "0 (unless >Tm)"],
        ["Potassium (K+)", "Yes", "65% reabsorbed",
         "25% reabsorbed (TAL via ROMK recycling)", "Secreted by principal cells (aldosterone)",
         "Variable; ~15% normally"],
        ["Urea", "Yes", "~50% reabsorbed (passive)",
         "Secreted (thin ALH)", "Reabsorbed (inner MCD, UT-A1 with ADH)", "~50%"],
        ["Creatinine", "Yes", "Minimal reabsorption",
         "–", "Small secretion", "~100% of filtered"],
        ["Bicarbonate (HCO3-)", "Yes", "80-90% reabsorbed (NHE3 + carbonic anhydrase)",
         "~5% TAL", "Final titration (intercalated cells)", "Very little (normal pH)"],
        ["Calcium (Ca2+)", "Yes (40% free)", "65% passive paracellular",
         "25% (TAL – paracellular, driven by lumen +ve potential)", 
         "Active transcellular (PTH-stimulated)", "<2%"],
        ["Phosphate", "Yes", "85% reabsorbed (NaPi-IIa cotransporter – inhibited by PTH)",
         "–", "–", "15% normally"],
        ["Uric acid", "Yes", "Reabsorbed AND secreted (net reabsorption 90%)",
         "–", "–", "~10%"],
        ["H+ (acid)", "–", "Secreted (NHE3 → reclaims HCO3-)",
         "–", "Secreted (H+-ATPase in intercalated cells)", "~80 mEq/day"],
    ],
    col_widths=[2.8*cm, 1.5*cm, 4.2*cm, 3*cm, 3.5*cm, 2.5*cm]
))
story.append(PageBreak())

# ══════════════════════ SECTION 8: ACID-BASE ══════════════════════
story.append(section_header("8.  Renal Acid–Base Balance", colors.HexColor("#6c3483"), ""))
story.append(spacer(0.2))
story.append(body(
    "The kidneys are the <b>long-term</b> regulators of body pH (lungs handle short-term CO2). "
    "Normal arterial pH = 7.35–7.45. The kidneys excrete ~80 mEq of fixed acid per day "
    "through three mechanisms:"
))
story.append(spacer(0.2))

story.append(make_table(
    ["Mechanism", "Where", "How It Works", "Significance"],
    [
        ["HCO3- Reabsorption", "PCT (~85%), TAL (~5%), CD",
         "H+ secreted via NHE3 (PCT) reacts with filtered HCO3-; "
         "carbonic anhydrase: H2CO3 → CO2+H2O; CO2 enters cell → reforms HCO3- → "
         "exits basolaterally. NET: reclaims filtered bicarbonate",
         "Not true acid excretion; reclaims bicarbonate buffer"],
        ["Titratable Acid (TA)", "Collecting duct",
         "H+ secreted by H+-ATPase combines with HPO4(2-) → H2PO4(-), "
         "which is excreted. Each H+ excreted regenerates 1 HCO3-",
         "~30-40 mEq/day; limited by phosphate availability"],
        ["Ammonium (NH4+)", "PCT generates NH3; CD secretes into lumen",
         "Glutamine → glutaminase → NH3 + H+ → NH4+ (trapped in lumen). "
         "Medullary recycling amplifies delivery to collecting duct",
         "~40-50 mEq/day; upregulated in chronic acidosis; most important buffer"],
    ],
    col_widths=[3.5*cm, 2.5*cm, 7*cm, 3.5*cm]
))
story.append(spacer(0.2))

story.append(sub_header("Renal Compensation for Acid-Base Disorders"))
story.append(make_table(
    ["Disorder", "Primary Change", "Renal Compensation", "Time Course"],
    [
        ["Metabolic Acidosis", "↓ HCO3-", "↑ H+ secretion; ↑ NH4+ production; ↑ HCO3- generation",
         "Hours to days"],
        ["Metabolic Alkalosis", "↑ HCO3-", "↓ H+ secretion; ↑ HCO3- excretion (bicarbonaturia)",
         "Hours to days"],
        ["Respiratory Acidosis", "↑ PaCO2", "↑ H+ secretion; ↑ NH4+; ↑ HCO3- reabsorption",
         "2-5 days"],
        ["Respiratory Alkalosis", "↓ PaCO2", "↓ H+ secretion; ↑ HCO3- excretion",
         "2-5 days"],
    ],
    col_widths=[4*cm, 3*cm, 6.5*cm, 3*cm]
))
story.append(PageBreak())

# ══════════════════════ SECTION 9: CLEARANCE ══════════════════════
story.append(section_header("9.  Renal Clearance", GREEN, ""))
story.append(spacer(0.2))
story.append(formula("Clearance (C) = (Urine concentration × Urine flow rate) ÷ Plasma concentration = U×V / P"))
story.append(body(
    "<b>Clearance</b> represents the volume of plasma completely cleared of a substance per unit time. "
    "Comparing a substance's clearance to inulin clearance (= GFR) reveals whether it is "
    "reabsorbed, secreted, or neither."
))
story.append(spacer(0.2))

story.append(make_table(
    ["Substance", "Clearance (mL/min)", "Interpretation"],
    [
        ["Glucose",     "0",     "Fully reabsorbed below Tm"],
        ["Sodium",      "~0.9",  "Mostly reabsorbed; <1% excreted"],
        ["Urea",        "~70",   "Partly reabsorbed (clearance < GFR)"],
        ["Inulin",      "125",   "= GFR (gold standard – filtered only, not absorbed/secreted)"],
        ["Creatinine",  "~140",  "Slightly > GFR (some tubular secretion)"],
        ["PAH",         "~650",  "= Renal Plasma Flow (RPF) – nearly fully secreted"],
    ],
    col_widths=[4*cm, 4*cm, 8.5*cm]
))
story.append(spacer(0.2))

story.append(make_table(
    ["Derived Value", "Formula", "Normal Value"],
    [
        ["GFR", "Inulin clearance = Uin×V / Pin", "~125 mL/min"],
        ["Renal Plasma Flow (RPF)", "PAH clearance = UPAH×V / PPAH", "~650 mL/min"],
        ["Renal Blood Flow (RBF)", "RPF / (1 - Hematocrit)", "~1200 mL/min (~20% cardiac output)"],
        ["Filtration Fraction (FF)", "GFR / RPF", "~0.19 (19%)"],
    ],
    col_widths=[4.5*cm, 6.5*cm, 5.5*cm]
))
story.append(spacer(0.2))

story.append(info_box("Creatinine Clearance – Clinical Use", [
    "Endogenous creatinine clearance ~140 mL/min (slight overestimate of GFR due to tubular secretion)",
    "Cockcroft-Gault formula: CrCl = [(140 - age) x weight(kg)] / [72 x serum Cr(mg/dL)]  (x 0.85 for females)",
    "eGFR by CKD-EPI equation now preferred in clinical practice",
    "CKD staging: G1 (>90), G2 (60-89), G3a (45-59), G3b (30-44), G4 (15-29), G5 (<15 mL/min/1.73m2)",
], bg=LIGHT_GREEN, border=GREEN))
story.append(PageBreak())

# ══════════════════════ SECTION 10: QUICK REFERENCE ══════════════════════
story.append(section_header("10.  Quick-Reference Tables &amp; Key Values", GOLD, ""))
story.append(spacer(0.2))

story.append(sub_header("Normal Renal Parameters"))
story.append(make_table(
    ["Parameter", "Normal Value"],
    [
        ["GFR",                           "125 mL/min (180 L/day)"],
        ["Renal Plasma Flow (RPF)",        "~650 mL/min"],
        ["Renal Blood Flow (RBF)",         "~1200 mL/min (20-25% cardiac output)"],
        ["Filtration Fraction",            "~19%"],
        ["Daily urine output",             "1-2 L/day"],
        ["Urine osmolarity range",         "50-1400 mOsm/L"],
        ["Plasma osmolarity",              "275-295 mOsm/L"],
        ["Maximum urine concentration",    "~1200-1400 mOsm/L (medullary tip)"],
        ["Normal serum creatinine",        "0.6-1.2 mg/dL (men); 0.5-1.1 (women)"],
        ["Normal GFR threshold for glucosuria", "Plasma glucose >180-200 mg/dL"],
    ],
    col_widths=[8*cm, 8.5*cm]
))
story.append(spacer(0.2))

story.append(sub_header("Diuretic Sites of Action"))
story.append(make_table(
    ["Diuretic Class", "Site", "Transporter Blocked", "Key Effects"],
    [
        ["Carbonic anhydrase inhibitors\n(Acetazolamide)",
         "PCT",
         "Carbonic anhydrase → ↓ H+ secretion → ↓ HCO3- reclamation",
         "Bicarbonaturia; metabolic acidosis; weak diuresis"],
        ["Osmotic diuretics\n(Mannitol)",
         "PCT + Descending LOH",
         "Not a transporter; limits passive water reabsorption",
         "↑ urine volume; reduces cerebral edema"],
        ["Loop diuretics\n(Furosemide, Bumetanide)",
         "Thick ascending LOH",
         "NKCC2 (Na+/K+/2Cl-)",
         "Most potent; destroys medullary gradient; Ca2+ and Mg2+ wasting; K+ wasting"],
        ["Thiazides\n(Hydrochlorothiazide)",
         "Early DCT",
         "NCC (Na+/Cl-)",
         "Moderate diuresis; K+ wasting; Ca2+ RETENTION (useful in hypercalciuria/stones)"],
        ["K+-sparing diuretics\n(Spironolactone, Amiloride)",
         "Collecting duct",
         "Spiro: blocks aldosterone receptor; Amiloride: blocks ENaC",
         "Weak diuresis; hyperkalemia risk; no K+ wasting"],
        ["V2 receptor antagonists\n(Tolvaptan – 'Vaptans')",
         "Collecting duct",
         "V2 receptor → blocks AQP2 insertion",
         "Aquaresis (free water excretion); treats hyponatremia in SIADH/CHF"],
    ],
    col_widths=[3.5*cm, 2.5*cm, 4.5*cm, 6*cm]
))
story.append(spacer(0.2))

story.append(sub_header("Tubular Transport Mechanisms Summary"))
story.append(make_table(
    ["Transporter", "Location", "Moves", "Blocked By"],
    [
        ["Na+/K+-ATPase", "Basolateral (all segments)", "3Na+ out, 2K+ in", "Ouabain (experimentally)"],
        ["SGLT2 / SGLT1", "PCT apical", "Na+ + Glucose cotransport", "Gliflozins (SGLT2i – empagliflozin etc.)"],
        ["NHE3 (Na+/H+ antiporter)", "PCT apical", "Na+ in, H+ out", "Carbonic anhydrase inhibitors (indirectly)"],
        ["NKCC2", "Thick ALH apical", "Na+, K+, 2Cl- in", "Loop diuretics (furosemide)"],
        ["NCC", "DCT apical", "Na+, Cl- in", "Thiazides"],
        ["ENaC", "Collecting duct apical", "Na+ in", "Amiloride, spironolactone (indirectly)"],
        ["AQP1", "PCT + descending LOH", "Water (constitutive)", "Not regulated"],
        ["AQP2", "Collecting duct apical", "Water (regulated)", "Blocked by absence of ADH; tolvaptan"],
        ["H+-ATPase", "Intercalated cells apical", "H+ secretion", "—"],
    ],
    col_widths=[3.5*cm, 4*cm, 4.5*cm, 4.5*cm]
))
story.append(PageBreak())

# ══════════════════════ BACK PAGE: MNEMONICS & PEARLS ══════════════════════
story.append(section_header("Clinical Pearls &amp; Mnemonics", colors.HexColor("#1a5276"), ""))
story.append(spacer(0.2))

pearls = [
    ("GFR Memory Aid",
     ["180 L/day filtered, ~1.5 L excreted = 99%+ reabsorption",
      "125 mL/min = normal adult GFR (memorize this number)",
      "Creatinine clearance slightly overestimates GFR (tubular secretion adds ~10%)"]),
    ("Thick ALH = The 'Diluting Segment'",
     ["Pumps NaCl OUT (NKCC2), water stays in (impermeable)",
      "Fluid exits at ~100 mOsm – HYPOTONIC despite being in hypertonic medulla",
      "This is why loop diuretics are the most powerful – they destroy the gradient"]),
    ("Aldosterone vs. ADH",
     ["Aldosterone: controls Na+ (and hence VOLUME). 'Aldo controls Amount'",
      "ADH: controls water (and hence OSMOLARITY). 'ADH controls dilution/concentration'",
      "Both act on collecting duct but are independently regulated"]),
    ("ACE Inhibitors / ARBs & GFR",
     ["Block Ang II → dilate efferent arteriole → ↓ GFR",
      "Beneficial in proteinuria (↓ glomerular hypertension) but dangerous in renal artery stenosis",
      "Serum creatinine may rise 10-20% initially – acceptable and even expected"]),
    ("Potassium Handling Mnemonic",
     ["PCT + LOH = Reabsorb K+",
      "DCT/CD principal cells = Secrete K+ (under aldosterone)",
      "↑ aldosterone → ↑ K+ loss → hypokalemia",
      "K+-sparing diuretics (spiro, amiloride) prevent this loss"]),
    ("Starling Forces Memory: '60 opposes 50'",
     ["Promoting filtration: Pgc = 60 mmHg",
      "Opposing: Pbs (18) + pgc (32) = 50 mmHg",
      "Net = 60 - 50 = 10 mmHg promoting filtration"]),
]

for (title, pts) in pearls:
    bg = LIGHT_BLUE if pearls.index((title,pts)) % 2 == 0 else LIGHT_GREEN
    story.append(info_box(title, pts, bg=bg, border=TEAL))
    story.append(spacer(0.2))

# Footer note
story.append(hr(GRAY))
story.append(Paragraph(
    "<i>Study Guide compiled from Guyton &amp; Hall Textbook of Medical Physiology 14E, "
    "Ganong's Review of Medical Physiology 26E, Costanzo Physiology 7E, and "
    "Brenner &amp; Rector's The Kidney. For educational use only.</i>",
    ST_CAPTION
))

# ─────────────────────────────────────────────────────────
# Build
# ─────────────────────────────────────────────────────────
doc.build(story)
print(f"PDF created: {OUTPUT}")
print(f"Size: {os.path.getsize(OUTPUT):,} bytes")
Running Command

cd /home/daytona/workspace/renal-physiology-guide && python3 create_pdf.py 2>&1

Editing File

~/renal-physiology-guide/create_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/renal-physiology-guide/create_pdf.py'
Running Command

cd /home/daytona/workspace/renal-physiology-guide && python3 create_pdf.py 2>&1

Running Command

python3 -c " from pypdf import PdfReader r = PdfReader('/home/daytona/workspace/…

Your comprehensive Renal Physiology Study Guide PDF is ready - 16 pages, fully verified.

Renal Physiology Study Guide

PDF Document · PDF


Here is what the guide covers across 16 pages:
Page 1 - Cover + Table of Contents
  • Colour-coded contents with all 10 sections listed
Pages 2-3 - Functional Anatomy
  • Nephron types (cortical vs. juxtamedullary), blood supply, two-capillary-bed system
  • Nephron flow diagram with osmolarity values at each segment
Pages 3-4 - Glomerular Filtration & GFR
  • Starling forces diagram with actual values (Pgc, Pbs, πgc)
  • Factors increasing/decreasing GFR table
  • Renal autoregulation (myogenic + TGF)
Pages 5-6 - Tubular Reabsorption & Secretion
  • PCT (Na+/K+-ATPase, SGLT2, NHE3, glucose Tm concept)
  • Loop of Henle segment-by-segment table
  • DCT and collecting duct cell types (principal, intercalated)
Pages 7-8 - Countercurrent Mechanism
  • Countercurrent multiplier diagram with mOsm/L values
  • How the gradient is built (4 factors including urea recycling)
  • Loop diuretic clinical pearl box
Pages 8-9 - ADH & Urine Concentration
  • ADH mechanism (V2 → cAMP → AQP2)
  • With/without ADH comparison table
  • DI vs. SIADH info box
Pages 9-10 - Hormonal Regulation
  • RAAS cascade diagram (JG cells → renin → Ang I → Ang II → aldosterone)
  • ANP, PTH, dopamine, prostaglandins table
Page 11 - Renal Handling of Key Substances
  • Full table: Na+, glucose, K+, urea, creatinine, HCO3-, Ca2+, phosphate, H+
Pages 12-13 - Acid-Base Balance & Clearance
  • Three acid excretion mechanisms; renal compensation table
  • Clearance formula; inulin/PAH/creatinine values; CKD staging
Pages 14-15 - Quick Reference Tables
  • Normal renal parameters; diuretic sites of action (6 classes); all key transporters
Page 16 - Clinical Pearls & Mnemonics
  • 6 high-yield memory aids for exams
This is a shared conversation. Sign in to Orris to start your own chat.