Sexual dysfunction and Infertility make short notes on exam oriented 1.Order and interpret relevant investigations of Sexual dysfunction and Infertility 2. Describe differential diagnosis of Sexual dysfunction and Infertility

Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Finding Sources
Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
I now have comprehensive material from multiple authoritative textbooks. Let me compile the complete exam-oriented short notes.

SHORT NOTES: Sexual Dysfunction & Infertility

Exam-Oriented Review


PART 1: SEXUAL DYSFUNCTION

Definition & Classification

Sexual dysfunction = persistent disturbance in the normal sexual response cycle causing personal distress.
DomainMaleFemale
DesireHypoactive sexual desire disorder (HSDD)HSDD
ArousalErectile dysfunction (ED)Female sexual arousal disorder
OrgasmPremature/delayed ejaculation, anorgasmiaOrgasmic disorder
PainDyspareuniaDyspareunia, vaginismus
(Campbell-Walsh-Wein Urology)

ERECTILE DYSFUNCTION (ED) - Most Testable

Definition (AUA/NIH): Inability to attain and/or maintain penile erection sufficient for satisfactory intercourse. Affects >50% of men over age 40.

Causes (Differential Diagnosis)

CategoryExamples
Vasculogenic (most common)Atherosclerosis, hypertension, dyslipidemia, diabetes (vasculopathy)
NeurogenicDM (peripheral neuropathy), MS, spinal cord injury, pelvic surgery (radical prostatectomy)
PsychogenicDepression, anxiety, relationship problems, performance anxiety
EndocrinologicHypogonadism (low testosterone), hyperprolactinemia, hypothyroidism
Medication-inducedAntihypertensives (beta-blockers, thiazides), antidepressants (SSRIs), antipsychotics
StructuralPeyronie's disease, penile trauma
Key differentiating clue: Situational ED (erection with one partner but not another, or adequate nocturnal tumescence) = psychogenic cause. Absent nocturnal erections = organic cause.
ED can be a harbinger of occult coronary artery disease - always consider cardiology referral.

Investigations of Erectile Dysfunction

1. Validated Questionnaires (first step)
  • IIEF (International Index of Erectile Function) - gold standard questionnaire; assesses erectile function, orgasm, desire, intercourse satisfaction
  • IIEF-6 / SHIM (Sexual Health Index for Men) - abbreviated version
  • ADAM questionnaire, Aging Male Survey - for hypogonadism screening
2. Basic Laboratory Tests
TestPurpose
Serum total testosteroneScreen for hypogonadism (low testosterone)
Free/bioavailable testosteronePortion not bound to SHBG - more accurate
LH, FSHDistinguish primary vs secondary hypogonadism
Serum prolactinIf low testosterone identified - rule out prolactinoma
FBS/HbA1cScreen for diabetes mellitus
Lipid profileScreen for vascular risk factors
TSHRule out thyroid disorders
Serum estradiolIf gynecomastia or feminization present
3. Specialized Tests
TestPurpose
Nocturnal Penile Tumescence (NPT)Differentiates organic from psychogenic ED; normal NPT = psychogenic
Intracavernosal injection testPapaverine/PGE1 injection - erection = no vascular disease
Penile Doppler ultrasoundEvaluates arterial inflow and venous occlusion
Pudendal arteriographyBefore vascular surgery
Cavernosometry/cavernosographyVenous leak evaluation
Neurophysiologic testingBulbocavernosus reflex, penile biothesiometry

OTHER SEXUAL DYSFUNCTION TYPES

Premature Ejaculation (PE)

  • Definition (ISSM): Ejaculation in <1 minute (lifelong) or <3 minutes (acquired), with inability to delay and negative personal consequence
  • Median normal IELT: 5.4 minutes (multicountry study)
  • Treatment: Behavioral (squeeze/stop-start technique), SSRIs (dapoxetine), topical anesthetics

Loss of Libido

  • Often due to hypogonadism, depression, medications, severe illness
  • Investigate with testosterone, prolactin, gonadotropins

Female Sexual Dysfunction

  • Hypoactive sexual desire disorder (HSDD) - most common in women
  • Vaginismus - involuntary vaginal spasm, can be primary or secondary
  • Dyspareunia - painful intercourse (consider endometriosis, atrophic vaginitis, vulvodynia)
  • Investigations: hormone levels (estrogen, testosterone, FSH), gynecologic exam, psychological assessment

PART 2: INFERTILITY

Definition

WHO definition: Failure to achieve a clinical pregnancy after 12 months of regular unprotected sexual intercourse. Evaluation warranted at 6 months for women ≥35 years.
(Goldman-Cecil Medicine)

Requirements for Pregnancy (Key Points)

  1. Male must produce adequate numbers of normal, motile spermatozoa
  2. Male must eject sperm through a patent ductal system
  3. Sperm must traverse an unobstructed female reproductive tract
  4. Female must ovulate and release an ovum
  5. Sperm must fertilize the ovum
  6. Fertilized ovum must implant in appropriately prepared endometrium

Differential Diagnosis / Causes of Infertility

Male Factors (~40% of cases)

CauseExamples
Decreased sperm productionVaricocele (most common treatable cause), testicular failure (Klinefelter syndrome XXY), cryptorchidism, endocrine disorders, mumps orchitis
Ductal obstructionPost-epididymal infection (Chlamydia, gonorrhea), congenital absence of vas deferens (CBAVD - associated with CFTR mutation/CF), post-vasectomy
Ejaculatory disturbancesRetrograde ejaculation (diabetes, prostate surgery), hypospadias, anejaculation
Abnormal semenInfection, abnormal volume (<1.5 mL or >6 mL), abnormal viscosity
ImmunologicAntisperm antibodies (sperm-immobilizing, sperm-agglutinating) - occur after blood-testis barrier disruption
Sexual problemsED, psychological causes

Female Factors

CauseApprox. Incidence
Tubal/peritoneal disease30-40%
Ovulatory disorders (PCOS most common)30-40%
Cervical/uterine factors10-15%
Unexplained infertility<10%
Minor ovulatory disturbances<5%
Vaginal factors (vaginismus, vaginitis)<5%
Immunologic factors<5%
Nutritional/metabolic (thyroid, DM)5%
(Goldman-Cecil Medicine, Table 218-6)

Specific Female Causes (Detail)

Fallopian Tube Disease:
  • Pelvic inflammatory disease (PID) - Chlamydia, gonorrhea
  • Endometriosis (causes peritoneal adhesions, blocks tubo-ovarian motility)
  • Post-peritonitis adhesions
  • Congenital anomalies
Anovulatory/Ovulatory Disorders:
  • PCOS (most common cause of oligo/anovulation)
  • Hypothalamic amenorrhea (weight loss, exercise, stress)
  • Hyperprolactinemia (prolactinoma)
  • Premature ovarian failure (FSH >40 IU/L)
  • Thyroid disease, Cushing syndrome
Uterine Factors:
  • Intrauterine synechiae = Asherman syndrome (after D&C, endometritis)
  • Leiomyomas (submucosal) and polyps
  • Uterine anomalies (bicornuate, septate uterus)
  • Destroyed endocervical glands (after surgery or infection)
Cervical Factors:
  • Hostile cervical mucus (anti-sperm antibodies, post-cone biopsy)

Investigations of Infertility

Step-by-Step Approach

Basic investigations (ordered in all couples):
  1. Semen analysis
  2. Confirmation of ovulation
  3. Documentation of tubal patency

A. Male Investigations

1. Semen Analysis (cornerstone)
WHO Normal ValuesThreshold
Volume≥1.5 mL
Concentration≥16 million/mL
Total motility≥42%
Progressive motility≥30%
Normal morphology (Kruger)≥4%
Vitality≥54% live
  • Azoospermia = no sperm on semen analysis
  • Oligospermia = low count, Asthenospermia = low motility, Teratospermia = abnormal morphology
  • Key: semen analysis represents probabilistic assessment - no single threshold absolutely discerns infertility from fertility (except azoospermia)
  • Sperm vitality stain - differentiates complete asthenospermia from necrospermia
  • Pyospermia vs immature germ cells - distinguished by laboratory staining
Interpretation of semen volume <1.0 mL - differential:
  • Ejaculatory ductal obstruction
  • Retrograde ejaculation
  • Congenital bilateral absence of vas deferens (CBAVD)
2. Hormonal Assessment
TestSignificance
Total testosteroneHypogonadism (primary or secondary)
Free testosterone/SHBGBioavailable fraction
LH, FSHPrimary (elevated) vs secondary (low) hypogonadism
ProlactinHyperprolactinemia suppresses GnRH axis
EstradiolIf gynecomastia present
  • Primary hypogonadism: low T + high LH/FSH (testicular failure - Klinefelter, mumps orchitis)
  • Secondary hypogonadism: low T + low/normal LH/FSH (hypothalamic/pituitary cause)
3. Genetic Testing
  • Karyotype - if azoospermia/severe oligospermia (Klinefelter = 47,XXY)
  • CFTR gene mutation - if CBAVD (risk of CF in offspring)
  • Y-chromosome microdeletions (AZF regions) - AZFa, AZFb, AZFc deletions
4. Imaging
  • Scrotal Doppler ultrasound - varicocele (dilated pampiniform plexus >3 mm), testicular volume (normal 15-20 mL)
  • Transrectal ultrasound (TRUS) - ejaculatory duct obstruction
  • Post-ejaculate urinalysis - retrograde ejaculation (sperm in urine)
5. Advanced Tests
  • Antisperm antibody test (immunobead or MAR test)
  • Testicular biopsy - obstructive vs non-obstructive azoospermia
  • Globozoospermia (round-headed sperm) = absent acrosome - treat with IVF/ICSI

B. Female Investigations

1. Ovulation Assessment
MethodDetails
Basal body temperature (BBT) chartBiphasic pattern = ovulation occurred
Serum progesterone (Day 21/mid-luteal)>30 nmol/L (>10 ng/mL) = ovulation confirmed; done 6-8 days before expected menses
LH surge (urine OPK)Positive = ovulation in ~24-36 hrs
Serial transvaginal ultrasoundGold standard - visualizes follicle growth and collapse
Endometrial biopsyNow rarely used; dating <3 days before menses (luteal phase assessment)
2. Ovarian Reserve Testing
TestInterpretation
Serum FSH (Day 2-3)>10-15 IU/L = diminished reserve
Estradiol (Day 2-3)>60-80 pg/mL = poor reserve
Anti-Mullerian hormone (AMH)Best marker of ovarian reserve; low = decreased reserve; not cycle-day dependent
Antral follicle count (AFC)By transvaginal USS; <5-7 = poor reserve
Clomiphene citrate challenge test (CCCT)FSH on Day 3 and Day 10; elevated Day 10 FSH = poor reserve
3. Tubal Patency Assessment
TestDetails
Hysterosalpingography (HSG)First-line; X-ray with contrast; shows tubal patency and uterine cavity outline; also has therapeutic effect (flushes tubes)
Sonohysterography (saline infusion sonography, SIS)Ultrasound + saline; good for uterine cavity
Laparoscopy with chromopertubationGold standard; direct visualization; dye passed through tubes; indicated if HSG abnormal or unexplained infertility; detects endometriosis, adhesions
HyCoSy (Hysterosalpingo-contrast sonography)Ultrasound alternative to HSG
4. Uterine Cavity Assessment
  • Hysteroscopy - gold standard for intrauterine pathology (polyps, fibroids, Asherman)
  • MRI pelvis - Mullerian anomalies, fibroids
5. Hormonal Profile (Female)
TestPurpose
TSHThyroid disorder - hypothyroidism causes anovulation
ProlactinHyperprolactinemia - suppresses ovulation
LH:FSH ratioLH:FSH >2:1 suggests PCOS
Androgens (free testosterone, DHEAS)PCOS, adrenal hyperplasia
Glucose/insulinPCOS with insulin resistance
17-OHPCongenital adrenal hyperplasia (CAH)
6. Immunologic Tests
  • Antisperm antibodies (cervical mucus/serum)
  • Antinuclear antibodies (autoimmune causes)
  • Antiphospholipid antibodies (recurrent pregnancy loss)

Summary Table: Investigations at a Glance

InvestigationMaleFemale
First-lineSemen analysisBBT chart / serum progesterone (Day 21)
Ovarian reserve-AMH, Day 3 FSH, AFC
HormonesT, LH, FSH, prolactinFSH, LH, estradiol, AMH, TSH, prolactin
AnatomicScrotal Doppler USSHSG, hysteroscopy, laparoscopy
GeneticKaryotype, CFTR, Y-microdeletionKaryotype
ImmunologicAntisperm antibodiesAntisperm Ab, antiphospholipid Ab

Differential Diagnosis Summary

Sexual Dysfunction - DDx

ConditionKey Feature
Psychogenic EDSituational, present with masturbation/morning erections, preserved NPT, young age, anxiety/depression
Vasculogenic EDAbsent morning erections, cardiovascular risk factors (DM, HTN, smoking), bilateral
Neurogenic EDHistory of DM neuropathy, spinal cord injury, pelvic surgery, MS
Endocrinogenic EDLow libido, fatigue, gynecomastia, decreased beard growth, low testosterone
Drug-induced EDTemporal relationship to new medication (antihypertensives, SSRIs, antiandrogens)
Premature ejaculationNormal erection, short IELT (<1-3 min), significant distress
Peyronie's diseasePenile curvature, painful erection, palpable plaque
Vaginismus (female)Involuntary vaginal muscle spasm, inability to allow penetration, normal libido
DyspareuniaPainful intercourse; DDx: endometriosis, atrophic vaginitis, vulvodynia, PID
HSDD (female)Loss of desire, may be hormonal (menopause, hyperprolactinemia) or psychosocial

Infertility - DDx (Male)

ConditionKey Lab Finding
Klinefelter syndrome (47,XXY)Azoospermia, elevated FSH/LH, low T, small testes
Obstructive azoospermiaNormal FSH, normal testis size, no sperm
Non-obstructive azoospermiaElevated FSH, small testes
VaricoceleOligoasthenoteratozoospermia (OAT), dilated pampiniform plexus
Retrograde ejaculationLow volume (<1 mL), sperm in post-ejaculate urine
CBAVDAbsent vas on exam, CFTR mutation, low volume acidic semen
HyperprolactinemiaLow T, low LH/FSH, elevated prolactin

Infertility - DDx (Female)

ConditionKey Feature
PCOSOligomenorrhea, LH:FSH >2:1, USS polycystic ovaries, elevated androgens
Hypothalamic amenorrheaLow BMI, athletes, stress, low FSH/LH/estrogen
Premature ovarian failureAge <40, hot flashes, high FSH (>40), low AMH
HyperprolactinemiaGalactorrhea, amenorrhea, MRI pituitary fossa
Tubal disease (PID sequelae)History of STI, HSG shows blocked tubes
EndometriosisDysmenorrhea, dyspareunia, CA-125 elevated (unreliable), laparoscopy gold standard
Asherman syndromePost-D&C/curettage, scanty/absent periods, hysteroscopy - synechiae
HypothyroidismIrregular cycles, anovulation, elevated TSH
Cervical factorAbnormal post-coital test, hostile mucus, history of cone biopsy
Unexplained infertilityAll tests normal; treat with superovulation + IUI or IVF

High-Yield Exam Points

  1. Infertility evaluation timing: 12 months (general), 6 months if woman ≥35 years
  2. Most common cause of male infertility: Varicocele
  3. Most common cause of female anovulatory infertility: PCOS
  4. Most common cause of female infertility overall: Tubal/peritoneal disease (30-40%)
  5. Gold standard for tubal patency: Laparoscopy with chromopertubation
  6. Best ovarian reserve marker: AMH (not cycle-day dependent)
  7. ED harbinger of: Occult coronary artery disease
  8. NPT test: Normal = psychogenic ED; Absent = organic ED
  9. CBAVD association: CFTR mutation (cystic fibrosis gene) - screen partner
  10. Asherman syndrome: Post-curettage synechiae causing anovulation/infertility
  11. Klinefelter syndrome (47,XXY): Most common genetic cause of male infertility/azoospermia
  12. Male factor contributes to: 40% solely, up to 50% as contributing factor
  13. Clomiphene citrate: First-line ovulation induction (antiestrogen, stimulates pituitary FSH/LH), start Day 3-5, 50 mg x 5 days

Sources: Campbell-Walsh-Wein Urology; Goldman-Cecil Medicine 2 Vol. Set; Berek & Novak's Gynecology

Notes

Asking for Preferences
Reading File
Running Command

ls /home/daytona/workspace/ 2>/dev/null || echo "workspace not found"

Running Command

mkdir -p /home/daytona/workspace/sexual-dysfunction-infertility

Writing File

~/sexual-dysfunction-infertility/generate_notes.py

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,
    HRFlowable, KeepTogether, PageBreak
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate

OUTPUT = "/home/daytona/workspace/sexual-dysfunction-infertility/Sexual_Dysfunction_Infertility_Notes.pdf"

# ── Colour palette ──────────────────────────────────────────────────────────
DARK_BLUE   = colors.HexColor("#1a3a5c")
MID_BLUE    = colors.HexColor("#2e6da4")
LIGHT_BLUE  = colors.HexColor("#ddeeff")
ACCENT      = colors.HexColor("#e8f4fd")
ORANGE      = colors.HexColor("#d45500")
GREEN       = colors.HexColor("#1a6b3c")
LIGHT_GREEN = colors.HexColor("#e8f5ee")
YELLOW_BG   = colors.HexColor("#fffbe6")
BORDER      = colors.HexColor("#b0c4de")
WHITE       = colors.white
LIGHT_GREY  = colors.HexColor("#f5f5f5")
TEXT        = colors.HexColor("#1c1c1c")

PAGE_W, PAGE_H = A4
MARGIN = 1.8*cm

# ── Page numbering ───────────────────────────────────────────────────────────
def header_footer(canvas, doc):
    canvas.saveState()
    # Header bar
    canvas.setFillColor(DARK_BLUE)
    canvas.rect(0, PAGE_H - 1.2*cm, PAGE_W, 1.2*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica-Bold", 9)
    canvas.drawString(MARGIN, PAGE_H - 0.8*cm, "EXAM NOTES: Sexual Dysfunction & Infertility")
    canvas.setFont("Helvetica", 9)
    canvas.drawRightString(PAGE_W - MARGIN, PAGE_H - 0.8*cm, f"Page {doc.page}")
    # Footer
    canvas.setFillColor(DARK_BLUE)
    canvas.rect(0, 0, PAGE_W, 0.8*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica-Oblique", 7)
    canvas.drawCentredString(PAGE_W/2, 0.25*cm,
        "Sources: Campbell-Walsh-Wein Urology | Goldman-Cecil Medicine | Berek & Novak's Gynecology")
    canvas.restoreState()

# ── Styles ───────────────────────────────────────────────────────────────────
def make_styles():
    s = getSampleStyleSheet()
    base = dict(fontName="Helvetica", textColor=TEXT)

    styles = {}

    # Page title
    styles["page_title"] = ParagraphStyle(
        "page_title", fontName="Helvetica-Bold", fontSize=20,
        textColor=WHITE, alignment=TA_CENTER, spaceAfter=6,
        leading=24
    )
    styles["page_subtitle"] = ParagraphStyle(
        "page_subtitle", fontName="Helvetica", fontSize=11,
        textColor=colors.HexColor("#cce0ff"), alignment=TA_CENTER, spaceAfter=4
    )

    # Section heading (H1)
    styles["h1"] = ParagraphStyle(
        "h1", fontName="Helvetica-Bold", fontSize=13,
        textColor=WHITE, spaceAfter=4, spaceBefore=10, leading=17,
        leftIndent=0
    )
    # Sub-heading (H2)
    styles["h2"] = ParagraphStyle(
        "h2", fontName="Helvetica-Bold", fontSize=11,
        textColor=DARK_BLUE, spaceAfter=3, spaceBefore=8, leading=14
    )
    # Sub-sub heading (H3)
    styles["h3"] = ParagraphStyle(
        "h3", fontName="Helvetica-Bold", fontSize=10,
        textColor=MID_BLUE, spaceAfter=2, spaceBefore=5, leading=13
    )
    # Body
    styles["body"] = ParagraphStyle(
        "body", fontName="Helvetica", fontSize=9,
        textColor=TEXT, spaceAfter=3, leading=13, alignment=TA_JUSTIFY
    )
    # Bullet
    styles["bullet"] = ParagraphStyle(
        "bullet", fontName="Helvetica", fontSize=9,
        textColor=TEXT, spaceAfter=2, leading=13,
        leftIndent=14, bulletIndent=4
    )
    # Key point
    styles["keypoint"] = ParagraphStyle(
        "keypoint", fontName="Helvetica-Bold", fontSize=9,
        textColor=GREEN, spaceAfter=2, leading=13,
        leftIndent=14, bulletIndent=4
    )
    # Warning / important
    styles["warning"] = ParagraphStyle(
        "warning", fontName="Helvetica-Bold", fontSize=9,
        textColor=ORANGE, spaceAfter=3, leading=13
    )
    # Table header cell
    styles["th"] = ParagraphStyle(
        "th", fontName="Helvetica-Bold", fontSize=8.5,
        textColor=WHITE, alignment=TA_CENTER, leading=12
    )
    # Table body cell
    styles["td"] = ParagraphStyle(
        "td", fontName="Helvetica", fontSize=8.5,
        textColor=TEXT, alignment=TA_LEFT, leading=12
    )
    styles["td_c"] = ParagraphStyle(
        "td_c", fontName="Helvetica", fontSize=8.5,
        textColor=TEXT, alignment=TA_CENTER, leading=12
    )
    styles["td_bold"] = ParagraphStyle(
        "td_bold", fontName="Helvetica-Bold", fontSize=8.5,
        textColor=DARK_BLUE, alignment=TA_LEFT, leading=12
    )
    return styles

# ── Helper builders ──────────────────────────────────────────────────────────
def section_banner(text, styles, color=DARK_BLUE):
    """Full-width coloured banner for a major section."""
    tbl = Table([[Paragraph(text, styles["h1"])]], colWidths=[PAGE_W - 2*MARGIN])
    tbl.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),
        ("RIGHTPADDING",  (0,0), (-1,-1), 10),
        ("ROUNDEDCORNERS", (0,0), (-1,-1), [4,4,4,4]),
    ]))
    return tbl

def sub_banner(text, styles, color=MID_BLUE):
    tbl = Table([[Paragraph(text, styles["h2"])]], colWidths=[PAGE_W - 2*MARGIN])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), ACCENT),
        ("LINEBELOW",  (0,0), (-1,-1), 1.5, color),
        ("TOPPADDING",    (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
    ]))
    return tbl

def make_table(headers, rows, styles, col_widths=None):
    th = styles["th"]
    td = styles["td"]
    td_b = styles["td_bold"]

    data = [[Paragraph(h, th) for h in headers]]
    for row in rows:
        data.append([Paragraph(str(cell), td_b if i == 0 else td)
                     for i, cell in enumerate(row)])

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

    tbl = Table(data, colWidths=col_widths, repeatRows=1)
    row_count = len(data)

    row_styles = [
        ("BACKGROUND",    (0,0), (-1,0),  DARK_BLUE),
        ("TEXTCOLOR",     (0,0), (-1,0),  WHITE),
        ("FONTNAME",      (0,0), (-1,0),  "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 8.5),
        ("GRID",          (0,0), (-1,-1), 0.4, BORDER),
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
        ("TOPPADDING",    (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING",   (0,0), (-1,-1), 5),
        ("RIGHTPADDING",  (0,0), (-1,-1), 5),
    ]
    for i in range(1, row_count):
        bg = LIGHT_BLUE if i % 2 == 0 else WHITE
        row_styles.append(("BACKGROUND", (0,i), (-1,i), bg))

    tbl.setStyle(TableStyle(row_styles))
    return tbl

def highlight_box(text, styles, bg=YELLOW_BG, border_color=ORANGE):
    tbl = Table([[Paragraph(text, styles["warning"])]], colWidths=[PAGE_W - 2*MARGIN])
    tbl.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (-1,-1), bg),
        ("LINEBEFORE",   (0,0), (0,-1),  3, border_color),
        ("TOPPADDING",   (0,0), (-1,-1), 6),
        ("BOTTOMPADDING",(0,0), (-1,-1), 6),
        ("LEFTPADDING",  (0,0), (-1,-1), 10),
    ]))
    return tbl

def bullet_table(items, styles, icon="•"):
    rows = [[Paragraph(f"<b>{icon}</b>", styles["bullet"]),
             Paragraph(item, styles["body"])] for item in items]
    tbl = Table(rows, colWidths=[0.5*cm, PAGE_W - 2*MARGIN - 0.5*cm])
    tbl.setStyle(TableStyle([
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
        ("TOPPADDING",    (0,0), (-1,-1), 1),
        ("BOTTOMPADDING", (0,0), (-1,-1), 1),
        ("LEFTPADDING",   (0,0), (-1,-1), 0),
        ("RIGHTPADDING",  (0,0), (-1,-1), 0),
    ]))
    return tbl

# ── Title Page ───────────────────────────────────────────────────────────────
def title_page(styles):
    story = []
    # Big blue title block
    title_data = [
        [Paragraph("EXAM NOTES", styles["page_subtitle"])],
        [Paragraph("Sexual Dysfunction<br/>&amp; Infertility", styles["page_title"])],
        [Paragraph("Investigations • Differential Diagnosis • Key Points", styles["page_subtitle"])],
    ]
    title_tbl = Table(title_data, colWidths=[PAGE_W - 2*MARGIN])
    title_tbl.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), DARK_BLUE),
        ("TOPPADDING",    (0,0), (-1,-1), 14),
        ("BOTTOMPADDING", (0,0), (-1,-1), 14),
        ("LEFTPADDING",   (0,0), (-1,-1), 20),
        ("RIGHTPADDING",  (0,0), (-1,-1), 20),
        ("ROUNDEDCORNERS",(0,0), (-1,-1), [8,8,8,8]),
    ]))
    story.append(Spacer(1, 2*cm))
    story.append(title_tbl)
    story.append(Spacer(1, 0.8*cm))

    # Contents box
    contents = [
        "PART 1: Sexual Dysfunction",
        "  • Definition & Classification",
        "  • Erectile Dysfunction — Causes & Differential Diagnosis",
        "  • Investigations of Sexual Dysfunction",
        "  • Other Forms (PE, Loss of Libido, Female SD)",
        "",
        "PART 2: Infertility",
        "  • Definition & Requirements for Pregnancy",
        "  • Differential Diagnosis — Male & Female Causes",
        "  • Investigations — Semen Analysis, Hormones, Imaging",
        "  • Summary Tables",
        "",
        "HIGH-YIELD EXAM POINTS",
    ]
    cont_rows = [[Paragraph(c, styles["body"])] for c in contents]
    cont_tbl = Table(cont_rows, colWidths=[PAGE_W - 2*MARGIN])
    cont_tbl.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), ACCENT),
        ("LINEABOVE",     (0,0), (-1,0),  1.5, MID_BLUE),
        ("LINEBELOW",     (0,-1),(-1,-1), 1.5, MID_BLUE),
        ("TOPPADDING",    (0,0), (-1,-1), 3),
        ("BOTTOMPADDING", (0,0), (-1,-1), 3),
        ("LEFTPADDING",   (0,0), (-1,-1), 16),
    ]))
    story.append(cont_tbl)
    story.append(Spacer(1, 0.6*cm))
    story.append(Paragraph(
        "Sources: <i>Campbell-Walsh-Wein Urology | Goldman-Cecil Medicine | Berek &amp; Novak's Gynecology</i>",
        styles["body"]
    ))
    story.append(PageBreak())
    return story

# ════════════════════════════════════════════════════════════════════
#  MAIN CONTENT
# ════════════════════════════════════════════════════════════════════
def build_story(styles):
    story = title_page(styles)
    SP = lambda n=0.3: Spacer(1, n*cm)

    # ─── PART 1: SEXUAL DYSFUNCTION ─────────────────────────────────
    story += [section_banner("PART 1: SEXUAL DYSFUNCTION", styles), SP()]

    # Definition
    story += [sub_banner("Definition & Classification", styles), SP(0.2)]
    story.append(Paragraph(
        "Sexual dysfunction = a persistent disturbance in the normal sexual response cycle causing "
        "personal distress. It spans disorders of <b>desire, arousal, orgasm,</b> and <b>pain</b>.",
        styles["body"]
    ))
    story.append(SP(0.2))

    class_data = [
        ["Domain", "Male Disorder", "Female Disorder"],
        ["Desire",  "Hypoactive sexual desire disorder (HSDD)", "HSDD"],
        ["Arousal", "Erectile dysfunction (ED)", "Female sexual arousal disorder"],
        ["Orgasm",  "Premature / delayed ejaculation, anorgasmia", "Female orgasmic disorder"],
        ["Pain",    "Dyspareunia", "Dyspareunia, Vaginismus"],
    ]
    story.append(make_table(class_data[0], class_data[1:], styles,
                            col_widths=[3.5*cm, 8*cm, 5.5*cm]))
    story.append(SP())

    # ED definition
    story += [sub_banner("Erectile Dysfunction (ED) — Most Testable", styles), SP(0.2)]
    story.append(highlight_box(
        "<b>AUA / NIH Definition:</b> Inability to attain and/or maintain penile erection sufficient "
        "for satisfactory intercourse. Affects >50% of men over age 40.",
        styles
    ))
    story.append(SP(0.2))
    story.append(highlight_box(
        "⚠ ED can be a harbinger of occult coronary artery disease — always consider cardiology referral.",
        styles, bg=colors.HexColor("#fff0f0"), border_color=colors.red
    ))
    story.append(SP(0.3))

    # ED Differential Diagnosis
    story.append(Paragraph("<b>Differential Diagnosis of Erectile Dysfunction</b>", styles["h3"]))
    ed_dd = [
        ["Category", "Examples / Key Clues"],
        ["Vasculogenic (most common)", "Atherosclerosis, hypertension, DM (vasculopathy), dyslipidemia, smoking"],
        ["Neurogenic", "DM peripheral neuropathy, MS, spinal cord injury, radical prostatectomy"],
        ["Psychogenic", "Situational ED, adequate morning/nocturnal erections, anxiety, depression, young age"],
        ["Endocrinologic", "Hypogonadism (low T), hyperprolactinemia, hypothyroidism"],
        ["Medication-induced", "Beta-blockers, thiazides, SSRIs, antipsychotics, antiandrogens"],
        ["Structural", "Peyronie's disease (penile curvature + plaque), penile trauma"],
    ]
    story.append(make_table(ed_dd[0], ed_dd[1:], styles, col_widths=[5*cm, 12*cm]))
    story.append(SP(0.2))
    story.append(highlight_box(
        "<b>Key Differentiator:</b> Situational ED / adequate nocturnal erections = <b>PSYCHOGENIC</b>. "
        "Absent nocturnal erections = <b>ORGANIC</b>.",
        styles, bg=LIGHT_GREEN, border_color=GREEN
    ))
    story.append(SP(0.4))

    # ED Investigations
    story += [sub_banner("Investigations of Sexual Dysfunction", styles), SP(0.2)]
    story.append(Paragraph("<b>Step 1 — Validated Questionnaires</b>", styles["h3"]))
    story.append(bullet_table([
        "<b>IIEF (International Index of Erectile Function)</b> — gold standard; assesses erectile function, orgasm, desire, intercourse satisfaction, overall satisfaction",
        "<b>IIEF-6 / SHIM (Sexual Health Index for Men)</b> — abbreviated 6-item version",
        "<b>ADAM questionnaire</b>, Aging Male Survey — screen for hypogonadism",
    ], styles))
    story.append(SP(0.2))

    story.append(Paragraph("<b>Step 2 — Basic Laboratory Tests</b>", styles["h3"]))
    lab_data = [
        ["Test", "Purpose"],
        ["Serum total testosterone", "Screen for hypogonadism (low = ED, low libido)"],
        ["Free / bioavailable testosterone", "More accurate — portion not bound to SHBG"],
        ["LH, FSH", "Distinguish primary (high LH/FSH) vs secondary (low LH/FSH) hypogonadism"],
        ["Serum prolactin", "If low testosterone — rule out prolactinoma"],
        ["FBS / HbA1c", "Screen for diabetes mellitus"],
        ["Lipid profile", "Screen for vascular risk factors"],
        ["TSH", "Rule out thyroid disorders"],
        ["Serum estradiol", "If gynecomastia or feminization present"],
    ]
    story.append(make_table(lab_data[0], lab_data[1:], styles, col_widths=[6.5*cm, 10.5*cm]))
    story.append(SP(0.3))

    story.append(Paragraph("<b>Step 3 — Specialized / Second-line Tests</b>", styles["h3"]))
    spec_data = [
        ["Test", "Purpose / Interpretation"],
        ["Nocturnal Penile Tumescence (NPT)", "Normal NPT = psychogenic ED; Absent NPT = organic ED. Gold standard for differentiation."],
        ["Intracavernosal injection test", "PGE1 / papaverine injection — erection achieved = no significant vascular disease"],
        ["Penile colour Doppler ultrasound", "Evaluates arterial inflow and venous leak (veno-occlusive dysfunction)"],
        ["Pudendal arteriography", "Only before vascular reconstructive surgery"],
        ["Cavernosometry / cavernosography", "Venous leak evaluation"],
        ["Neurophysiologic tests", "Bulbocavernosus reflex, penile biothesiometry — for neurogenic ED"],
    ]
    story.append(make_table(spec_data[0], spec_data[1:], styles, col_widths=[5.5*cm, 11.5*cm]))
    story.append(SP(0.4))

    # Other SD
    story += [sub_banner("Other Forms of Sexual Dysfunction", styles), SP(0.2)]
    story.append(Paragraph("<b>Premature Ejaculation (PE)</b>", styles["h3"]))
    story.append(bullet_table([
        "<b>ISSM Definition:</b> Ejaculation in &lt;1 minute (lifelong) or &lt;3 minutes (acquired), with inability to delay and negative personal consequence",
        "Median normal IELT: <b>5.4 minutes</b> (multicountry study); 3–7 minutes = adequate per sexual therapists",
        "<b>Treatment:</b> Behavioral (squeeze/stop-start technique), SSRIs (dapoxetine), topical anesthetics",
    ], styles))
    story.append(SP(0.2))

    story.append(Paragraph("<b>Loss of Libido</b>", styles["h3"]))
    story.append(bullet_table([
        "Causes: hypogonadism, depression, medications (SSRIs, antiandrogens), severe illness (cancer)",
        "Investigate with: testosterone, prolactin, gonadotropins (LH/FSH)",
        "Adequate ejaculatory volume → hypogonadism severe enough to cause libido loss is unlikely",
    ], styles))
    story.append(SP(0.2))

    story.append(Paragraph("<b>Female Sexual Dysfunction</b>", styles["h3"]))
    fsd_data = [
        ["Disorder", "Key Feature", "Investigations"],
        ["HSDD", "Loss of desire, most common female SD", "Hormones: estrogen, testosterone, FSH, prolactin"],
        ["Vaginismus", "Involuntary vaginal spasm; inability to allow penetration; normal libido", "Pelvic exam, psychological assessment"],
        ["Dyspareunia", "Painful intercourse; deep (endometriosis) or superficial (vulvodynia, atrophic vaginitis)", "Gynecologic exam, laparoscopy if suspected endometriosis"],
        ["Female arousal disorder", "Inadequate lubrication / genital engorgement", "Hormone levels, psychosexual evaluation"],
    ]
    story.append(make_table(fsd_data[0], fsd_data[1:], styles, col_widths=[3.8*cm, 6*cm, 7.2*cm]))

    story.append(PageBreak())

    # ─── PART 2: INFERTILITY ────────────────────────────────────────
    story += [section_banner("PART 2: INFERTILITY", styles, color=GREEN), SP()]

    story += [sub_banner("Definition & Requirements for Pregnancy", styles), SP(0.2)]
    story.append(highlight_box(
        "<b>WHO Definition:</b> Failure to achieve a clinical pregnancy after <b>12 months</b> of regular "
        "unprotected sexual intercourse. Evaluation warranted after <b>6 months</b> if woman ≥35 years.",
        styles, bg=LIGHT_GREEN, border_color=GREEN
    ))
    story.append(SP(0.2))
    story.append(Paragraph("<b>Requirements for Pregnancy (exam favourite):</b>", styles["h3"]))
    story.append(bullet_table([
        "Male must produce adequate numbers of normal, motile spermatozoa",
        "Male must eject sperm through a patent ductal system",
        "Sperm must traverse an unobstructed female reproductive tract",
        "Female must ovulate and release an ovum",
        "Sperm must fertilize the ovum",
        "Fertilized ovum must implant in appropriately prepared endometrium",
    ], styles))
    story.append(SP(0.4))

    # Causes table
    story += [sub_banner("Differential Diagnosis — Causes of Infertility", styles), SP(0.2)]
    story.append(Paragraph("<b>Overview by Factor (Goldman-Cecil Medicine)</b>", styles["h3"]))
    ov_data = [
        ["Factor", "Approximate Incidence", "Main Causes"],
        ["Male factor", "~40%", "Varicocele, testicular failure, ductal obstruction, ejaculatory disorders, immunologic"],
        ["Tubal / peritoneal (female)", "30–40%", "PID sequelae, endometriosis, post-peritonitis adhesions"],
        ["Ovulatory disorders (female)", "30–40%", "PCOS (most common), hypothalamic amenorrhea, hyperprolactinemia, POF"],
        ["Uterine / cervical (female)", "10–15%", "Asherman syndrome, fibroids (submucosal), polyps, Mullerian anomalies"],
        ["Unexplained infertility", "&lt;10%", "All tests normal"],
        ["Nutritional / metabolic", "~5%", "Thyroid disorders, DM, severe nutritional deficiency"],
        ["Immunologic", "&lt;5%", "Antisperm antibodies"],
        ["Vaginal factors", "&lt;5%", "Vaginismus, vaginitis, imperforate hymen"],
    ]
    story.append(make_table(ov_data[0], ov_data[1:], styles, col_widths=[4.5*cm, 3*cm, 9.5*cm]))
    story.append(SP(0.3))

    # Male DD detail
    story.append(Paragraph("<b>Male Factor — Detailed Differential Diagnosis</b>", styles["h3"]))
    male_dd = [
        ["Condition", "Key Diagnostic Feature"],
        ["Varicocele", "Dilated pampiniform plexus ≥3 mm; OAT syndrome on semen analysis; most common treatable cause"],
        ["Klinefelter syndrome (47,XXY)", "Azoospermia, small firm testes, elevated FSH/LH, low testosterone, gynaecomastia"],
        ["Obstructive azoospermia", "Normal FSH, normal testis volume, no sperm; TRUS for ejaculatory duct obstruction"],
        ["Non-obstructive azoospermia", "Elevated FSH, small/atrophic testes; testicular failure"],
        ["Retrograde ejaculation", "Low ejaculate volume (&lt;1 mL), sperm in post-ejaculate urine; DM, prostate surgery"],
        ["CBAVD", "Absent vas deferens on exam, CFTR mutation, low volume acidic semen (absent seminal vesicles)"],
        ["Hyperprolactinemia", "Low T, low LH/FSH, elevated prolactin; MRI pituitary"],
        ["Cryptorchidism", "History of undescended testes; testicular atrophy; elevated FSH"],
    ]
    story.append(make_table(male_dd[0], male_dd[1:], styles, col_widths=[5*cm, 12*cm]))
    story.append(SP(0.3))

    # Female DD detail
    story.append(Paragraph("<b>Female Factor — Detailed Differential Diagnosis</b>", styles["h3"]))
    female_dd = [
        ["Condition", "Key Diagnostic Feature"],
        ["PCOS", "Oligomenorrhea/amenorrhea, LH:FSH >2:1, hyperandrogenism, USS polycystic ovaries; most common anovulatory cause"],
        ["Hypothalamic amenorrhea", "Low BMI / athlete / stress; low FSH, LH, estrogen; normal anatomy"],
        ["Premature ovarian failure (POF)", "Age &lt;40, hot flashes/flushes, FSH >40 IU/L, low estrogen, low AMH"],
        ["Hyperprolactinemia", "Galactorrhea, amenorrhea, elevated prolactin; MRI: pituitary adenoma"],
        ["Tubal disease (PID sequelae)", "History of STI (Chlamydia, gonorrhea); HSG shows blocked / hydrosalpinx"],
        ["Endometriosis", "Dysmenorrhea, dyspareunia, dyschezia; CA-125 unreliable; <b>laparoscopy = gold standard</b>"],
        ["Asherman syndrome", "Post-D&C/curettage; scanty/absent periods; hysteroscopy shows intrauterine synechiae"],
        ["Uterine fibroids", "Submucosal type most imp.; menorrhagia; USS/hysteroscopy/MRI"],
        ["Hypothyroidism", "Irregular cycles, anovulation, weight gain, cold intolerance; elevated TSH"],
        ["Cervical factor", "Hostile mucus; history of cone biopsy / LEEP; abnormal post-coital test"],
    ]
    story.append(make_table(female_dd[0], female_dd[1:], styles, col_widths=[5*cm, 12*cm]))

    story.append(PageBreak())

    # ─── INVESTIGATIONS OF INFERTILITY ──────────────────────────────
    story += [section_banner("INVESTIGATIONS OF INFERTILITY", styles, color=MID_BLUE), SP()]
    story.append(highlight_box(
        "<b>Basic investigations ordered in ALL couples:</b>  (1) Semen analysis  "
        "(2) Confirmation of ovulation  (3) Documentation of tubal patency",
        styles, bg=LIGHT_BLUE, border_color=MID_BLUE
    ))
    story.append(SP(0.3))

    # Semen analysis
    story += [sub_banner("A. Male Investigations", styles), SP(0.2)]
    story.append(Paragraph("<b>1. Semen Analysis (Cornerstone)</b>", styles["h3"]))
    sa_data = [
        ["Parameter", "WHO Normal Value", "Abnormal Term"],
        ["Volume", "≥1.5 mL", "Hypospermia / Aspermia"],
        ["Concentration", "≥16 million/mL", "Oligospermia"],
        ["Total motility", "≥42%", "Asthenospermia"],
        ["Progressive motility", "≥30%", "Asthenospermia"],
        ["Normal morphology (Kruger strict)", "≥4%", "Teratospermia"],
        ["Vitality (live sperm)", "≥54%", "Necrospermia"],
        ["No sperm", "—", "Azoospermia"],
    ]
    story.append(make_table(sa_data[0], sa_data[1:], styles, col_widths=[5*cm, 5*cm, 7*cm]))
    story.append(SP(0.2))
    story.append(bullet_table([
        "<b>Sperm vitality stain</b> — differentiates complete asthenospermia from necrospermia",
        "<b>Volume &lt;1 mL DDx:</b> Ejaculatory ductal obstruction | Retrograde ejaculation | CBAVD",
        "<b>Globozoospermia</b> (round-headed sperm) = absent acrosome → treat with IVF/ICSI",
        "<b>Pyospermia</b> vs immature germ cells — differentiated by laboratory staining",
        "Semen analysis = <b>probabilistic assessment</b>; only azoospermia absolutely confirms infertility",
    ], styles))
    story.append(SP(0.2))

    story.append(Paragraph("<b>2. Male Hormonal Assessment</b>", styles["h3"]))
    mh_data = [
        ["Test", "Interpretation"],
        ["Total testosterone", "Low = hypogonadism (primary or secondary)"],
        ["LH, FSH", "High LH/FSH = primary (testicular failure); Low = secondary (hypothalamic/pituitary)"],
        ["Prolactin", "Elevated → hyperprolactinemia suppresses GnRH → low T"],
        ["Estradiol", "Elevated if gynaecomastia present"],
        ["SHBG", "Calculate free/bioavailable T"],
    ]
    story.append(make_table(mh_data[0], mh_data[1:], styles, col_widths=[5*cm, 12*cm]))
    story.append(SP(0.2))

    story.append(Paragraph("<b>3. Genetic Testing</b>", styles["h3"]))
    story.append(bullet_table([
        "<b>Karyotype</b> — azoospermia/severe oligospermia → Klinefelter (47,XXY) most common genetic cause",
        "<b>CFTR gene mutation</b> — if CBAVD; screen partner (risk of CF offspring if both carriers)",
        "<b>Y-chromosome microdeletions (AZF regions)</b> — AZFa, AZFb, AZFc; important for prognosis of sperm retrieval",
    ], styles))
    story.append(SP(0.2))

    story.append(Paragraph("<b>4. Imaging (Male)</b>", styles["h3"]))
    mimg_data = [
        ["Modality", "Indication / Findings"],
        ["Scrotal colour Doppler USS", "Varicocele (dilated veins >3 mm); testicular volume (normal 15–20 mL); testicular microlithiasis"],
        ["Transrectal USS (TRUS)", "Ejaculatory duct obstruction; seminal vesicle abnormalities"],
        ["Post-ejaculate urinalysis", "Retrograde ejaculation (sperm in urine)"],
    ]
    story.append(make_table(mimg_data[0], mimg_data[1:], styles, col_widths=[5*cm, 12*cm]))
    story.append(SP(0.2))

    story.append(Paragraph("<b>5. Advanced Tests</b>", styles["h3"]))
    story.append(bullet_table([
        "<b>Antisperm antibody test</b> (immunobead / MAR test) — after blood-testis barrier disruption (trauma, infection, vasectomy reversal)",
        "<b>Testicular biopsy</b> — obstructive vs non-obstructive azoospermia; also for TESE (sperm extraction for IVF)",
    ], styles))
    story.append(SP(0.4))

    # Female investigations
    story += [sub_banner("B. Female Investigations", styles), SP(0.2)]
    story.append(Paragraph("<b>1. Ovulation Assessment</b>", styles["h3"]))
    ov_inv = [
        ["Method", "Details / Interpretation"],
        ["Basal body temperature (BBT) chart", "Biphasic pattern (0.2–0.5°C rise) = ovulation occurred"],
        ["Serum progesterone (Day 21 / mid-luteal)", ">30 nmol/L (>10 ng/mL) = ovulation confirmed; done 6–8 days before expected menses"],
        ["Urine LH surge (OPK)", "Positive = ovulation in ~24–36 hours"],
        ["Serial transvaginal USS", "Gold standard — visualises follicle growth and collapse; confirms ovulation"],
        ["Endometrial biopsy", "Now rarely used; dating &lt;3 days before menses (luteal phase defect assessment)"],
    ]
    story.append(make_table(ov_inv[0], ov_inv[1:], styles, col_widths=[5*cm, 12*cm]))
    story.append(SP(0.2))

    story.append(Paragraph("<b>2. Ovarian Reserve Testing</b>", styles["h3"]))
    or_data = [
        ["Test", "Normal / Interpretation"],
        ["Serum FSH (Day 2–3)", "Normal &lt;10 IU/L; >10–15 IU/L = diminished reserve"],
        ["Estradiol (Day 2–3)", "Elevated (>60–80 pg/mL) on Day 2–3 = poor reserve"],
        ["Anti-Mullerian hormone (AMH)", "Best marker — low = decreased reserve; not cycle-day dependent"],
        ["Antral follicle count (AFC) by TVUSS", "&lt;5–7 follicles = poor reserve"],
        ["Clomiphene citrate challenge test (CCCT)", "FSH on Day 3 and Day 10; elevated Day 10 FSH = poor reserve"],
    ]
    story.append(make_table(or_data[0], or_data[1:], styles, col_widths=[5.5*cm, 11.5*cm]))
    story.append(SP(0.2))

    story.append(Paragraph("<b>3. Tubal Patency Assessment</b>", styles["h3"]))
    tubal_data = [
        ["Test", "Details"],
        ["HSG (Hysterosalpingography)", "First-line; X-ray with contrast; shows tubal patency + uterine cavity; therapeutic (tubal flushing) effect"],
        ["Sonohysterography (SIS)", "USS + saline; superior for uterine cavity evaluation"],
        ["Laparoscopy + chromopertubation", "<b>Gold standard</b>; direct visualisation; detects endometriosis + adhesions; dye flushed through tubes"],
        ["HyCoSy", "USS contrast alternative to HSG"],
    ]
    story.append(make_table(tubal_data[0], tubal_data[1:], styles, col_widths=[5*cm, 12*cm]))
    story.append(SP(0.2))

    story.append(Paragraph("<b>4. Uterine Cavity Assessment</b>", styles["h3"]))
    story.append(bullet_table([
        "<b>Hysteroscopy</b> — gold standard for intrauterine pathology (polyps, submucosal fibroids, Asherman syndrome / synechiae)",
        "<b>MRI pelvis</b> — Mullerian anomalies, deep endometriosis, fibroids mapping",
        "<b>3D transvaginal USS</b> — uterine septum, congenital anomalies",
    ], styles))
    story.append(SP(0.2))

    story.append(Paragraph("<b>5. Female Hormonal Profile</b>", styles["h3"]))
    fh_data = [
        ["Test", "Purpose"],
        ["TSH", "Hypothyroidism causes anovulation, irregular cycles"],
        ["Prolactin", "Hyperprolactinemia suppresses GnRH → amenorrhea/anovulation"],
        ["LH:FSH ratio", "LH:FSH >2:1 suggests PCOS"],
        ["Free testosterone, DHEAS", "PCOS, congenital adrenal hyperplasia (CAH)"],
        ["17-OHP", "CAH (21-hydroxylase deficiency)"],
        ["Fasting glucose / insulin", "PCOS with insulin resistance"],
        ["Estradiol", "Ovarian reserve, POF (low)"],
    ]
    story.append(make_table(fh_data[0], fh_data[1:], styles, col_widths=[5*cm, 12*cm]))
    story.append(SP(0.2))

    story.append(Paragraph("<b>6. Immunologic Tests</b>", styles["h3"]))
    story.append(bullet_table([
        "Antisperm antibodies (cervical mucus/serum)",
        "Antinuclear antibodies — autoimmune causes",
        "Antiphospholipid antibodies (anticardiolipin, lupus anticoagulant) — recurrent pregnancy loss",
    ], styles))

    story.append(PageBreak())

    # ─── SUMMARY + HIGH YIELD ───────────────────────────────────────
    story += [section_banner("SUMMARY TABLES & HIGH-YIELD POINTS", styles, color=ORANGE), SP()]

    story += [sub_banner("Investigation Summary at a Glance", styles), SP(0.2)]
    summary_data = [
        ["Investigation", "Male", "Female"],
        ["First-line", "Semen analysis", "BBT chart / serum progesterone (Day 21)"],
        ["Ovarian reserve", "—", "AMH (best), Day 3 FSH, AFC"],
        ["Hormones", "T, LH, FSH, prolactin, estradiol", "FSH, LH, estradiol, AMH, TSH, prolactin, androgens"],
        ["Anatomic / imaging", "Scrotal Doppler USS, TRUS", "HSG, hysteroscopy, laparoscopy, pelvic USS"],
        ["Genetic", "Karyotype, CFTR, Y-microdeletion", "Karyotype"],
        ["Immunologic", "Antisperm antibodies (MAR test)", "Antisperm Ab, antiphospholipid Ab"],
        ["Advanced", "Testicular biopsy (azoospermia)", "Laparoscopy (unexplained infertility)"],
    ]
    story.append(make_table(summary_data[0], summary_data[1:], styles, col_widths=[4.5*cm, 6.5*cm, 6*cm]))
    story.append(SP(0.4))

    # High yield
    story += [sub_banner("High-Yield Exam Points", styles), SP(0.2)]

    hy = [
        ("<b>1. Infertility timing:</b>", "12 months (general); 6 months if woman ≥35 years"),
        ("<b>2. Most common male infertility cause:</b>", "Varicocele (most common treatable)"),
        ("<b>3. Most common female anovulatory cause:</b>", "PCOS"),
        ("<b>4. Most common female infertility overall:</b>", "Tubal/peritoneal disease (30–40%)"),
        ("<b>5. Gold standard — tubal patency:</b>", "Laparoscopy with chromopertubation"),
        ("<b>6. Best ovarian reserve marker:</b>", "AMH (not cycle-day dependent)"),
        ("<b>7. ED + cardiovascular:</b>", "ED is a harbinger of occult coronary artery disease"),
        ("<b>8. NPT test:</b>", "Normal NPT = psychogenic ED; Absent NPT = organic ED"),
        ("<b>9. CBAVD association:</b>", "CFTR mutation (CF gene) — screen partner for CF mutations"),
        ("<b>10. Asherman syndrome:</b>", "Post-curettage intrauterine synechiae → anovulation/infertility"),
        ("<b>11. Klinefelter (47,XXY):</b>", "Most common genetic cause of male infertility/azoospermia"),
        ("<b>12. Male factor incidence:</b>", "Sole cause in ~40%; contributing factor in up to 50%"),
        ("<b>13. Clomiphene citrate:</b>", "First-line ovulation induction (antiestrogen); 50 mg Day 3–7; do NOT use in ovarian failure"),
        ("<b>14. Premature ejaculation:</b>", "Lifelong &lt;1 min; acquired &lt;3 min; normal IELT = 5.4 min"),
        ("<b>15. AZF microdeletion:</b>", "AZFa/b = no sperm retrieval possible; AZFc = sperm retrieval possible via TESE"),
    ]
    hy_rows = [[Paragraph(label, styles["td_bold"]), Paragraph(val, styles["body"])]
               for label, val in hy]
    hy_tbl = Table(hy_rows, colWidths=[6.5*cm, 10.5*cm])
    hy_tbl.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), WHITE),
        ("ROWBACKGROUNDS",(0,0), (-1,-1), [LIGHT_BLUE, WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.4, BORDER),
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
        ("TOPPADDING",    (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING",   (0,0), (-1,-1), 6),
    ]))
    story.append(hy_tbl)
    story.append(SP(0.5))
    story.append(HRFlowable(width="100%", thickness=1, color=DARK_BLUE))
    story.append(SP(0.2))
    story.append(Paragraph(
        "<i>Sources: Campbell-Walsh-Wein Urology | Goldman-Cecil Medicine | Berek &amp; Novak's Gynecology</i>",
        styles["body"]
    ))

    return story

# ── Build PDF ────────────────────────────────────────────────────────────────
def main():
    doc = SimpleDocTemplate(
        OUTPUT,
        pagesize=A4,
        leftMargin=MARGIN, rightMargin=MARGIN,
        topMargin=1.5*cm, bottomMargin=1.2*cm,
        title="Sexual Dysfunction & Infertility — Exam Notes",
        author="Orris Medical Notes",
    )
    styles = make_styles()
    story  = build_story(styles)
    doc.build(story, onFirstPage=header_footer, onLaterPages=header_footer)
    print(f"PDF saved: {OUTPUT}")

if __name__ == "__main__":
    main()
Running Command

cd /home/daytona/workspace/sexual-dysfunction-infertility && python generate_notes.py 2>&1

Running Command

ls -lh /home/daytona/workspace/sexual-dysfunction-infertility/Sexual_Dysfunction_Infertility_Notes.pdf

Your printable PDF notes are ready. Click below to download:

Sexual Dysfunction Infertility Notes

PDF Document · PDF


What's inside the PDF (4 pages, A4, print-ready):
PageContent
1Title page with full contents list
2Sexual Dysfunction - classification, ED differential diagnosis, full investigations (questionnaires, labs, specialised tests), other SD types (PE, libido, female SD)
3Infertility - definition, requirements for pregnancy, complete DDx table (male + female), detailed condition-by-condition breakdown
4Female investigations (ovulation, ovarian reserve, tubal patency, uterine, hormones), master summary table, 15 high-yield exam points
Design features: colour-coded section banners, alternating-row tables, highlight boxes for key facts, page headers/footers, all sourced from Campbell-Walsh-Wein Urology, Goldman-Cecil Medicine, and Berek & Novak's Gynecology.

Notes pdf

Asking for Preferences
The user already has a PDF of Sexual Dysfunction & Infertility notes from the previous session. Since they said "Notes pdf" again, they likely want the same PDF re-delivered or a re-download link. Let me just provide the existing download link directly.
The PDF from the previous session is already available for download:

Sexual Dysfunction Infertility Notes

PDF Document · PDF

If you meant a different topic, just type the topic name and I'll build a fresh PDF for it right away.

Notes pn male and female infertility with investigation interpretation and differential diagnosis

Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Writing File

~/sexual-dysfunction-infertility/infertility_notes.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak, KeepTogether
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY

OUTPUT = "/home/daytona/workspace/sexual-dysfunction-infertility/Male_Female_Infertility_Notes.pdf"

PAGE_W, PAGE_H = A4
MARGIN = 1.7 * cm

# ─── Palette ─────────────────────────────────────────────────────────────────
NAVY        = colors.HexColor("#0d2b4e")
ROYAL       = colors.HexColor("#1a5276")
SKY         = colors.HexColor("#2e86c1")
LIGHT_BLUE  = colors.HexColor("#d6eaf8")
PALE_BLUE   = colors.HexColor("#eaf4fb")
TEAL        = colors.HexColor("#0e6655")
LIGHT_TEAL  = colors.HexColor("#d0ece7")
PALE_TEAL   = colors.HexColor("#e8f8f5")
ORANGE      = colors.HexColor("#ca6f1e")
ORANGE_LITE = colors.HexColor("#fdebd0")
RED         = colors.HexColor("#922b21")
RED_LITE    = colors.HexColor("#fadbd8")
GOLD        = colors.HexColor("#9a7d0a")
GOLD_LITE   = colors.HexColor("#fef9e7")
BORDER      = colors.HexColor("#aed6f1")
WHITE       = colors.white
TEXT        = colors.HexColor("#1a1a1a")
GREY        = colors.HexColor("#f2f3f4")

# ─── Page decoration ─────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    # Top bar
    canvas.setFillColor(NAVY)
    canvas.rect(0, PAGE_H - 1.15*cm, PAGE_W, 1.15*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica-Bold", 8.5)
    canvas.drawString(MARGIN, PAGE_H - 0.76*cm, "EXAM NOTES  |  Male & Female Infertility")
    canvas.setFont("Helvetica", 8.5)
    canvas.drawRightString(PAGE_W - MARGIN, PAGE_H - 0.76*cm, f"Page {doc.page}")
    # Bottom bar
    canvas.setFillColor(NAVY)
    canvas.rect(0, 0, PAGE_W, 0.72*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica-Oblique", 6.5)
    canvas.drawCentredString(PAGE_W/2, 0.23*cm,
        "Sources: Campbell-Walsh-Wein Urology  |  Goldman-Cecil Medicine  |  Berek & Novak's Gynecology  |  Textbook of Family Medicine")
    canvas.restoreState()

# ─── Styles ───────────────────────────────────────────────────────────────────
def S():
    d = {}
    def ps(name, **kw):
        d[name] = ParagraphStyle(name, **kw)
    ps("cover_title",   fontName="Helvetica-Bold",  fontSize=22, textColor=WHITE,
       alignment=TA_CENTER, leading=28, spaceAfter=4)
    ps("cover_sub",     fontName="Helvetica",        fontSize=11, textColor=colors.HexColor("#aed6f1"),
       alignment=TA_CENTER, spaceAfter=3)
    ps("cover_tag",     fontName="Helvetica-Oblique",fontSize=9,  textColor=colors.HexColor("#85c1e9"),
       alignment=TA_CENTER)
    ps("h1",  fontName="Helvetica-Bold", fontSize=12, textColor=WHITE, leading=16)
    ps("h2",  fontName="Helvetica-Bold", fontSize=10.5, textColor=NAVY, leading=14, spaceBefore=6, spaceAfter=2)
    ps("h3",  fontName="Helvetica-Bold", fontSize=9.5,  textColor=ROYAL, leading=13, spaceBefore=4, spaceAfter=1)
    ps("body",fontName="Helvetica",      fontSize=8.8, textColor=TEXT, leading=13, spaceAfter=2, alignment=TA_JUSTIFY)
    ps("bul", fontName="Helvetica",      fontSize=8.8, textColor=TEXT, leading=13, spaceAfter=1,
       leftIndent=12, bulletIndent=2)
    ps("warn",fontName="Helvetica-Bold", fontSize=8.8, textColor=RED, leading=13)
    ps("ok",  fontName="Helvetica-Bold", fontSize=8.8, textColor=TEAL, leading=13)
    ps("th",  fontName="Helvetica-Bold", fontSize=8.2, textColor=WHITE, alignment=TA_CENTER, leading=11)
    ps("td",  fontName="Helvetica",      fontSize=8.2, textColor=TEXT, alignment=TA_LEFT,  leading=11)
    ps("tdb", fontName="Helvetica-Bold", fontSize=8.2, textColor=NAVY, alignment=TA_LEFT,  leading=11)
    ps("tdc", fontName="Helvetica",      fontSize=8.2, textColor=TEXT, alignment=TA_CENTER,leading=11)
    ps("num", fontName="Helvetica-Bold", fontSize=8.8, textColor=ORANGE, leading=13)
    return d

STYLES = S()
SP = lambda n=0.3: Spacer(1, n*cm)
W = PAGE_W - 2*MARGIN   # usable width

# ─── Builders ─────────────────────────────────────────────────────────────────
def banner(text, color=NAVY, text_style="h1"):
    t = Table([[Paragraph(text, STYLES[text_style])]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,-1), color),
        ("TOPPADDING",    (0,0),(-1,-1), 7),
        ("BOTTOMPADDING", (0,0),(-1,-1), 7),
        ("LEFTPADDING",   (0,0),(-1,-1), 10),
        ("RIGHTPADDING",  (0,0),(-1,-1), 10),
    ]))
    return t

def sub_bar(text, color=ROYAL):
    p = Paragraph(text, STYLES["h2"])
    t = Table([[p]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0),(-1,-1), PALE_BLUE),
        ("LINEBELOW",    (0,0),(-1,-1), 2, color),
        ("TOPPADDING",   (0,0),(-1,-1), 4),
        ("BOTTOMPADDING",(0,0),(-1,-1), 4),
        ("LEFTPADDING",  (0,0),(-1,-1), 8),
    ]))
    return t

def teal_bar(text):
    p = Paragraph(text, STYLES["h2"])
    t = Table([[p]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0),(-1,-1), PALE_TEAL),
        ("LINEBELOW",    (0,0),(-1,-1), 2, TEAL),
        ("TOPPADDING",   (0,0),(-1,-1), 4),
        ("BOTTOMPADDING",(0,0),(-1,-1), 4),
        ("LEFTPADDING",  (0,0),(-1,-1), 8),
    ]))
    return t

def mktable(hdr, rows, cw=None, hdr_color=NAVY):
    data = [[Paragraph(h, STYLES["th"]) for h in hdr]]
    for row in rows:
        data.append([Paragraph(str(c), STYLES["tdb"] if i==0 else STYLES["td"])
                     for i,c in enumerate(row)])
    if cw is None:
        cw = [W/len(hdr)]*len(hdr)
    t = Table(data, colWidths=cw, repeatRows=1)
    rstyles = [
        ("BACKGROUND",    (0,0),(-1,0),  hdr_color),
        ("GRID",          (0,0),(-1,-1), 0.35, BORDER),
        ("VALIGN",        (0,0),(-1,-1), "TOP"),
        ("TOPPADDING",    (0,0),(-1,-1), 3),
        ("BOTTOMPADDING", (0,0),(-1,-1), 3),
        ("LEFTPADDING",   (0,0),(-1,-1), 5),
        ("RIGHTPADDING",  (0,0),(-1,-1), 5),
    ]
    for i in range(1, len(data)):
        rstyles.append(("BACKGROUND",(0,i),(-1,i), LIGHT_BLUE if i%2==0 else WHITE))
    t.setStyle(TableStyle(rstyles))
    return t

def teal_table(hdr, rows, cw=None):
    data = [[Paragraph(h, STYLES["th"]) for h in hdr]]
    for row in rows:
        data.append([Paragraph(str(c), STYLES["tdb"] if i==0 else STYLES["td"])
                     for i,c in enumerate(row)])
    if cw is None:
        cw = [W/len(hdr)]*len(hdr)
    t = Table(data, colWidths=cw, repeatRows=1)
    rstyles = [
        ("BACKGROUND",    (0,0),(-1,0),  TEAL),
        ("GRID",          (0,0),(-1,-1), 0.35, colors.HexColor("#a2d9ce")),
        ("VALIGN",        (0,0),(-1,-1), "TOP"),
        ("TOPPADDING",    (0,0),(-1,-1), 3),
        ("BOTTOMPADDING", (0,0),(-1,-1), 3),
        ("LEFTPADDING",   (0,0),(-1,-1), 5),
        ("RIGHTPADDING",  (0,0),(-1,-1), 5),
    ]
    for i in range(1, len(data)):
        rstyles.append(("BACKGROUND",(0,i),(-1,i), LIGHT_TEAL if i%2==0 else WHITE))
    t.setStyle(TableStyle(rstyles))
    return t

def box(text, bg, border, style="warn"):
    t = Table([[Paragraph(text, STYLES[style])]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0),(-1,-1), bg),
        ("LINEBEFORE",   (0,0),(0,-1),  3.5, border),
        ("TOPPADDING",   (0,0),(-1,-1), 6),
        ("BOTTOMPADDING",(0,0),(-1,-1), 6),
        ("LEFTPADDING",  (0,0),(-1,-1), 10),
        ("RIGHTPADDING", (0,0),(-1,-1), 8),
    ]))
    return t

def buls(items, icon="▸"):
    rows = [[Paragraph(f"<b>{icon}</b>", STYLES["bul"]),
             Paragraph(item, STYLES["body"])] for item in items]
    t = Table(rows, colWidths=[0.45*cm, W-0.45*cm])
    t.setStyle(TableStyle([
        ("VALIGN",        (0,0),(-1,-1),"TOP"),
        ("TOPPADDING",    (0,0),(-1,-1), 1),
        ("BOTTOMPADDING", (0,0),(-1,-1), 1),
        ("LEFTPADDING",   (0,0),(-1,-1), 0),
        ("RIGHTPADDING",  (0,0),(-1,-1), 0),
    ]))
    return t

def num_list(items):
    rows = [[Paragraph(f"<b>{i+1}.</b>", STYLES["num"]),
             Paragraph(item, STYLES["body"])] for i,item in enumerate(items)]
    t = Table(rows, colWidths=[0.55*cm, W-0.55*cm])
    t.setStyle(TableStyle([
        ("VALIGN",        (0,0),(-1,-1),"TOP"),
        ("TOPPADDING",    (0,0),(-1,-1), 1),
        ("BOTTOMPADDING", (0,0),(-1,-1), 1),
        ("LEFTPADDING",   (0,0),(-1,-1), 0),
    ]))
    return t

# ═══════════════════════════════════════════════════════════════════════
# CONTENT
# ═══════════════════════════════════════════════════════════════════════
def build():
    story = []

    # ── COVER ──────────────────────────────────────────────────────────
    cover_rows = [
        [Paragraph("EXAM NOTES", STYLES["cover_tag"])],
        [Paragraph("Male &amp; Female<br/>Infertility", STYLES["cover_title"])],
        [Paragraph("Investigations • Interpretation • Differential Diagnosis", STYLES["cover_sub"])],
        [Spacer(1, 0.4*cm)],
        [Paragraph("Investigations | Semen Analysis &amp; Interpretation | Hormonal Assessment<br/>"
                   "Ovarian Reserve | Tubal Patency | Genetic Tests | DDx by Category",
                   STYLES["cover_tag"])],
    ]
    cover = Table(cover_rows, colWidths=[W])
    cover.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,-1), NAVY),
        ("TOPPADDING",    (0,0),(-1,-1), 14),
        ("BOTTOMPADDING", (0,0),(-1,-1), 14),
        ("LEFTPADDING",   (0,0),(-1,-1), 18),
        ("RIGHTPADDING",  (0,0),(-1,-1), 18),
    ]))
    story += [SP(1.5), cover, SP(0.7)]

    # Contents list
    contents = [
        ("PART 1", "MALE INFERTILITY",  "Definition | Causes | Semen Analysis | Interpretation | DDx"),
        ("PART 2", "FEMALE INFERTILITY","Causes | Ovulation | Ovarian Reserve | Tubal Patency | DDx"),
        ("PART 3", "SHARED INVESTIGATIONS","Hormones | Genetic | Imaging | Immunologic"),
        ("PART 4", "HIGH-YIELD EXAM POINTS","15 must-know facts + Investigation Summary Table"),
    ]
    crows = [[Paragraph(f"<b>{p}</b>", STYLES["td"]),
              Paragraph(f"<b>{t}</b>", STYLES["tdb"]),
              Paragraph(sub, STYLES["td"])] for p,t,sub in contents]
    ct = Table(crows, colWidths=[1.5*cm, 5.5*cm, W-7*cm])
    ct.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,-1), PALE_BLUE),
        ("LINEABOVE",     (0,0),(-1,0),  1.5, SKY),
        ("LINEBELOW",     (0,-1),(-1,-1),1.5, SKY),
        ("GRID",          (0,0),(-1,-1), 0.3, BORDER),
        ("TOPPADDING",    (0,0),(-1,-1), 4),
        ("BOTTOMPADDING", (0,0),(-1,-1), 4),
        ("LEFTPADDING",   (0,0),(-1,-1), 6),
        ("VALIGN",        (0,0),(-1,-1),"MIDDLE"),
    ]))
    story += [ct, SP(0.5)]
    story.append(Paragraph(
        "<i>Sources: Campbell-Walsh-Wein Urology | Goldman-Cecil Medicine | "
        "Berek &amp; Novak's Gynecology | Textbook of Family Medicine</i>",
        STYLES["body"]
    ))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════
    # PART 1 — MALE INFERTILITY
    # ══════════════════════════════════════════════════════════════════
    story += [banner("PART 1: MALE INFERTILITY", NAVY), SP(0.2)]

    # Definition
    story += [sub_bar("Definition & Epidemiology"), SP(0.1)]
    story.append(Paragraph(
        "<b>Infertility</b> = failure to achieve a clinical pregnancy after <b>12 months</b> of regular "
        "unprotected sexual intercourse (WHO). Evaluation is warranted at <b>6 months</b> if the female partner "
        "is ≥35 years.", STYLES["body"]))
    story.append(SP(0.1))
    epi_data = [
        ["Statistic", "Value"],
        ["Male factor as sole cause", "~40% of infertile couples"],
        ["Male factor as contributing cause", "Up to 50%"],
        ["Varicocele in idiopathic oligospermia", "31% of men"],
        ["Varicocele in fertile men", "13.5%"],
        ["Unexplained male infertility", "48–50%"],
        ["Idiopathic abnormal semen", "26%"],
    ]
    story.append(mktable(epi_data[0], epi_data[1:], cw=[8*cm, W-8*cm]))
    story.append(SP(0.3))

    # Causes
    story += [sub_bar("Causes of Male Infertility (Diagnostic Categories)"), SP(0.1)]
    causes_data = [
        ["Diagnostic Category", "Incidence (%)", "Key Examples"],
        ["Idiopathic infertility", "50–60", "No identifiable cause; OAT syndrome on semen analysis"],
        ["Varicocele", "15–37", "Dilated pampiniform plexus; raises scrotal temperature"],
        ["Primary testicular failure", "10–20", "Klinefelter (47,XXY), Y microdeletions, mumps orchitis, cryptorchidism, radiation"],
        ["Idiopathic abnormal semen", "26", "Isolated oligospermia/asthenospermia/teratospermia"],
        ["Genital tract obstruction", "5–6", "CBAVD (CFTR mutation), post-vasectomy, epididymal obstruction, ejaculatory duct obstruction"],
        ["Hypogonadotropic hypogonadism", "3–4", "Pituitary adenoma (prolactinoma), Kallmann syndrome, panhypopituitarism"],
        ["Immunologic factors", "3", "Antisperm antibodies (MAR/immunobead test)"],
        ["Infectious factors", "6–7", "Chlamydia, gonorrhea, TB epididymitis"],
        ["Coital / ejaculatory disorders", "<2", "Retrograde ejaculation, hypospadias, anejaculation, erectile dysfunction"],
        ["Other acquired factors", "2–3", "Drugs (sulfasalazine, chemotherapy), toxins, systemic illness"],
    ]
    story.append(mktable(causes_data[0], causes_data[1:],
                          cw=[5.5*cm, 2.5*cm, W-8*cm]))
    story.append(SP(0.3))

    # Semen Analysis
    story += [sub_bar("Semen Analysis — The Cornerstone Investigation"), SP(0.1)]
    story += [
        box("Collection instructions: 2–5 days abstinence, masturbation into sterile container, "
            "analysis within 1 hour. <b>Two abnormal analyses</b> required before proceeding to hormonal workup.",
            GOLD_LITE, GOLD, "ok"),
        SP(0.2)
    ]

    who_data = [
        ["Parameter", "WHO 2010 Reference (5th centile)", "Abnormal Term"],
        ["Volume",                  "≥1.5 mL",       "Hypospermia (<1.5 mL) / Aspermia (0 mL)"],
        ["Sperm concentration",     "≥16 million/mL", "Oligozoospermia (<16 M/mL); Severe: <5 M/mL"],
        ["Total sperm count",       "≥39 million/ejaculate", "Oligozoospermia"],
        ["Total motility (PR+NP)",  "≥42%",           "Asthenozoospermia"],
        ["Progressive motility (PR)","≥30%",          "Asthenozoospermia"],
        ["Morphology (Kruger strict)","≥4% normal forms","Teratozoospermia (<4%)"],
        ["Vitality (live sperm)",   "≥54%",           "Necrozoospermia"],
        ["No sperm",                "—",              "Azoospermia"],
        ["WBC (leukocytes)",        "<1 million/mL",  "Pyospermia / Leukocytospermia (≥1 M/mL)"],
        ["pH",                      "≥7.2",           "Acidic semen (<7.0) → absent seminal vesicles"],
    ]
    story.append(mktable(who_data[0], who_data[1:], cw=[4.5*cm, 4.5*cm, W-9*cm]))
    story.append(SP(0.2))

    story.append(Paragraph("<b>Semen Analysis Terminology</b>", STYLES["h3"]))
    term_data = [
        ["Term", "Meaning"],
        ["Normozoospermia",          "All semen parameters normal"],
        ["Oligozoospermia",          "Reduced sperm concentration (<16 M/mL); Mild-moderate: 5–20; Severe: <5"],
        ["Asthenozoospermia",        "Reduced motility (<42% total or <30% progressive)"],
        ["Teratozoospermia",         "Increased abnormal sperm morphology (<4% normal forms by Kruger)"],
        ["OAT syndrome",             "Oligoasthenoteratozoospermia — all three parameters subnormal"],
        ["Azoospermia",              "No sperm in semen (centrifuged sample)"],
        ["Cryptozoospermia",         "Very rare sperm found only after centrifugation"],
        ["Necrozoospermia",          "All/majority sperm non-viable (confirmed by vitality stain)"],
        ["Pyospermia",               "Leukocytes ≥1 M/mL (confirmed by peroxidase stain / Papanicolaou)"],
        ["Globozoospermia",          "Round-headed sperm — absent acrosome; treat with IVF/ICSI"],
        ["Hypospermia",              "Semen volume <1.5 mL"],
    ]
    story.append(mktable(term_data[0], term_data[1:], cw=[4.5*cm, W-4.5*cm]))
    story.append(SP(0.3))

    # Interpretation
    story += [sub_bar("Interpretation of Semen Analysis Results"), SP(0.1)]
    interp_data = [
        ["Finding", "Differential Diagnosis", "Next Investigation"],
        ["Volume <1.5 mL (hypospermia)", "Ejaculatory duct obstruction | Retrograde ejaculation | CBAVD | Short abstinence",
         "Post-ejaculate urinalysis (retrograde), TRUS (obstruction), CFTR mutation (CBAVD)"],
        ["Azoospermia (no sperm)", "Obstructive azoospermia (OA) | Non-obstructive azoospermia (NOA) | Retrograde ejaculation",
         "FSH + testis volume; if FSH normal + normal testes → OA; if FSH↑ + small testes → NOA; testicular biopsy"],
        ["Severe oligospermia (<5 M/mL)", "Testicular failure | Klinefelter | Y-microdeletion | Varicocele",
         "Karyotype, Y-microdeletion, FSH, testosterone, scrotal USS"],
        ["Asthenospermia only", "Antisperm antibodies | Smoking | Genital infection | Partial obstruction | Immotile cilia syndrome",
         "MAR/immunobead test, culture, ciliary studies"],
        ["Teratospermia only", "Varicocele | Infection | Toxins | Idiopathic",
         "Scrotal USS, culture, lifestyle review"],
        ["Normal volume + azoospermia", "Retrograde ejaculation | Complete obstruction",
         "Post-ejaculate urine, TRUS"],
        ["Acidic pH + low volume", "Absent seminal vesicles (CBAVD) | Ejaculatory duct obstruction",
         "TRUS, CFTR gene testing"],
        ["Sperm agglutination", "Antisperm antibodies",
         "Direct immunobead test (preferred) or MAR test"],
        ["Pyospermia (WBC ≥1 M/mL)", "Genital tract infection (Chlamydia, Ureaplasma, E. coli)",
         "Semen culture, STI screen, urinalysis"],
        ["Round cells only / immature germ cells", "Spermatogenic arrest | Maturation arrest",
         "Peroxidase stain to differentiate from WBC; testicular biopsy"],
    ]
    story.append(mktable(interp_data[0], interp_data[1:],
                          cw=[4.2*cm, 5.8*cm, W-10*cm]))
    story.append(SP(0.2))
    story += [
        box("<b>KEY:</b>  FSH normal + normal testis size → 96% probability of obstructive azoospermia. "
            "FSH elevated + small testes → non-obstructive azoospermia (spermatogenic failure).",
            LIGHT_BLUE, SKY, "ok"),
        SP(0.3)
    ]

    # Hormonal assessment male
    story += [sub_bar("Male Hormonal Assessment"), SP(0.1)]
    mh_data = [
        ["Test", "Normal Value", "Interpretation"],
        ["Total testosterone (morning)", "10–35 nmol/L (300–1000 ng/dL)",
         "Low → hypogonadism. Sample between 7–10 AM (circadian peak). Repeat if borderline."],
        ["Free / bioavailable testosterone", "Calculated from T + SHBG + albumin",
         "More accurate when SHBG is abnormal (obesity lowers SHBG; hepatic disease raises it)"],
        ["LH (luteinising hormone)", "1–9 IU/L",
         "Elevated LH + low T = primary hypogonadism (testicular failure). Low LH + low T = secondary (pituitary/hypothalamic)"],
        ["FSH (follicle-stimulating hormone)", "1–12 IU/L",
         "Elevated FSH = germ cell depletion/testicular failure. Normal FSH + azoospermia → likely obstructive"],
        ["Prolactin", "<25 µg/L (males)",
         "Elevated → hyperprolactinemia (prolactinoma, drugs); suppresses GnRH → low LH/FSH/T"],
        ["Estradiol (E2)", "< 40 pg/mL (males)",
         "Elevated in gynaecomastia, Klinefelter, obesity, testicular tumour"],
        ["SHBG", "Variable with age",
         "Raised SHBG (aging, hepatic disease, hyperthyroidism) → lowers bioavailable T; Lowered (obesity, DM, hypothyroidism) → raises free T"],
        ["Inhibin B", ">80 pg/mL (normal spermatogenesis)",
         "Sertoli cell marker; low = spermatogenic failure; complements FSH in azoospermia evaluation"],
    ]
    story.append(mktable(mh_data[0], mh_data[1:], cw=[3.8*cm, 3.8*cm, W-7.6*cm]))
    story.append(SP(0.2))

    story.append(Paragraph("<b>Pattern Recognition: Hormonal Profiles in Male Infertility</b>", STYLES["h3"]))
    pattern_data = [
        ["Hormonal Pattern", "Diagnosis"],
        ["Low T + High LH + High FSH + small testes", "Primary hypogonadism (testicular failure) — Klinefelter, orchitis, irradiation"],
        ["Low T + Low LH + Low FSH", "Secondary hypogonadism (hypogonadotropic) — pituitary tumour, Kallmann syndrome"],
        ["Low T + High prolactin + Low LH/FSH", "Hyperprolactinemia (prolactinoma) — MRI pituitary"],
        ["Normal T + High FSH + Azoospermia", "Non-obstructive azoospermia (germ cell failure) with preserved Leydig cell function"],
        ["Normal T + Normal FSH + Azoospermia", "Obstructive azoospermia (bilateral) — normal spermatogenesis blocked"],
        ["Normal T + Normal FSH + OAT syndrome", "Varicocele, idiopathic, antisperm antibodies, toxins"],
    ]
    story.append(mktable(pattern_data[0], pattern_data[1:], cw=[7.5*cm, W-7.5*cm]))
    story.append(SP(0.3))

    # Genetic
    story += [sub_bar("Genetic Investigations in Male Infertility"), SP(0.1)]
    gen_data = [
        ["Test", "Indication", "Key Findings"],
        ["Karyotype (peripheral blood)", "Azoospermia, severe oligospermia",
         "47,XXY = Klinefelter (most common genetic cause); 46,XX male; structural chromosomal abnormalities"],
        ["Y-chromosome microdeletion (PCR)", "Azoospermia or severe oligospermia (<5 M/mL)",
         "AZFa deletion → no sperm retrieval (TESE will fail). AZFb → no sperm retrieval. AZFc deletion → sperm may be retrieved by TESE"],
        ["CFTR gene mutation analysis", "CBAVD (congenital bilateral absence of vas deferens)",
         "ΔF508 and other mutations. Screen partner: if both carriers, 25% chance of CF in offspring"],
        ["Antisperm antibodies (MAR/immunobead)", "Sperm agglutination, post-vasectomy reversal, orchitis, trauma",
         ">50% binding = clinically significant. IgA binding to sperm head > tail in significance"],
        ["Sperm DNA fragmentation (SDF)", "Recurrent IVF failure, recurrent miscarriage, idiopathic infertility",
         "DFI >25% associated with poor IVF outcomes; >30% = poor prognosis"],
    ]
    story.append(mktable(gen_data[0], gen_data[1:], cw=[4*cm, 4.5*cm, W-8.5*cm]))
    story.append(SP(0.3))

    # Imaging male
    story += [sub_bar("Imaging in Male Infertility"), SP(0.1)]
    img_data = [
        ["Modality", "Indication", "Key Findings"],
        ["Scrotal colour Doppler USS", "Suspected varicocele, testicular atrophy, mass",
         "Varicocele: dilated veins >2.7–3 mm, retrograde flow. Testis volume normal 15–20 mL. Microlithiasis: benign but note"],
        ["Transrectal USS (TRUS)", "Low volume azoospermia (<1 mL), suspected ejaculatory duct obstruction",
         "Midline prostatic cyst, dilated seminal vesicles (>1.5 cm width), ejaculatory duct dilation"],
        ["Post-ejaculate urinalysis", "Low volume azoospermia",
         "Sperm in urine = retrograde ejaculation. Confirm: >10 sperm/hpf after centrifugation"],
        ["MRI pituitary", "Hyperprolactinemia, low LH/FSH",
         "Microadenoma (<10 mm) or macroadenoma (≥10 mm). Prolactinoma most common"],
        ["Testicular biopsy (TESA/TESE)", "Azoospermia — differentiates OA from NOA; sperm retrieval for ICSI",
         "OA: active spermatogenesis. NOA: maturation arrest, Sertoli-cell-only, hypospermatogenesis"],
    ]
    story.append(mktable(img_data[0], img_data[1:], cw=[4*cm, 4.5*cm, W-8.5*cm]))
    story.append(SP(0.3))

    # DDx male
    story += [sub_bar("Differential Diagnosis — Male Infertility"), SP(0.1)]
    mddx = [
        ["Condition", "Key Features", "Confirming Test"],
        ["Varicocele",
         "Grade I-III; dilated pampiniform plexus; OAT syndrome; left-sided predominance (85%)",
         "Scrotal Doppler USS (vein >3 mm, retrograde flow)"],
        ["Klinefelter syndrome (47,XXY)",
         "Small firm testes (<6 mL), gynaecomastia, tall stature, azoospermia, elevated FSH/LH",
         "Karyotype — 47,XXY. T low, LH/FSH elevated"],
        ["Y-chromosome AZFc deletion",
         "Severe oligospermia or azoospermia; no phenotypic abnormality; normal testis size",
         "Y-microdeletion PCR (AZFa/b/c)"],
        ["Obstructive azoospermia",
         "Normal testis volume, normal FSH, azoospermia; history of vasectomy/infection",
         "Testicular biopsy (normal spermatogenesis), TRUS"],
        ["Hypogonadotropic hypogonadism",
         "Small testes, low T, low LH/FSH, anosmia (Kallmann), or pituitary adenoma",
         "GnRH stimulation test; MRI pituitary"],
        ["Hyperprolactinemia",
         "Low libido, low T, galactorrhea (rare), visual field defect (if macroadenoma)",
         "Serum prolactin; MRI pituitary"],
        ["CBAVD",
         "Absent vas deferens on examination, low volume acidic semen, azoospermia",
         "CFTR mutation; TRUS (absent/small seminal vesicles)"],
        ["Retrograde ejaculation",
         "Low ejaculate volume or anejaculation; DM, alpha-blockers, post-TURP",
         "Post-ejaculate urine: sperm present (>10/hpf)"],
        ["Antisperm antibodies",
         "Sperm agglutination, poor motility despite normal count; history of vasectomy reversal/orchitis",
         "MAR test or direct immunobead test (>50% binding)"],
        ["Cryptorchidism (bilateral)",
         "History of undescended testes; testicular atrophy; elevated FSH",
         "Examination + USS; karyotype if phenotypically abnormal"],
    ]
    story.append(mktable(mddx[0], mddx[1:], cw=[4.2*cm, 5.5*cm, W-9.7*cm]))

    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════
    # PART 2 — FEMALE INFERTILITY
    # ══════════════════════════════════════════════════════════════════
    story += [banner("PART 2: FEMALE INFERTILITY", TEAL), SP(0.2)]

    story += [teal_bar("Causes of Female Infertility"), SP(0.1)]
    fcauses = [
        ["Cause", "Incidence", "Key Conditions"],
        ["Tubal / peritoneal factor",  "30–40%",
         "PID (Chlamydia, gonorrhea), endometriosis with adhesions, post-surgical adhesions, congenital anomalies"],
        ["Ovulatory factor",           "30–40%",
         "PCOS (most common), hypothalamic amenorrhea, hyperprolactinemia, POF/POI, thyroid disease, CAH"],
        ["Decreased ovarian reserve",  "10–15%",
         "Age-related decline, chemotherapy, ovarian surgery, premature ovarian insufficiency"],
        ["Uterine / cervical factors", "10–15%",
         "Asherman syndrome, submucosal fibroids, polyps, septate uterus, DES exposure, cervical stenosis"],
        ["Pelvic / peritoneal factor", "Overlaps tubal",
         "Endometriosis (minimal/mild without adhesions), peritoneal adhesions"],
        ["Immunologic / cervical",     "<5%",
         "Hostile cervical mucus, antisperm antibodies, autoimmune oophoritis"],
        ["Nutritional / metabolic",    "5%",
         "Thyroid disease, diabetes, obesity, severe nutritional deficiency"],
        ["Unexplained infertility",    "10–20%",
         "All standard tests normal; possible subtle ovulatory dysfunction, sperm-egg interaction failure"],
    ]
    story.append(teal_table(fcauses[0], fcauses[1:], cw=[4*cm, 2*cm, W-6*cm]))
    story.append(SP(0.3))

    # Investigations female
    story += [teal_bar("Female Investigations — Ovulation Assessment"), SP(0.1)]
    ov_data = [
        ["Method", "Details", "Normal/Interpretation"],
        ["Basal body temperature (BBT) chart",
         "Temperature recorded daily; rise of 0.2–0.5°C after ovulation (progesterone effect)",
         "Biphasic pattern = ovulation occurred. Monophasic = anovulatory"],
        ["Serum progesterone (Day 21)",
         "Measured 6–8 days before next expected period (mid-luteal phase)",
         ">30 nmol/L (>10 ng/mL) = ovulation confirmed; 16–30 nmol/L = borderline; <16 = anovulatory"],
        ["Urine LH (OPK test)",
         "Detects LH surge preceding ovulation by 24–36 hours",
         "Positive LH surge → ovulation expected within 24–36 h"],
        ["Serial transvaginal USS (TVS)",
         "Monitors follicular development; documents follicle collapse",
         "Gold standard for confirming ovulation; dominant follicle 18–24 mm → collapse = ovulated"],
        ["Endometrial biopsy",
         "Rarely used; histologic dating <3 days before expected menses",
         "Secretory endometrium = ovulation. Now largely replaced by USS + progesterone"],
    ]
    story.append(teal_table(ov_data[0], ov_data[1:], cw=[3.8*cm, 5.5*cm, W-9.3*cm]))
    story.append(SP(0.25))

    story += [teal_bar("Ovarian Reserve Testing"), SP(0.1)]
    story += [
        box("Ovarian reserve = ovarian pool of primordial follicles. Declines with age (sharply after 35). "
            "Poor reserve = low chance of spontaneous conception and poor response to ovarian stimulation.",
            LIGHT_TEAL, TEAL, "ok"),
        SP(0.15)
    ]
    or_data = [
        ["Test", "When Performed", "Normal Value", "Interpretation"],
        ["Serum FSH",
         "Day 2–3 of menstrual cycle",
         "<10 IU/L",
         "10–15 IU/L = diminished reserve; >20 IU/L = poor reserve/POI; >40 IU/L = ovarian failure"],
        ["Serum estradiol (E2)",
         "Day 2–3 (same sample as FSH)",
         "<60–80 pmol/L",
         "Elevated early follicular E2 suppresses FSH artificially — may mask poor reserve. High E2 + 'normal' FSH = poor reserve"],
        ["Anti-Müllerian hormone (AMH)",
         "Any day of cycle (not cycle-dependent)",
         "1.0–3.5 ng/mL (age-variable)",
         "<1.0 ng/mL = diminished reserve; <0.5 = very poor; >3.5 may indicate PCOS. Best single marker."],
        ["Antral follicle count (AFC)",
         "Day 2–4 by transvaginal USS",
         "≥10–15 (both ovaries combined)",
         "<7 = diminished reserve; <4 = poor response to stimulation. Correlates directly with AMH."],
        ["Clomiphene citrate challenge test (CCCT)",
         "FSH Day 3 + clomiphene 100 mg Days 5–9 + FSH Day 10",
         "Day 10 FSH <10 IU/L",
         "Elevated Day 10 FSH = poor reserve; more sensitive than basal FSH alone. Rarely used now (AMH preferred)"],
    ]
    story.append(teal_table(or_data[0], or_data[1:], cw=[3.5*cm, 3.5*cm, 3*cm, W-10*cm]))
    story.append(SP(0.25))

    story += [teal_bar("Tubal Patency Assessment"), SP(0.1)]
    tubal_data = [
        ["Test", "Description", "Advantages / Disadvantages"],
        ["HSG (hysterosalpingography)",
         "Fluoroscopic X-ray with radio-opaque contrast injected through cervix",
         "First-line; shows uterine cavity + tubal patency; therapeutic effect (oil-based contrast); radiation exposure; misses peritoneal disease"],
        ["Saline infusion sonography (SIS / sonohysterography)",
         "Saline instilled into uterine cavity with USS monitoring",
         "Superior for uterine cavity (polyps, fibroids, septa); no radiation; cannot assess tubes reliably"],
        ["HyCoSy (hysterosalpingo-contrast sonography)",
         "USS with echogenic contrast through tubes",
         "No radiation; assesses tubal patency; operator-dependent"],
        ["Laparoscopy + chromopertubation",
         "Methylene blue/indigo carmine dye injected via cervix; observed flowing through fimbriae",
         "GOLD STANDARD: direct visualisation; diagnoses endometriosis + adhesions; surgical; expensive; requires GA"],
    ]
    story.append(teal_table(tubal_data[0], tubal_data[1:], cw=[3.5*cm, 5.5*cm, W-9*cm]))
    story.append(SP(0.25))

    story += [teal_bar("Uterine Cavity & Structural Investigations"), SP(0.1)]
    ut_data = [
        ["Investigation", "Best For", "Notes"],
        ["Transvaginal USS (TVS)", "Uterine fibroids, ovarian cysts, endometrial thickness, AFC",
         "First-line; real-time; operator-dependent"],
        ["Saline infusion sonography (SIS)", "Submucosal fibroids, endometrial polyps, intrauterine synechiae (Asherman)",
         "Better than USS alone for cavity lesions"],
        ["Hysteroscopy", "GOLD STANDARD for intrauterine pathology — polyps, submucosal fibroids, Asherman syndrome, septa",
         "Therapeutic and diagnostic; can biopsy, resect, divide synechiae"],
        ["MRI pelvis", "Mullerian anomalies (bicornuate, septate, unicornuate), deep infiltrating endometriosis, fibroid mapping",
         "Best soft tissue contrast; expensive"],
        ["3D transvaginal USS", "Uterine septum (fundal contour), Mullerian anomalies",
         "Approaches MRI accuracy for congenital anomalies; non-invasive"],
    ]
    story.append(teal_table(ut_data[0], ut_data[1:], cw=[3.8*cm, 5.5*cm, W-9.3*cm]))
    story.append(SP(0.25))

    story += [teal_bar("Female Hormonal Profile"), SP(0.1)]
    fhorm_data = [
        ["Test", "Interpretation / Significance"],
        ["TSH", "Hypothyroidism (elevated TSH) → anovulation, irregular cycles, elevated prolactin. Hyperthyroidism also disrupts ovulation"],
        ["Prolactin", "Elevated → inhibits GnRH pulsatility → anovulation, amenorrhea, galactorrhea. Causes: prolactinoma, drugs (metoclopramide, antipsychotics), hypothyroidism, stress"],
        ["LH:FSH ratio", "LH:FSH >2:1 (or >3:1) on Day 2–3 → strongly suggests PCOS. Both may be low in hypothalamic amenorrhea"],
        ["Free testosterone / total testosterone", "Elevated in PCOS, CAH, androgen-secreting tumour. >5× normal → suspect ovarian/adrenal tumour"],
        ["DHEAS (dehydroepiandrosterone sulfate)", "Adrenal androgen marker. Markedly elevated → adrenal source (CAH, adrenal tumour)"],
        ["17-hydroxyprogesterone (17-OHP)", "Elevated (especially post-ACTH stimulation) → 21-hydroxylase deficiency (CAH). Late-onset CAH mimics PCOS"],
        ["Fasting insulin / glucose / HOMA-IR", "Insulin resistance in PCOS; metabolic syndrome screening; guides treatment (metformin)"],
        ["Estradiol (E2)", "Low in hypothalamic amenorrhea, POI, ovarian failure. Elevated in early follicular phase → poor reserve (as above)"],
        ["Progesterone (Day 21)", "Confirms ovulation (see ovulation assessment above)"],
        ["AMH", "See ovarian reserve above"],
    ]
    story.append(teal_table(fhorm_data[0], fhorm_data[1:], cw=[4.5*cm, W-4.5*cm]))
    story.append(SP(0.3))

    # DDx female
    story += [teal_bar("Differential Diagnosis — Female Infertility"), SP(0.1)]
    fddx = [
        ["Condition", "Key Clinical Features", "Key Investigations"],
        ["PCOS",
         "Oligomenorrhea/amenorrhea, obesity (50-75%), hirsutism, acne, LH:FSH >2:1",
         "USS (≥12 follicles 2–9 mm/ovary OR ovarian volume >10 mL), testosterone, LH:FSH, fasting insulin"],
        ["Hypothalamic amenorrhea",
         "Low BMI (<18.5), athlete, eating disorder, high stress, history of excessive exercise",
         "Low FSH (<3 IU/L), low LH, low estradiol, normal prolactin, normal USS (no follicles/small ovaries)"],
        ["Premature ovarian insufficiency (POI/POF)",
         "Age <40, amenorrhea, hot flashes, night sweats, vaginal dryness",
         "FSH >25 IU/L (×2, 4 weeks apart), low AMH, karyotype (Turner 45,X), FMR1 premutation"],
        ["Hyperprolactinemia",
         "Amenorrhea/oligomenorrhea, galactorrhea (30%), headache, visual field defect",
         "Elevated prolactin; MRI pituitary (microadenoma vs macroadenoma); exclude hypothyroidism, drugs"],
        ["Hypothyroidism",
         "Weight gain, fatigue, cold intolerance, constipation, irregular periods",
         "Elevated TSH, low free T4"],
        ["Tubal disease (PID sequelae)",
         "History of STI, previous PID/ectopic pregnancy, IUD use, pelvic surgery",
         "HSG (blocked tubes, hydrosalpinx); laparoscopy + chromotubation for confirmation"],
        ["Endometriosis",
         "Dysmenorrhea (cyclical pelvic pain), dyspareunia (deep), dyschezia; may be asymptomatic",
         "TVS (ovarian endometrioma 'ground glass'), MRI; GOLD STANDARD: laparoscopy + biopsy. CA-125 unreliable"],
        ["Asherman syndrome",
         "Secondary amenorrhea or hypomenorrhea after uterine instrumentation (D&C, ERPC, myomectomy, endometritis)",
         "SIS or hysteroscopy: intrauterine synechiae/adhesions; MRI in severe cases"],
        ["Submucosal fibroids",
         "Menorrhagia, dysmenorrhea; may be asymptomatic",
         "TVS (hypoechoic mass), SIS (intracavitary), hysteroscopy (type 0/1/2 classification)"],
        ["Septate uterus",
         "Recurrent pregnancy loss, infertility; often asymptomatic",
         "3D TVS or MRI; hysteroscopy + laparoscopy for definitive diagnosis and treatment"],
        ["Cervical factor",
         "History of LLETZ/cone biopsy, cervicitis; abnormal post-coital test",
         "Post-coital test (PCT): <5 motile sperm/hpf = abnormal; cervical mucus culture"],
        ["Unexplained infertility",
         "All standard investigations normal; diagnosis of exclusion (~10–20%)",
         "May have subtle egg-sperm interaction defects; laparoscopy sometimes reveals endometriosis"],
    ]
    story.append(teal_table(fddx[0], fddx[1:], cw=[3.8*cm, 5.8*cm, W-9.6*cm]))

    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════
    # PART 3 — SHARED / IMMUNOLOGIC / OVERVIEW
    # ══════════════════════════════════════════════════════════════════
    story += [banner("PART 3: COMBINED & IMMUNOLOGIC INVESTIGATIONS", ROYAL), SP(0.2)]

    story += [sub_bar("Immunologic Investigations (Both Partners)"), SP(0.1)]
    imm_data = [
        ["Test", "Indication", "Interpretation"],
        ["Antisperm antibodies (MAR / immunobead)",
         "Male: sperm agglutination, vasectomy reversal, orchitis. Female: cervical factor infertility",
         ">50% sperm binding = clinically significant. IgA on sperm head more important than IgG on tail"],
        ["Antinuclear antibodies (ANA)",
         "Suspected autoimmune infertility, recurrent pregnancy loss",
         "Positive ANA → investigate for SLE, antiphospholipid syndrome"],
        ["Antiphospholipid antibodies (aPL)",
         "Recurrent miscarriage (≥3), unexplained infertility",
         "Anticardiolipin IgG/IgM and lupus anticoagulant positive → antiphospholipid syndrome (treat with aspirin + LMWH)"],
        ["NK cell testing / TH1:TH2 ratio",
         "Recurrent implantation failure (controversial)",
         "Elevated uterine NK cells or TH1-skew theorised to impair implantation. No standard clinical guideline yet"],
    ]
    story.append(mktable(imm_data[0], imm_data[1:], cw=[4*cm, 4.5*cm, W-8.5*cm]))
    story.append(SP(0.3))

    story += [sub_bar("Stepwise Investigation Algorithm"), SP(0.1)]
    story.append(Paragraph("<b>Step 1 — Basic (all couples):</b>", STYLES["h3"]))
    story.append(num_list([
        "<b>Semen analysis</b> (×2 if abnormal, 6–12 weeks apart)",
        "<b>Confirm ovulation</b>: mid-luteal progesterone (Day 21) ≥30 nmol/L",
        "<b>Tubal patency</b>: HSG or sonohysterography",
        "<b>Ovarian reserve</b>: Day 2–3 FSH + AMH (or AFC)",
    ]))
    story.append(SP(0.1))
    story.append(Paragraph("<b>Step 2 — Hormonal (if Step 1 abnormal or anovulatory):</b>", STYLES["h3"]))
    story.append(num_list([
        "TSH, prolactin (both partners — hyperprolactinemia)",
        "LH, FSH, estradiol (Day 2–3) — PCOS, hypothalamic amenorrhea, POI",
        "Free testosterone, DHEAS, 17-OHP — hyperandrogenism, CAH",
        "If male: testosterone, LH, FSH (if oligospermia/azoospermia confirmed)",
    ]))
    story.append(SP(0.1))
    story.append(Paragraph("<b>Step 3 — Specialised (if Steps 1–2 inconclusive):</b>", STYLES["h3"]))
    story.append(num_list([
        "Karyotype + Y-microdeletion (azoospermia/severe oligospermia)",
        "CFTR mutation testing (CBAVD)",
        "Laparoscopy + chromopertubation (unexplained infertility, suspected endometriosis)",
        "Hysteroscopy (uterine cavity abnormality on HSG/SIS)",
        "Testicular biopsy (azoospermia — OA vs NOA)",
        "Sperm DNA fragmentation (recurrent IVF failure)",
        "Antiphospholipid antibodies (recurrent pregnancy loss)",
    ]))
    story.append(SP(0.3))

    story += [sub_bar("Master Investigation Summary Table"), SP(0.1)]
    summary = [
        ["Investigation", "Male", "Female"],
        ["First-line",
         "Semen analysis (×2)",
         "Serum progesterone Day 21; BBT chart"],
        ["Ovarian reserve",
         "—",
         "AMH (best), Day 3 FSH + E2, AFC by TVS"],
        ["Hormones — Line 1",
         "Testosterone (morning), LH, FSH, prolactin",
         "TSH, prolactin, Day 3 LH:FSH, estradiol"],
        ["Hormones — Line 2",
         "Estradiol, SHBG, inhibin B",
         "Free testosterone, DHEAS, 17-OHP, fasting insulin"],
        ["Anatomic / structural",
         "Scrotal Doppler USS, TRUS, post-ejaculate urine",
         "TVS, HSG (tubal patency), SIS, hysteroscopy, MRI pelvis"],
        ["Genetic",
         "Karyotype, Y-microdeletion (AZFa/b/c), CFTR",
         "Karyotype (POI: Turner), FMR1 premutation"],
        ["Immunologic",
         "MAR test / immunobead (antisperm Ab)",
         "Antisperm Ab, ANA, antiphospholipid Ab"],
        ["Advanced",
         "Testicular biopsy (TESA/TESE), sperm DNA fragmentation",
         "Laparoscopy + chromopertubation (gold standard tubal), hysteroscopy"],
        ["Pituitary imaging",
         "MRI pituitary (if prolactin elevated or low LH/FSH)",
         "MRI pituitary (prolactinoma, hypopituitarism)"],
    ]
    story.append(mktable(summary[0], summary[1:], cw=[4*cm, 6*cm, W-10*cm]))

    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════
    # PART 4 — HIGH-YIELD EXAM POINTS
    # ══════════════════════════════════════════════════════════════════
    story += [banner("PART 4: HIGH-YIELD EXAM POINTS", colors.HexColor("#6e2f8c")), SP(0.2)]

    hyp = [
        ("1", "Infertility definition",
         "12 months regular unprotected sex (WHO). 6 months if ♀ ≥35 years."),
        ("2", "Most common male cause",
         "Varicocele (15–37%). Most common treatable cause of male infertility."),
        ("3", "Most common female cause overall",
         "Tubal/peritoneal disease (30–40%) — closely followed by ovulatory disorders (30–40%)."),
        ("4", "Most common anovulatory cause in ♀",
         "PCOS — responsible for 70–80% of anovulatory infertility."),
        ("5", "Cornerstone of male infertility investigation",
         "Semen analysis. Must be performed twice (6–12 weeks apart) if abnormal."),
        ("6", "Best single marker of ovarian reserve",
         "AMH (anti-Müllerian hormone) — not cycle-day dependent, most reliable."),
        ("7", "Gold standard for tubal patency",
         "Laparoscopy with chromopertubation. HSG is the first-line test."),
        ("8", "Gold standard for intrauterine pathology",
         "Hysteroscopy — polyps, submucosal fibroids, Asherman syndrome, septa."),
        ("9", "FSH + testis size rule in azoospermia",
         "Normal FSH + normal testes = 96% obstructive azoospermia. Elevated FSH + small testes = non-obstructive (testicular failure)."),
        ("10", "AZF microdeletion prognostic rule",
         "AZFa/b deletion → no sperm retrieval possible (TESE futile). AZFc deletion → sperm may be retrieved."),
        ("11", "CBAVD genetic risk",
         "CFTR mutation (CF gene). If partner also carries severe mutation (e.g., ΔF508) → 25% risk of CF in offspring. Screen partner."),
        ("12", "Klinefelter syndrome key facts",
         "47,XXY. Most common genetic cause of male infertility/azoospermia. Small firm testes, gynaecomastia, elevated FSH/LH, low T."),
        ("13", "Asherman syndrome",
         "Post-curettage intrauterine synechiae → secondary amenorrhea/hypomenorrhea/infertility. Diagnose with hysteroscopy (gold standard)."),
        ("14", "Clomiphene citrate — first-line ovulation induction",
         "Anti-estrogen (acts on hypothalamus). 50 mg/day Days 3–7. Dose escalate in 50 mg steps. Do NOT use in ovarian failure (unresponsive). Monitor with TVS + progesterone."),
        ("15", "Endometriosis in infertility",
         "Gold standard diagnosis = laparoscopy + biopsy. CA-125 is unreliable. Even minimal disease may reduce fecundity."),
        ("16", "Unexplained infertility management",
         "Diagnosis of exclusion (~10–20%). Treat with superovulation + IUI or IVF after 2 years of failed attempts."),
        ("17", "Progesterone Day 21 interpretation",
         ">30 nmol/L = ovulation confirmed. 16–30 = borderline. <16 = anovulatory cycle."),
        ("18", "Retrograde ejaculation diagnosis",
         "Low ejaculate volume (<1 mL) + sperm found in post-ejaculate urine (>10 sperm/hpf after centrifugation)."),
    ]
    hy_rows = [[Paragraph(f"<b>{n}</b>", STYLES["num"]),
                Paragraph(f"<b>{title}</b>", STYLES["tdb"]),
                Paragraph(fact, STYLES["body"])]
               for n, title, fact in hyp]
    hy_tbl = Table(hy_rows, colWidths=[0.6*cm, 5*cm, W-5.6*cm])
    hy_tbl.setStyle(TableStyle([
        ("ROWBACKGROUNDS", (0,0),(-1,-1), [PALE_BLUE, WHITE]),
        ("GRID",          (0,0),(-1,-1), 0.3, BORDER),
        ("VALIGN",        (0,0),(-1,-1),"TOP"),
        ("TOPPADDING",    (0,0),(-1,-1), 4),
        ("BOTTOMPADDING", (0,0),(-1,-1), 4),
        ("LEFTPADDING",   (0,0),(-1,-1), 5),
    ]))
    story.append(hy_tbl)
    story.append(SP(0.4))
    story.append(HRFlowable(width="100%", thickness=1.2, color=NAVY))
    story.append(SP(0.2))
    story.append(Paragraph(
        "<i>Sources: Campbell-Walsh-Wein Urology | Goldman-Cecil Medicine | "
        "Berek &amp; Novak's Gynecology | Textbook of Family Medicine 9e</i>",
        STYLES["body"]
    ))
    return story

def main():
    doc = SimpleDocTemplate(
        OUTPUT, pagesize=A4,
        leftMargin=MARGIN, rightMargin=MARGIN,
        topMargin=1.4*cm, bottomMargin=1.1*cm,
        title="Male & Female Infertility — Exam Notes",
        author="Orris Medical Notes"
    )
    story = build()
    doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
    print(f"Done: {OUTPUT}")

if __name__ == "__main__":
    main()
!

Failed to create session: bad request: failed to resolve container IP after 3 attempts: no IP address found. Is the Sandbox started?

We encountered an error while processing your request. Please try again or reach out to us for help.

Notes to copy not pdf

Got it — plain copyable notes below, no PDF.

MALE & FEMALE INFERTILITY

Exam-Oriented Short Notes


DEFINITIONS

  • Infertility: Failure to achieve clinical pregnancy after 12 months of regular unprotected intercourse (WHO)
  • Subfertility: Reduced capacity to conceive (used interchangeably)
  • Primary infertility: No previous pregnancy ever
  • Secondary infertility: Infertility after at least one prior pregnancy (not necessarily live birth)
  • Evaluate at 6 months if female partner ≥35 years
  • ~90% of couples should conceive within 12 months of unprotected intercourse

PART 1: MALE INFERTILITY

Causes (with Incidence)

Diagnostic CategoryIncidence
Idiopathic (no demonstrable cause)50–60%
Varicocele (most common treatable cause)15–37%
Primary testicular failure (Klinefelter, Y-microdeletion, orchitis, cryptorchidism, radiation)10–20%
Idiopathic abnormal semen26%
Genital tract obstruction (CBAVD, vasectomy, epididymal)5–6%
Hypogonadotropic hypogonadism (prolactinoma, Kallmann)3–4%
Immunologic (antisperm antibodies)3%
Infectious (Chlamydia, gonorrhea, TB)6–7%
Ejaculatory / coital disorders<2%

INVESTIGATIONS OF MALE INFERTILITY

Step 1 — Semen Analysis (Cornerstone)

Collection: 2–5 days abstinence, masturbation, analysed within 1 hour. Two abnormal results (6–12 weeks apart) required before further workup.

WHO 2010 Reference Values (5th centile)

ParameterNormal ValueAbnormal Term
Volume≥1.5 mLHypospermia
Concentration≥16 million/mLOligozoospermia
Total count≥39 million/ejaculateOligozoospermia
Total motility (PR+NP)≥42%Asthenozoospermia
Progressive motility≥30%Asthenozoospermia
Morphology (Kruger strict)≥4% normal formsTeratozoospermia
Vitality≥54% liveNecrozoospermia
WBC<1 million/mLPyospermia
pH≥7.2Acidic: absent seminal vesicles

Semen Terminology

TermMeaning
NormozoospermiaAll parameters normal
OligozoospermiaConcentration <16 M/mL; Severe: <5 M/mL
AsthenozoospermiaMotility <42% total or <30% progressive
Teratozoospermia<4% normal morphology (Kruger strict)
OAT syndromeOligo + Astheno + Terato (all abnormal)
AzoospermiaNo sperm in ejaculate (centrifuged sample)
CryptozoospermiaRare sperm only after centrifugation
NecrozoospermiaAll/majority sperm non-viable (vitality stain)
GlobozoospermiaRound-headed sperm — absent acrosome → IVF/ICSI
PyospermiaWBC ≥1 M/mL (confirmed by peroxidase stain)

Interpretation of Semen Analysis

FindingDifferential DiagnosisNext Investigation
Volume <1.5 mLRetrograde ejaculation, ejaculatory duct obstruction, CBAVD, short abstinencePost-ejaculate urine, TRUS, CFTR
AzoospermiaObstructive (OA) vs Non-obstructive (NOA), retrograde ejaculationFSH + testis volume, testicular biopsy
Severe oligospermia (<5 M/mL)Testicular failure, Klinefelter, Y-microdeletion, varicoceleKaryotype, Y-deletion PCR, FSH, T, USS
Asthenospermia onlyAntisperm antibodies, infection, smoking, immotile ciliaMAR/immunobead test, culture
Teratospermia onlyVaricocele, infection, toxins, idiopathicScrotal USS, semen culture
Sperm agglutinationAntisperm antibodiesDirect immunobead test (preferred) or MAR test
Acidic pH + low volumeCBAVD (absent seminal vesicles), ejaculatory duct obstructionTRUS, CFTR gene test
Pyospermia (WBC ≥1M)Genital infection (Chlamydia, Ureaplasma, E. coli)Semen culture, STI screen
KEY RULE: Normal FSH + normal testis size = 96% probability of obstructive azoospermia. Elevated FSH + small testes = non-obstructive azoospermia (testicular failure).

Step 2 — Male Hormonal Assessment

TestNormalInterpretation
Total testosterone (morning 7–10 AM)10–35 nmol/LLow = hypogonadism. Repeat if borderline.
Free/bioavailable testosteroneCalculated (T + SHBG + albumin)More accurate when SHBG abnormal
LH1–9 IU/LHigh LH + low T = primary hypogonadism; Low LH + low T = secondary
FSH1–12 IU/LElevated = germ cell depletion; Normal + azoospermia = likely obstructive
Prolactin<25 µg/LElevated → prolactinoma or drugs → suppresses GnRH
Estradiol<40 pg/mLElevated in Klinefelter, gynaecomastia, obesity
Inhibin B>80 pg/mLLow = spermatogenic failure; complements FSH in azoospermia

Hormonal Pattern Recognition

PatternDiagnosis
Low T + High LH + High FSH + small testesPrimary hypogonadism (testicular failure — Klinefelter, orchitis)
Low T + Low LH + Low FSHSecondary hypogonadism (pituitary/hypothalamic — prolactinoma, Kallmann)
Low T + High prolactin + Low LH/FSHHyperprolactinemia → MRI pituitary
Normal T + High FSH + AzoospermiaNOA with preserved Leydig cell function
Normal T + Normal FSH + AzoospermiaObstructive azoospermia
Normal T + Normal FSH + OATVaricocele, idiopathic, antisperm antibodies

Step 3 — Genetic Investigations

TestIndicationKey Findings
KaryotypeAzoospermia, severe oligospermia47,XXY = Klinefelter (most common genetic cause)
Y-chromosome microdeletion (PCR)Azoospermia, <5 M/mLAZFa/b deletion = no sperm retrieval (TESE futile); AZFc deletion = sperm may be retrieved
CFTR gene mutationCBAVD (absent vas on exam)ΔF508 and others; screen partner — if both carry severe mutation, 25% risk CF in offspring
Antisperm antibodies (MAR/immunobead)Agglutination, post-vasectomy reversal, orchitis>50% binding = significant; IgA on sperm head > tail in clinical importance
Sperm DNA fragmentation (SDF)Recurrent IVF failure, recurrent miscarriageDFI >25% = poor IVF outcomes; >30% = poor prognosis

Step 4 — Imaging (Male)

ModalityIndicationFindings
Scrotal colour Doppler USSSuspected varicocele, testicular atrophy/massVein >3 mm with retrograde flow = varicocele; normal testis volume 15–20 mL
Transrectal USS (TRUS)Low volume azoospermia (<1 mL)Ejaculatory duct dilation, midline cyst, absent/dilated seminal vesicles (>1.5 cm)
Post-ejaculate urinalysisLow volume azoospermiaSperm in urine (>10/hpf) = retrograde ejaculation
MRI pituitaryElevated prolactin, low LH/FSHMicroadenoma (<10 mm) or macroadenoma (≥10 mm)
Testicular biopsy (TESA/TESE)Azoospermia — OA vs NOA; sperm retrievalOA: active spermatogenesis; NOA: maturation arrest, Sertoli-cell-only, hypospermatogenesis

DIFFERENTIAL DIAGNOSIS — MALE INFERTILITY

ConditionKey FeaturesConfirming Test
VaricoceleGrade I–III; dilated pampiniform plexus; OAT syndrome; predominantly left-sided (85%)Scrotal Doppler USS (vein >3 mm, retrograde flow)
Klinefelter (47,XXY)Small firm testes (<6 mL), gynaecomastia, tall stature, azoospermia, elevated FSH/LHKaryotype — 47,XXY
Y-chromosome AZFc deletionSevere oligospermia/azoospermia; no phenotypic abnormality; normal testis sizeY-microdeletion PCR
Obstructive azoospermiaNormal testis volume, normal FSH, azoospermia; history of vasectomy or infectionTesticular biopsy (normal spermatogenesis), TRUS
Non-obstructive azoospermiaElevated FSH, small soft testes, azoospermiaTesticular biopsy (maturation arrest / SCO)
Hypogonadotropic hypogonadismSmall testes, low T, low LH/FSH; anosmia (Kallmann); or pituitary adenomaGnRH stimulation test; MRI pituitary
HyperprolactinemiaLow libido, low T, galactorrhea (rare), visual field defectSerum prolactin; MRI pituitary
CBAVDAbsent vas deferens on examination, low volume acidic semen, azoospermiaCFTR mutation; TRUS (absent/small seminal vesicles)
Retrograde ejaculationLow volume (<1 mL); DM, alpha-blockers, post-TURPPost-ejaculate urine: sperm >10/hpf
Antisperm antibodiesSperm agglutination, poor motility despite normal count; post-vasectomy reversalMAR test / immunobead test (>50% binding)
Cryptorchidism (bilateral)History of undescended testes; testicular atrophy; elevated FSHExamination + USS; karyotype if abnormal


PART 2: FEMALE INFERTILITY

Causes (with Incidence)

CauseIncidenceKey Conditions
Tubal / peritoneal disease30–40%PID (Chlamydia, gonorrhea), endometriosis with adhesions, post-surgical adhesions
Ovulatory disorders30–40%PCOS (most common, 70–80% of anovulatory cases), hypothalamic amenorrhea, hyperprolactinemia, POI/POF, thyroid disease, CAH
Decreased ovarian reserve10–15%Age-related decline, chemotherapy, ovarian surgery, POI
Uterine / cervical factors10–15%Asherman syndrome, submucosal fibroids, polyps, septate uterus, cervical stenosis
Unexplained infertility10–20%All standard tests normal; diagnosis of exclusion
Immunologic / cervical<5%Hostile cervical mucus, antisperm antibodies
Nutritional / metabolic5%Hypothyroidism, DM, obesity, severe deficiency

INVESTIGATIONS OF FEMALE INFERTILITY

A. Ovulation Assessment

MethodDetailsInterpretation
BBT chart (Basal Body Temperature)Temperature daily; thermometer each morning before risingBiphasic rise of 0.2–0.5°C after ovulation = ovulated. Monophasic = anovulatory
Serum progesterone (Day 21)Taken 6–8 days before next expected period>30 nmol/L = ovulation confirmed; 16–30 = borderline; <16 = anovulatory
Urine LH (ovulation predictor kit)Detects LH surgePositive → ovulation within 24–36 hours
Serial transvaginal USS (TVS)Tracks follicle growth; documents collapseGold standard — dominant follicle 18–24 mm then collapse = ovulated
Endometrial biopsyRarely used now; <3 days before mensesSecretory endometrium = ovulation; largely replaced by USS + progesterone

B. Ovarian Reserve Testing

Ovarian reserve = pool of primordial follicles. Declines with age; sharply after 35. Poor reserve = low chance of conception and poor response to ovarian stimulation.
TestWhenNormalInterpretation
Serum FSHDay 2–3<10 IU/L10–15 = diminished; >20 = poor reserve; >40 = ovarian failure
Estradiol (E2)Day 2–3 (same sample)<60–80 pmol/LElevated early E2 suppresses FSH artificially — high E2 + "normal" FSH = poor reserve
AMH (Anti-Müllerian hormone)Any day (not cycle-dependent)1.0–3.5 ng/mLBest single marker. <1.0 = diminished; <0.5 = very poor; >3.5 = may indicate PCOS
Antral follicle count (AFC)Day 2–4 by TVS≥10–15 (both ovaries)<7 = diminished reserve; <4 = poor stimulation response; correlates with AMH
Clomiphene Citrate Challenge Test (CCCT)FSH Day 3 + clomiphene 100 mg Days 5–9 + FSH Day 10Day 10 FSH <10 IU/LElevated Day 10 FSH = poor reserve; rarely used now (AMH preferred)

C. Tubal Patency Assessment

TestDescriptionAdvantages / Limitations
HSG (Hysterosalpingography)Fluoroscopic X-ray with radio-opaque contrast via cervixFirst-line; shows tubal patency + uterine cavity; therapeutic (oil-based contrast flushes tubes); radiation; misses peritoneal disease
Saline infusion sonography (SIS)Saline into uterine cavity + USSSuperior for uterine cavity (polyps, fibroids, septa); no radiation; cannot assess tubes reliably
HyCoSyUSS with echogenic contrast through tubesNo radiation; assesses tubes; operator-dependent
Laparoscopy + chromopertubationMethylene blue dye injected via cervix; observed at fimbriaeGOLD STANDARD — direct visualisation; diagnoses endometriosis + adhesions; surgical; requires GA

D. Uterine Cavity Investigations

InvestigationBest ForNotes
Transvaginal USS (TVS)Fibroids, ovarian cysts, endometrial thickness, AFCFirst-line; real-time
Saline infusion sonography (SIS)Submucosal fibroids, polyps, Asherman synechiaeBetter than TVS alone for cavity lesions
HysteroscopyGold standard for intrauterine pathology — polyps, fibroids, Asherman, septaTherapeutic and diagnostic; biopsy, resect, divide synechiae
MRI pelvisMullerian anomalies, deep endometriosis, fibroid mappingBest soft tissue contrast; expensive
3D transvaginal USSUterine septum, Mullerian anomaliesApproaches MRI accuracy; non-invasive

E. Female Hormonal Profile

TestInterpretation
TSHHypothyroidism (elevated TSH) → anovulation, irregular cycles, elevated prolactin
ProlactinElevated → inhibits GnRH pulsatility → anovulation, amenorrhea, galactorrhea. Causes: prolactinoma, drugs (metoclopramide, antipsychotics), hypothyroidism
LH:FSH ratio (Day 2–3)LH:FSH >2:1 → strongly suggests PCOS. Both low → hypothalamic amenorrhea
Free testosterone / total testosteroneElevated in PCOS, CAH, androgen-secreting tumour. >5× normal → suspect ovarian/adrenal tumour
DHEASMarkedly elevated → adrenal source (CAH, adrenal tumour)
17-hydroxyprogesterone (17-OHP)Elevated (especially post-ACTH stimulation) → 21-hydroxylase deficiency (CAH); late-onset CAH mimics PCOS
Fasting insulin / glucose / HOMA-IRInsulin resistance in PCOS; guides metformin therapy
EstradiolLow in hypothalamic amenorrhea, POI, ovarian failure
AMHSee ovarian reserve above

DIFFERENTIAL DIAGNOSIS — FEMALE INFERTILITY

ConditionKey FeaturesKey Investigations
PCOSOligomenorrhea/amenorrhea, obesity (50–75%), hirsutism, acne, LH:FSH >2:1TVS (≥12 follicles 2–9 mm per ovary OR ovarian volume >10 mL), testosterone, fasting insulin
Hypothalamic amenorrheaLow BMI (<18.5), athlete, eating disorder, excessive exercise, stressLow FSH (<3), low LH, low estradiol, normal prolactin, small ovaries on USS
Premature ovarian insufficiency (POI/POF)Age <40, amenorrhea, hot flashes, night sweats, vaginal drynessFSH >25 IU/L (×2, 4 weeks apart), low AMH, karyotype (Turner 45,X), FMR1 premutation
HyperprolactinemiaAmenorrhea/oligomenorrhea, galactorrhea (30%), headache, visual field defectElevated prolactin; MRI pituitary; exclude hypothyroidism and drugs
HypothyroidismWeight gain, fatigue, cold intolerance, constipation, irregular periodsElevated TSH, low free T4
Tubal disease (PID sequelae)History of STI, previous PID, ectopic pregnancy, IUD, pelvic surgeryHSG (blocked tubes, hydrosalpinx); laparoscopy + chromopertubation (gold standard)
EndometriosisDysmenorrhea (cyclical pelvic pain), deep dyspareunia, dyschezia; may be asymptomaticTVS (ovarian endometrioma - "ground glass"), MRI; GOLD STANDARD: laparoscopy + biopsy. CA-125 unreliable
Asherman syndromeSecondary amenorrhea or hypomenorrhea after D&C, ERPC, myomectomy, or endometritisSIS or hysteroscopy (intrauterine synechiae); MRI in severe cases
Submucosal fibroidsMenorrhagia, dysmenorrhea; may be asymptomaticTVS, SIS (intracavitary), hysteroscopy (type 0/1/2 ESGE classification)
Septate uterusRecurrent pregnancy loss, infertility; often asymptomatic3D TVS or MRI; hysteroscopy + laparoscopy for definitive diagnosis and treatment
Cervical factorHistory of LLETZ/cone biopsy, cervicitis; abnormal post-coital testPost-coital test: <5 motile sperm/hpf = abnormal; cervical culture
Unexplained infertilityAll standard investigations normal; diagnosis of exclusionLaparoscopy (may reveal endometriosis); treat with superovulation + IUI or IVF


PART 3: STEPWISE INVESTIGATION ALGORITHM

Step 1 — Basic (All Couples)

  1. Semen analysis (×2 if abnormal, 6–12 weeks apart)
  2. Confirm ovulation: Mid-luteal progesterone (Day 21) ≥30 nmol/L
  3. Tubal patency: HSG or sonohysterography
  4. Ovarian reserve: Day 2–3 FSH + AMH (or AFC)

Step 2 — Hormonal (if Step 1 abnormal or anovulatory)

  1. TSH, prolactin (both partners)
  2. LH, FSH, estradiol (Day 2–3) — PCOS, hypothalamic amenorrhea, POI
  3. Free testosterone, DHEAS, 17-OHP — hyperandrogenism, CAH
  4. Testosterone, LH, FSH in male — if oligospermia/azoospermia confirmed

Step 3 — Specialised (if Steps 1–2 inconclusive)

  1. Karyotype + Y-microdeletion (azoospermia/severe oligospermia)
  2. CFTR mutation testing (CBAVD)
  3. Laparoscopy + chromopertubation (unexplained infertility, suspected endometriosis)
  4. Hysteroscopy (uterine cavity abnormality on HSG/SIS)
  5. Testicular biopsy (azoospermia — OA vs NOA)
  6. Sperm DNA fragmentation (recurrent IVF failure)
  7. Antiphospholipid antibodies (recurrent pregnancy loss)

Master Investigation Summary

InvestigationMaleFemale
First-lineSemen analysis (×2)Serum progesterone Day 21; BBT chart
Ovarian reserveAMH (best), Day 3 FSH + E2, AFC by TVS
Hormones Line 1Testosterone (morning), LH, FSH, prolactinTSH, prolactin, Day 3 LH:FSH, estradiol
Hormones Line 2Estradiol, SHBG, inhibin BFree testosterone, DHEAS, 17-OHP, fasting insulin
AnatomicScrotal Doppler USS, TRUS, post-ejaculate urineTVS, HSG (tubal patency), SIS, hysteroscopy, MRI pelvis
GeneticKaryotype, Y-microdeletion (AZFa/b/c), CFTRKaryotype (Turner 45,X), FMR1 premutation
ImmunologicMAR test / immunobead (antisperm Ab)Antisperm Ab, ANA, antiphospholipid Ab
AdvancedTesticular biopsy (TESA/TESE), sperm DNA fragmentationLaparoscopy + chromopertubation, hysteroscopy
Pituitary imagingMRI pituitary (prolactin elevated, low LH/FSH)MRI pituitary (prolactinoma, hypopituitarism)


PART 4: HIGH-YIELD EXAM POINTS

  1. Infertility definition: 12 months (WHO); 6 months if female ≥35 years
  2. Most common male cause: Varicocele (15–37%) — most common treatable cause
  3. Most common female cause overall: Tubal/peritoneal disease (30–40%)
  4. Most common anovulatory cause in females: PCOS (70–80% of anovulatory infertility)
  5. Cornerstone of male investigation: Semen analysis — must be done twice if abnormal
  6. Best single ovarian reserve marker: AMH — not cycle-day dependent; most reliable
  7. Gold standard tubal patency: Laparoscopy with chromopertubation. HSG = first-line test
  8. Gold standard intrauterine pathology: Hysteroscopy
  9. FSH + testis size in azoospermia: Normal FSH + normal testes = 96% obstructive; Elevated FSH + small testes = non-obstructive
  10. AZF microdeletion rule: AZFa/b deletion = TESE futile (no sperm retrievable). AZFc deletion = sperm may be retrieved by TESE
  11. CBAVD genetic risk: CFTR mutation — screen partner; 25% risk of CF in offspring if both carry severe mutation
  12. Klinefelter syndrome (47,XXY): Most common genetic cause of male infertility/azoospermia. Small firm testes, gynaecomastia, elevated FSH/LH, low T
  13. Asherman syndrome: Post-curettage intrauterine synechiae → secondary amenorrhea/infertility. Gold standard diagnosis = hysteroscopy
  14. Clomiphene citrate: First-line ovulation induction; anti-estrogen; 50 mg Days 3–7; DO NOT use in ovarian failure; monitor with TVS + progesterone
  15. Endometriosis: Gold standard diagnosis = laparoscopy + biopsy. CA-125 is unreliable. Even minimal disease may reduce fecundity
  16. Progesterone Day 21: >30 nmol/L = ovulated; 16–30 = borderline; <16 = anovulatory
  17. Retrograde ejaculation: Low volume + sperm in post-ejaculate urine (>10/hpf after centrifugation)
  18. Unexplained infertility: 10–20%; treat with superovulation + IUI, or IVF after 2 years

Sources: Campbell-Walsh-Wein Urology | Goldman-Cecil Medicine | Berek & Novak's Gynecology | Textbook of Family Medicine 9e
This is a shared conversation. Sign in to Orris to start your own chat.