Wallerian and degeneration and regeneration.

Reading File
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Loading Image
Finding Sources
Reading File
Reading File
Loading Image
Reading File
Loading Image
I now have comprehensive information for a thorough answer. Let me compose it.

Wallerian Degeneration and Nerve Regeneration

Overview

Large myelinated peripheral axons respond to injury in three main ways: segmental demyelination, Wallerian degeneration, and axonal degeneration. Wallerian degeneration and segmental demyelination are primarily relevant to traumatic nerve injury; axonal degeneration is more typical of metabolic and toxic neuropathies (e.g., diabetes, renal failure). - Bradley and Daroff's Neurology in Clinical Practice

Segmental Demyelination

When a focal nerve segment is subjected to a mild compressive or traction force, myelin sheath damage occurs at one or several internodes while segments distal and proximal remain intact. Consequences depend on severity:
  • Mild damage: widened nodes of Ranvier → slowed conduction velocity → paresthesia
  • Moderate damage: asynchronous conduction → affects functions requiring synchronized firing (deep tendon reflexes, vibration sense)
  • Severe compression: tourniquet-type injury causes telescoping of axon and myelin at paranodal segments → focal demyelinating conduction block and weakness
This corresponds to a grade I (neurapraxia) injury.

Wallerian Degeneration

Named after Augustus Waller (1850), Wallerian degeneration follows grade II–V nerve injuries and involves both the axon distal and proximal to the injury site.
Fig. 64.4 - Wallerian Degeneration after axotomy, showing chromatolysis of the cell body, myelin debris, and macrophage infiltration distal to the transection site, with muscle degeneration.

Distal Segment Changes

The process begins within hours of injury and is complete within approximately 1 week:
  1. Disruption of axonal transport - retrograde and anterograde signaling is interrupted immediately.
  2. Ion influx - rapid inflow of extracellular calcium and sodium through the disrupted axonal membrane activates a cascade resembling apoptosis.
  3. Cytokine signaling - leukocytes are recruited; cytokine-mediated cascades trigger synthesis of neurotrophins, chemokines, extracellular matrix molecules, and proteolytic enzymes.
  4. By day 3 - Schwann cells retract from the node of Ranvier.
  5. Schwann cell reprogramming - activated by upregulation of c-Jun protein, Schwann cells dedifferentiate from myelin-manufacturing cells into repair Schwann cells. They downregulate promyelin transcription factors, trigger myelin autophagy, secrete glial growth factors (neuregulins), and recruit macrophages.
  6. Myelin digestion - repair Schwann cells and macrophages phagocytose myelin debris. This step is critical because myelin debris contains inhibitors of axon regeneration - its clearance is essential before regeneration can proceed.
  7. Granular disintegration - cytoskeletal components (microtubules, neurofilaments) disassemble; the axon fragments completely.
The degeneration of an axon distal to the injury site is also called anterograde (Wallerian) degeneration. - Histology: A Text and Atlas, Pawlina

Proximal Segment Changes

  • Axon breakdown extends proximally only to the first node of Ranvier.
  • The cell body undergoes chromatolysis: breakup and dispersion of the rough endoplasmic reticulum (Nissl substance), eccentric displacement of the nucleus, and increased transcription factor expression that switches the cell from axon maintenance to protein synthesis mode (regenerative state).
  • Very proximal injuries (e.g., avulsion near the spinal cord) may cause apoptosis of the cell body itself, preventing regeneration.

Nerve Regeneration

Recovery mechanism depends on the grade of injury:
Injury GradeMechanismTimescale
Grade I (neurapraxia)RemyelinationWeeks to months
Grade II–V (axonotmesis / neurotmesis)Collateral sprouting + axon regeneration3–24 months

1. Remyelination (Grade I)

Schwann cells divide and initiate remyelination. The new myelin is thinner and has more internodes per original internode, which can slow conduction slightly. Recovery is generally complete within weeks to months.

2. Collateral Sprouting (Partial Injury)

When only some axons are damaged, intact adjacent motor axons produce sprouts from:
  • Nodal sprouts (from nodes of Ranvier), or
  • Terminal sprouts (from nerve terminals)
These appear as early as 4 days after injury and reinnervate denervated muscle fibers, increasing motor unit size and contractile force. Clinical recovery from collateral sprouting takes 3–6 months. Remaining innervated muscle fibers undergo compensatory hypertrophy, though the overall muscle atrophies.

3. Axon Regeneration (Severe/Complete Injury)

In severe or complete nerve injuries, regeneration from the proximal stump begins only after Wallerian degeneration is complete.
Schwann cells are the key drivers. They:
  • Dedifferentiate and upregulate adhesion molecules and neurotrophins (cadherins, immunoglobulin superfamily factors, laminin)
  • Proliferate and arrange in linear columns within the original basal lamina - these are the bands of Büngner, which provide the scaffold for axon regrowth
The growth cone at the tip of each axon sprout extends filopodia (finger-like) and lamellipodia (sheet-like) to navigate the regeneration pathway.
Fig. 64.5 - Growth cone at the tip of an axon sprout advancing through bands of Büngner, guided by lamellipodia and filopodia, with macrophage clearing debris ahead.
Neurotropism - the directional guidance of the regenerating axon - is accomplished by guidance molecules:
  • Semaphorins, ephrins, netrins, slits - attract or repulse growth cones
  • The growth cone secretes plasminogen activators to dissolve debris plugging endoneurial tubules
Rate of regrowth: approximately 1–2 mm/day (roughly 1 inch/month). Proximal lesions may regenerate faster (2–3 mm/day) than distal lesions (~1 mm/day). This is also the basis of the Hoffmann-Tinel sign - percussion over the regenerating nerve elicits tingling at the level of advancing sprouts.
Trophic support is provided by a range of molecules including NGF, BDNF, neurotrophins 3 and 4, GDNF family factors (neurturin, artemin, persephin), IGF, IL-6, CNTF, and FGF. - Bradley and Daroff's Neurology in Clinical Practice, p. 1335

Timeline of Degeneration and Regeneration

Diagram showing Normal, Early, Late, and Recovering stages of axonal degeneration (both CNS and PNS), illustrating progressive axon fragmentation in PNS with subsequent axon regeneration, versus CNS astrocyte proliferation and failed regeneration.
TimepointEvent
ImmediatelyDisruption of axonal transport; ion influx; apoptotic cascade
8–24 hoursFirst sign: axonal swelling
Day 3Schwann cells retract from nodes of Ranvier; macrophage recruitment begins
~1 weekWallerian degeneration complete distally; Büngner bands formed
Day 4 onwardCollateral sprouting begins (partial injuries)
~3 monthsAxon regeneration begins contributing to recovery
6–24 monthsAxon regeneration is the dominant recovery mechanism
>4 months (gap uncrossed)Distal endoneurial tube shrinks to <3 μm; recovery impeded
Up to 2–3 yearsLate sensory reinnervation may still yield useful protective function

Factors Determining Outcome

  1. Endoneurial tube integrity - if intact, regenerating axon has a much better chance. If disrupted, axons stray into connective tissue → neuroma formation → ectopic sodium channel accumulation → neuropathic pain.
  2. Gap length - longer gaps delay regeneration crossing and increase mismatched reinnervation.
  3. Proximity to cell body - very proximal injuries risk cell body apoptosis; axons need more time to reach targets.
  4. End organ viability:
    • Denervated muscle tolerates up to ~1 year before irreversible fibrosis
    • Sensory receptors (Meissner corpuscles, Merkel cells) survive longer; even late reinnervation at 2–3 years may restore protective sensation
  5. Rate of regeneration - at 1 mm/day, a nerve injury 30 cm proximal to a hand target takes ~300 days just for axons to arrive, before remodeling begins

PNS vs. CNS Regeneration

FeaturePNSCNS
Schwann cell responseRapid dedifferentiation into repair cells, clear myelin debris, form Büngner bandsOligodendrocytes do not phagocytose debris efficiently
Macrophage accessBlood-nerve barrier permissive; macrophages recruited freelyBlood-brain barrier restricts macrophage entry
Myelin debris clearanceRapid (~1 week)Slow; debris persists and inhibits regeneration
OutcomeAxon regeneration generally occursAxons usually cannot regenerate; astrocyte scar forms instead
The fundamental reason CNS axons cannot regenerate is the persistence of myelin debris (which contains inhibitors of axon regeneration) combined with glial scar formation by astrocytes. - Histology: A Text and Atlas, Pawlina

Sources: Bradley and Daroff's Neurology in Clinical Practice, pp. 1334–1336 | Histology: A Text and Atlas (Pawlina) | THIEME Atlas of Anatomy - General Anatomy and Musculoskeletal System

White muscle fibres Classification and properties of nerve fibres

Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Loading Image
I now have everything needed for a comprehensive, well-sourced answer. Let me compose it.

Part 1: White Muscle Fibres (and the Full Muscle Fibre Classification)

Classification of Skeletal Muscle Fibres

Individual skeletal muscle fibres are classified as slow-twitch (Type I) or fast-twitch (Type II) based on their rate of force development, histological appearance, and fatigue resistance. Fast-twitch fibres are further divided into Type IIa and Type IIx/IIb. - Medical Physiology (Boron & Boulpaep)

Quick Comparison Table

PropertyType I (Slow-twitch)Type IIa (Fast oxidative)Type IIx/IIb (Fast glycolytic)
ColourRedRedWhite
MyoglobinHighHighLow
MetabolismOxidative (aerobic)Oxidative + glycolyticGlycolytic (anaerobic)
MitochondriaManyMore than Type IFew
GlycogenLowAbundantHigh
Glycolytic enzymesLowModerateHigh
Myosin ATPaseSlowFastFastest
FatigueResistantResistantEasily fatigable
DiameterSmallerIntermediate~2x Type I
Capillary densityHighHighLower
UseEndurance, postureMixedPower, sprint

White Muscle Fibres (Type IIx/IIb)

White fibres are the classic fast-twitch glycolytic fibres - the "white" appearance comes directly from their low myoglobin content (compare to red fibres which are rich in myoglobin). Key properties:
  1. Large diameter - about twice that of slow-twitch fibres. Larger fibre diameter generates greater contractile force.
  2. High myosin ATPase activity - the enzymes promoting rapid energy release from the phosphagen and glycogen-lactic acid systems are 2–3 times as active as in slow-twitch fibres. This gives white fibres approximately twice the maximal power of slow-twitch fibres for short bursts. - Guyton & Hall Textbook of Medical Physiology
  3. Anaerobic (glycolytic) metabolism - rely almost exclusively on stored glycogen and phosphocreatine for ATP. Cannot sustain contraction through oxidative metabolism.
  4. Rapid fatigue - because they depend on finite glycogen/phosphocreatine stores with no efficient aerobic backup. They can deliver extreme power for seconds to about a minute.
  5. Fewer mitochondria and capillaries - reflecting their independence from oxidative phosphorylation.

Key Distinction: Type IIa vs Type IIx/IIb

Type IIa are also fast-twitch but fatigue-resistant - they retain significant oxidative capacity (red in colour, rich in myoglobin and mitochondria). They are sometimes called fast oxidative fibres. True white fibres (IIx/IIb) are fatigable because of insufficient oxidative metabolism to sustain contraction. - Medical Physiology (Boron & Boulpaep)

Genetic and Athletic Relevance

Fast- vs slow-twitch fibre ratio is largely genetically determined, with training capable of shifting proportions by about 10%. Representative quadriceps data from Guyton & Hall:
Athlete typeFast-twitch %Slow-twitch %
Marathoners1882
Swimmers2674
Average person5545
Weight lifters5545
Sprinters/Jumpers6337
Examples: The gastrocnemius (jumping, rapid plantarflexion) is rich in fast-twitch fibres; the soleus (sustained postural support) is rich in slow-twitch fibres. - Guyton & Hall

Part 2: Classification and Properties of Nerve Fibres

Nerve fibres are classified by conduction velocity, which depends on two factors:
  • Fibre diameter: larger diameter = higher conduction velocity
  • Myelination: myelin sheath dramatically increases velocity via saltatory conduction
Two classification systems are used. - Costanzo Physiology, 7th Edition

System 1: Erlanger-Gasser Classification (A, B, C)

Applies to both sensory and motor fibres. Uses letters and Greek-letter subdivisions.
Physiological classifications and functions of nerve fibres - showing both general (A/C) and sensory (I-IV) systems with diameter, conduction velocity, sensory functions and motor functions mapped against fibre size.

Type A Fibres (Large to medium, myelinated)

SubtypeDiameter (µm)Conduction Velocity (m/s)Function
15–2080–120Alpha motor neurons to extrafusal muscle fibres; proprioception (muscle spindle primary endings, Golgi tendon organs)
8–1530–70Touch, pressure (skin mechanoreceptors); small motor
4–830–70Gamma motor neurons to intrafusal muscle spindle fibres
3–410–30Temperature, sharp/pricking pain, nociception, crude touch

Type B Fibres (Small, myelinated)

Diameter (µm)Conduction Velocity (m/s)Function
3–410–15Preganglionic autonomic fibres only

Type C Fibres (Unmyelinated)

Diameter (µm)Conduction Velocity (m/s)Function
0.5–20.5–2Slow/aching pain, temperature, crude touch; postganglionic autonomic fibres; olfaction
C fibres constitute more than half of all sensory fibres in most peripheral nerves, and all postganglionic autonomic fibres are C fibres. - Guyton & Hall
A large Aα fibre can conduct at up to 120 m/sec (longer than a football field per second). A C fibre conducting at 0.5 m/sec takes about 2 seconds to travel from the big toe to the spinal cord. - Guyton & Hall

System 2: Lloyd-Hunt Classification (I, II, III, IV)

Applies to sensory fibres only. Preferred by sensory physiologists because certain recording techniques can separate Aα subgroups but cannot easily distinguish Aβ from Aγ.
GroupDiameter (µm)Corresponds toOrigin / Function
Ia~17Annulospiral (primary) endings of muscle spindles - muscle length + velocity
Ib~16Golgi tendon organ afferents - muscle tension
II~8Aβ, AγSecondary (flower-spray) endings of muscle spindles; discrete cutaneous tactile receptors (touch, pressure)
III~3Temperature, crude touch, pricking pain
IV0.5–2CPain, temperature, itch, crude touch (unmyelinated)
  • Guyton & Hall, p. 587; Costanzo Physiology, p. 80

Sensitivity to Local Anaesthetics

Smaller fibres are blocked at lower anaesthetic concentrations - clinical relevance for differential spinal blocks:
FibreDiameter (µm)Block concentration (% approx.)Blocked first/last
15–20~1%Last (motor)
3–4~0.5%Intermediate (pain)
B3–4~0.25%Early (autonomic)
C1–2~0.5%Early (slow pain)
This explains the classic sequence of differential spinal: autonomic → sensory → motor block. - Campbell's Operative Orthopaedics, 15th Ed. 2026

Summary Mnemonic: A-B-C

  • A fibres - All myelinated, All motor + sensory (except Aδ which is mainly sensory)
  • B fibres - Barely myelinated, Before the ganglion (preganglionic autonomic only)
  • C fibres - Cannot see myelin (unmyelinated), Chronic pain and postganglionic autonomic

Saltatory conduction and rigor mortis

Finding Sources
Finding Sources
Reading File
Reading File
Finding Sources
Reading File
Reading File
Reading File
Reading File
Loading Image
Loading Image
Reading File
Reading File
Reading File
Reading File
I now have everything needed for a complete answer on both topics.

Part 1: Saltatory Conduction

The Problem It Solves

In unmyelinated fibres, an action potential propagates by depolarising every adjacent patch of membrane in sequence - slow, continuous conduction that uses enormous amounts of energy. Vertebrates solved this with myelin. The largest mammalian axons conduct ~400 times faster than the thinnest axons, but occupy ~40,000 times the volume. A squid-giant-axon-sized brain would not fit through a barn door. Myelin is evolution's solution to fast conduction without massive axon diameter. - Neuroscience: Exploring the Brain, 5th Ed.

Structural Basis

  • The myelin sheath is formed by Schwann cells (PNS) or oligodendrocytes (CNS), wrapping the axon in multiple layers of membrane that act as electrical insulation.
  • Myelin does not run continuously - it is interrupted at regular gaps called the nodes of Ranvier, which are only 1–2 µm long.
  • The internodal segments (myelinated axon between nodes) range from 0.2–2.0 mm in length, depending on axon diameter (thicker axons = longer internodes, up to 1,000× longer than the node).

Ion Channel Distribution - The Key

  • Voltage-gated Na⁺ channels are densely concentrated at nodes of Ranvier and are essentially absent under the myelin sheath.
  • K⁺ channels are present at the nodes (and just adjacent to them), driving repolarisation.
  • This means action potentials can only be generated at the nodes - not along the myelinated internodes.
Saltatory conduction: action potential at left node (Na⁺ influx, depolarisation), current spreads along axoplasm under myelin sheath, triggers new action potential at next node (1 msec later), while previous node repolarises via K⁺ efflux.

Mechanism

  1. An action potential fires at one node (Na⁺ rushes in, membrane depolarises to ~+35 mV).
  2. The resulting positive charge (current) flows through the axoplasm inside the axon - and simultaneously through the extracellular fluid outside - toward the next node.
  3. Myelin insulation prevents this current from leaking out through the internode, so it arrives at the next node with enough strength to depolarise it above threshold.
  4. A new action potential fires at the next node. The previous node repolarises (K⁺ efflux).
  5. The impulse effectively "jumps" from node to node - hence the name from the Latin saltare ("to leap").
Saltatory conduction diagram: action potential jumping node to node along a myelinated axon, with Na⁺ channels clustered at each node, current spreading through axoplasm between firings.

Advantages of Saltatory Conduction

Two major benefits over continuous conduction: - Guyton & Hall, p. 87
  1. Speed - depolarisation jumps long distances rather than advancing millimetre by millimetre. This increases conduction velocity 5- to 50-fold compared to equivalent-sized unmyelinated fibres.
    • Myelinated fibres conduct at 5–120 m/sec
    • A 1,000 µm squid giant axon (unmyelinated) only achieves ~25 m/sec
    • In myelinated axons, velocity is linearly related to diameter (vs. square-root relationship in unmyelinated fibres)
  2. Energy efficiency - only nodes depolarise, so only nodal ion pumps (Na⁺/K⁺-ATPase) need to restore concentration gradients after each impulse. This requires approximately 100 times less ion movement than continuous conduction and therefore far less ATP expenditure.
The myelin also reduces membrane capacitance by ~50-fold, so very little charge transfer is needed to change membrane voltage - further reducing energy cost. - Guyton & Hall

Clinical Relevance: Demyelinating Disease

When myelin is damaged (e.g., in multiple sclerosis), voltage-gated Na⁺ channels are absent from the bare internode, so the current that leaks out through the denuded membrane is insufficient to excite the next node. The result is:
  • Slowed conduction velocity (early demyelination)
  • Conduction block (severe demyelination)
  • Clinical symptoms: weakness, numbness, loss of coordination, impaired vision (optic nerve involvement)

Part 2: Rigor Mortis

Definition

Rigor mortis (Latin: rigor = rigidity, mortis = of death) is the stiffening and shortening of muscles that follows the initial period of primary relaxation after death. It indicates the molecular death of muscle cells and results from chemical changes in the structural proteins of muscle fibres. - Parikh's Textbook of Medical Jurisprudence & Forensic Medicine

Biochemical Mechanism

Normal muscle physiology:
  • In a relaxed muscle, actin and myosin filaments interdigitate only minimally.
  • Contraction requires ATP, which energises the myosin head to bind actin (cross-bridge formation), execute a power stroke, then detach from actin and reset.
  • ATP is required for cross-bridge detachment - not just formation.
After death:
  1. ATP production ceases (no circulation, no oxygen, no substrate delivery).
  2. For a short time, ATP is re-synthesised from remaining glycogen stores (anaerobic glycolysis → lactic acid) - this is why primary relaxation precedes rigor.
  3. Once glycogen is exhausted, ATP cannot be resynthesised.
  4. Without ATP, myosin heads bind actin and cannot detach - cross-bridges become permanently locked.
  5. Actin and myosin fuse into a dehydrated stiff gel - rigor mortis.
  6. The muscle reaction shifts from slightly alkaline to distinctly acid due to lactic acid accumulation.
  7. Rigor persists until autolysis of actin and myosin occurs as part of putrefaction → secondary relaxation.
"In the absence of ATP, actin and myosin filaments become permanently complexed and rigor mortis sets in. This complex remains until decomposition occurs." - DiMaio's Forensic Pathology, 3rd Ed.

Sequence of Appearance (Voluntary Muscles)

Rigor mortis involves all muscles simultaneously at the same rate, but becomes evident first in smaller muscles. The classical sequence by which it becomes clinically apparent:
Time after death (India)Muscles affected
~1 hourHeart (involuntary muscle)
3–4 hoursEyelids
4–5 hoursFace
5–7 hoursNeck and trunk
7–9 hoursUpper extremities
9–11 hoursLower extremities
11–12 hoursSmall muscles of fingers and toes
  • Full development: ~12 hours
  • Persistence: another ~12 hours
  • Passing off (in same order as onset): ~12 hours
  • Total duration: ~36 hours in temperate climates
In hot climates, the entire process is compressed; bodies may be in advanced decomposition within 24 hours with no rigor. Cold preserves it - a drowned boy in a cold lake remained in full rigor after 17 days. - DiMaio's Forensic Pathology

Factors Influencing Rigor Mortis

1. Age and Body Condition

  • Children and elderly: rigor develops earlier and passes sooner (less muscle mass, less glycogen)
  • Strong, muscular adults: onset is later, duration is longer (more glycogen to deplete, more actin-myosin to fix)

2. Mode of Death

ModeEffect
Violent exercise, convulsions, hyperthermiaRapid onset (pre-death ATP depletion)
Strychnine poisoningNearly immediate onset (massive convulsions)
DrowningEarly onset (2–3 hours) due to ATP exhaustion from violent struggling; lasts longer due to cold water
Chronic disease, septicaemiaEarly onset, short duration; may be absent in septicaemic limb
Sudden death in healthy adultLate onset, long duration

3. Surroundings (Temperature)

  • Heat accelerates onset and shortens duration
  • Cold delays onset and prolongs duration
General rule: the longer rigor takes to appear, the longer it lasts (and vice versa). - Parikh's Textbook

Cadaveric Spasm

A special variant: when ATP is so severely depleted at the moment of death (from extreme emotion, violent exertion, or sudden death at peak activity) that rigor mortis sets in instantaneously - without any preceding primary relaxation. The body freezes in its posture of death. Classic examples include victims found clutching weapons, drowning victims clutching vegetation, soldiers dying mid-action.

Conditions Simulating Rigor Mortis

ConditionCauseKey difference
Cadaveric spasmInstantaneous ATP depletionNo primary relaxation period; cannot be broken easily
Cold/freeze stiffeningFreezing of tissuesDisappears rapidly on thawing; body then enters true rigor
Heat stiffeningCoagulation of muscle proteins at >65°CPermanent; not broken by passive stretching
PutrefactionGas and decomposition of tissuesAssociated with other decomposition signs

Medicolegal Importance

  1. Proof of death - an unambiguous sign that death has occurred
  2. Estimation of time since death - rough guide, but highly variable
  3. Detection of body movement - if body is moved after rigor sets in, limbs remain in original position (e.g., arms raised without support if person died against a wall)
  4. Not dependent on nerve supply - rigor develops even in paralysed limbs; it is a purely chemical event
"Like livor mortis, rigor mortis displays far too much variability to be used to determine time of death, however, it can indicate whether a body has been moved." - DiMaio's Forensic Pathology, 3rd Ed.

Sources: Neuroscience: Exploring the Brain, 5th Ed. | Guyton & Hall Textbook of Medical Physiology | Parikh's Textbook of Medical Jurisprudence & Forensic Medicine | DiMaio's Forensic Pathology, 3rd Ed.

Can u make a pdf of this whole chat including images

Reading File
Running Command

mkdir -p /home/daytona/workspace/neuroscience-notes/images && ls /home/daytona/w…

Running Command

cd /home/daytona/workspace/neuroscience-notes && curl -s -o images/wallerian_fig…

Writing File

~/neuroscience-notes/generate_pdf.py

#!/usr/bin/env python3
"""
Generate a comprehensive PDF of the Neuroscience Notes chat session.
Covers: Wallerian Degeneration & Regeneration, Muscle Fibre Types,
        Nerve Fibre Classification, Saltatory Conduction, Rigor Mortis.
"""

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

BASE = "/home/daytona/workspace/neuroscience-notes"
IMG = os.path.join(BASE, "images")
OUT = os.path.join(BASE, "Neuroscience_Notes.pdf")

PAGE_W, PAGE_H = A4
MARGIN = 2.2 * cm

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

def make_style(name, parent='Normal', **kw):
    s = ParagraphStyle(name, parent=styles[parent], **kw)
    styles.add(s)
    return s

title_style   = make_style('DocTitle', fontSize=22, fontName='Helvetica-Bold',
                            textColor=colors.HexColor('#1a237e'), spaceAfter=8,
                            spaceBefore=0, alignment=TA_CENTER)
subtitle_style= make_style('DocSub', fontSize=13, fontName='Helvetica',
                            textColor=colors.HexColor('#455a64'), spaceAfter=16,
                            alignment=TA_CENTER)
h1_style      = make_style('H1', fontSize=16, fontName='Helvetica-Bold',
                            textColor=colors.HexColor('#0d47a1'), spaceBefore=20,
                            spaceAfter=6)
h2_style      = make_style('H2', fontSize=13, fontName='Helvetica-Bold',
                            textColor=colors.HexColor('#1565c0'), spaceBefore=14,
                            spaceAfter=4)
h3_style      = make_style('H3', fontSize=11, fontName='Helvetica-Bold',
                            textColor=colors.HexColor('#283593'), spaceBefore=10,
                            spaceAfter=3)
body_style    = make_style('Body', fontSize=10, fontName='Helvetica',
                            leading=15, spaceAfter=6, alignment=TA_JUSTIFY)
bullet_style  = make_style('Bullet', fontSize=10, fontName='Helvetica',
                            leading=14, spaceAfter=3, leftIndent=18,
                            bulletIndent=6)
caption_style = make_style('Caption', fontSize=8.5, fontName='Helvetica-Oblique',
                            textColor=colors.HexColor('#546e7a'), spaceAfter=8,
                            alignment=TA_CENTER)
source_style  = make_style('Source', fontSize=8, fontName='Helvetica-Oblique',
                            textColor=colors.HexColor('#78909c'), spaceAfter=12,
                            alignment=TA_RIGHT)
box_style     = make_style('Box', fontSize=9.5, fontName='Helvetica',
                            leading=14, leftIndent=12, rightIndent=12,
                            spaceAfter=4)

def hr(): return HRFlowable(width='100%', thickness=0.5, color=colors.HexColor('#90caf9'), spaceAfter=4, spaceBefore=4)
def sp(h=6): return Spacer(1, h)

def img(filename, caption='', width_cm=14):
    path = os.path.join(IMG, filename)
    if not os.path.exists(path):
        return []
    w = width_cm * cm
    from PIL import Image as PILImage
    with PILImage.open(path) as pil:
        iw, ih = pil.size
    h = w * ih / iw
    # cap height to avoid overflow
    max_h = 14 * cm
    if h > max_h:
        h = max_h
        w = h * iw / ih
    items = [Image(path, width=w, height=h, hAlign='CENTER')]
    if caption:
        items.append(Paragraph(caption, caption_style))
    return items

def p(text, style=None): return Paragraph(text, style or body_style)
def b(text): return Paragraph(f'• {text}', bullet_style)
def h1(text): return Paragraph(text, h1_style)
def h2(text): return Paragraph(text, h2_style)
def h3(text): return Paragraph(text, h3_style)

def table(data, col_widths=None, header_color='#1565c0', stripe=True):
    t = Table(data, colWidths=col_widths, repeatRows=1)
    n_rows = len(data)
    n_cols = len(data[0])
    style_cmds = [
        ('BACKGROUND', (0,0), (-1,0), colors.HexColor(header_color)),
        ('TEXTCOLOR',  (0,0), (-1,0), colors.white),
        ('FONTNAME',   (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE',   (0,0), (-1,-1), 9),
        ('FONTNAME',   (0,1), (-1,-1), 'Helvetica'),
        ('GRID',       (0,0), (-1,-1), 0.4, colors.HexColor('#b0bec5')),
        ('VALIGN',     (0,0), (-1,-1), 'TOP'),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, colors.HexColor('#e3f2fd')] if stripe else [colors.white]),
        ('LEFTPADDING',  (0,0), (-1,-1), 5),
        ('RIGHTPADDING', (0,0), (-1,-1), 5),
        ('TOPPADDING',   (0,0), (-1,-1), 4),
        ('BOTTOMPADDING',(0,0), (-1,-1), 4),
        ('WORDWRAP',   (0,0), (-1,-1), True),
    ]
    t.setStyle(TableStyle(style_cmds))
    return t

def source(text): return Paragraph(f'<i>Source: {text}</i>', source_style)

# ── Build story ──────────────────────────────────────────────────────────────
story = []

# COVER
story += [
    sp(40),
    p('NEUROSCIENCE NOTES', title_style),
    p('Comprehensive Study Guide', subtitle_style),
    hr(),
    sp(10),
    p('Topics Covered:', h2_style),
    b('Wallerian Degeneration and Nerve Regeneration'),
    b('White Muscle Fibres and Classification of Muscle Fibre Types'),
    b('Classification and Properties of Nerve Fibres'),
    b('Saltatory Conduction'),
    b('Rigor Mortis'),
    sp(20),
    p('Sources: Bradley and Daroff\'s Neurology in Clinical Practice • Guyton & Hall Textbook of Medical Physiology • '
      'Medical Physiology (Boron & Boulpaep) • Costanzo Physiology • Neuroscience: Exploring the Brain (5th Ed.) • '
      'Histology: A Text and Atlas (Pawlina) • THIEME Atlas of Anatomy • '
      'Parikh\'s Textbook of Medical Jurisprudence • DiMaio\'s Forensic Pathology', caption_style),
    PageBreak(),
]

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 1: WALLERIAN DEGENERATION AND NERVE REGENERATION
# ══════════════════════════════════════════════════════════════════════════════
story += [
    h1('1. Wallerian Degeneration and Nerve Regeneration'),
    hr(),
    sp(4),

    h2('Overview'),
    p('Large myelinated peripheral axons respond to injury in three main ways: <b>segmental demyelination</b>, '
      '<b>Wallerian degeneration</b>, and <b>axonal degeneration</b>. Wallerian degeneration and segmental '
      'demyelination are primarily relevant to traumatic nerve injury. Axonal degeneration is more typical of '
      'metabolic and toxic neuropathies (e.g., diabetes, renal failure).'),
    source("Bradley and Daroff's Neurology in Clinical Practice"),
    sp(4),

    h2('Segmental Demyelination'),
    p('Occurs when a focal nerve segment is subjected to a mild compressive or traction force. Myelin sheath '
      'damage occurs at one or several internodes while segments distal and proximal remain intact.'),
    b('<b>Mild damage:</b> Widened nodes of Ranvier → slowed conduction velocity → paresthesia'),
    b('<b>Moderate damage:</b> Asynchronous conduction → affects deep tendon reflexes, vibration sense'),
    b('<b>Severe compression:</b> Telescoping of axon and myelin at paranodal segments → focal demyelinating '
      'conduction block and weakness. Corresponds to <b>Grade I (neurapraxia)</b> injury.'),
    sp(8),

    h2('Wallerian Degeneration'),
    p('Named after Augustus Waller (1850). Follows grade II–V nerve injuries. Involves both the axon distal '
      'and proximal to the injury site.'),
    sp(4),
]
story += img('wallerian_fig64.png',
             'Fig. 64.4 — Wallerian Degeneration. After axotomy, the distal axon and myelin sheath degenerate. '
             'Macrophages digest debris. The cell body undergoes chromatolysis, switching from axon maintenance '
             'to regeneration mode. (Bradley & Daroff\'s Neurology)', width_cm=13)
story += [
    sp(6),
    h3('Distal Segment Changes'),
    p('Complete within approximately <b>1 week</b>:'),
    b('Disruption of axonal transport — retrograde and anterograde signalling interrupted immediately'),
    b('Rapid Ca²⁺ and Na⁺ influx through disrupted axonal membrane → apoptosis-like cascade'),
    b('Leukocyte recruitment; cytokine cascade; synthesis of neurotrophins, chemokines, proteolytic enzymes'),
    b('<b>Day 3:</b> Schwann cells retract from nodes of Ranvier; macrophage recruitment begins'),
    b('<b>Schwann cell reprogramming</b> (via c-Jun upregulation): dedifferentiation into repair Schwann cells; '
      'myelin autophagy; secretion of glial growth factors (neuregulins); macrophage recruitment'),
    b('Macrophages and repair Schwann cells phagocytose myelin debris. Critical: <b>myelin debris contains '
      'inhibitors of axon regeneration</b> — its clearance is essential'),
    b('<b>Granular disintegration</b>: cytoskeletal components (microtubules, neurofilaments) disassemble; axon fragments'),
    source("Histology: A Text and Atlas, Pawlina | Bradley & Daroff's Neurology"),
    sp(4),

    h3('Proximal Segment Changes'),
    b('Axon breakdown extends proximally only to the <b>first node of Ranvier</b>'),
    b('<b>Chromatolysis</b> of cell body: breakup and dispersion of Nissl substance (rough ER), eccentric '
      'nuclear displacement, increased transcription factor expression → switch from axon maintenance to '
      '<b>protein synthesis mode</b>'),
    b('Very proximal injuries (e.g., avulsion) may cause <b>apoptosis of the cell body</b> — preventing regeneration'),
    sp(8),

    h2('Nerve Regeneration'),
    p('Recovery mechanism depends on the grade of injury:'),
    sp(4),
    table([
        ['Injury Grade', 'Mechanism', 'Timescale'],
        ['Grade I (neurapraxia)', 'Remyelination', 'Weeks to months'],
        ['Grade II–V (axonotmesis/neurotmesis)', 'Collateral sprouting + axon regeneration', '3–24 months'],
    ], col_widths=[5*cm, 7*cm, 4.5*cm]),
    sp(8),

    h3('1. Remyelination (Grade I)'),
    p('Schwann cells divide and initiate remyelination. The new myelin is <b>thinner</b> with <b>more internodes</b> '
      'per original internode. Recovery within weeks to months.'),
    sp(4),

    h3('2. Collateral Sprouting (Partial Injury)'),
    p('Intact adjacent motor axons produce sprouts from nodes of Ranvier (nodal sprouts) or nerve terminals '
      '(terminal sprouts), appearing as early as <b>4 days</b> after injury. They reinnervate denervated muscle '
      'fibres. Clinical recovery: <b>3–6 months</b>. Remaining innervated fibres undergo compensatory hypertrophy.'),
    sp(4),

    h3('3. Axon Regeneration (Severe/Complete Injury)'),
    p('Begins from the proximal stump only <b>after Wallerian degeneration is complete</b>. Schwann cells '
      'dedifferentiate, upregulate adhesion molecules and neurotrophins (cadherins, laminin), proliferate '
      'into linear columns within the original basal lamina — the <b>bands of Büngner</b>.'),
    sp(4),
]
story += img('growth_cone_fig65.png',
             'Fig. 64.5 — Axonal Regeneration. Growth cone with lamellipodia and filopodia advancing through '
             'bands of Büngner (proliferating Schwann cells + basal lamina). Macrophage clears debris ahead. '
             '(Bradley & Daroff\'s Neurology)', width_cm=13)
story += [
    sp(6),
    b('<b>Growth cone</b> (motile tip): bears filopodia (finger-like) and lamellipodia (sheet-like) to navigate'),
    b('<b>Neurotropism</b> (guidance) via semaphorins, ephrins, netrins, slits — attract or repulse growth cone'),
    b('Growth cone secretes <b>plasminogen activators</b> to dissolve debris in endoneurial tubules'),
    b('<b>Rate of regrowth</b>: ~1–2 mm/day (~1 inch/month). Proximal lesions: 2–3 mm/day; distal: ~1 mm/day'),
    b('<b>Hoffmann-Tinel sign</b>: percussion over regenerating nerve → tingling at level of advancing sprouts'),
    sp(4),
    p('<b>Trophic support molecules:</b> NGF, BDNF, neurotrophins 3 & 4, GDNF family factors (neurturin, '
      'artemin, persephin), IGF, IL-6, CNTF, FGF.'),
    source("Bradley & Daroff's Neurology in Clinical Practice, p. 1335"),
    sp(8),
]
story += img('axonal_degen_stages.png',
             'Stages of axonal degeneration and regeneration (Normal → Early → Late → Recovering). '
             'PNS (bottom): axon fragmentation then axon regeneration. '
             'CNS (top): astrocyte proliferation and failed regeneration. (Bradley & Daroff\'s Neurology)',
             width_cm=15)
story += [
    sp(6),

    h2('Timeline of Degeneration and Regeneration'),
    table([
        ['Timepoint', 'Event'],
        ['Immediately', 'Disruption of axonal transport; ion influx; apoptotic cascade'],
        ['8–24 hours', 'First sign: axonal swelling'],
        ['Day 3', 'Schwann cells retract from nodes of Ranvier; macrophage recruitment'],
        ['~1 week', 'Wallerian degeneration complete; Büngner bands formed'],
        ['Day 4 onward', 'Collateral sprouting begins (partial injuries)'],
        ['~3 months', 'Axon regeneration contributes to recovery'],
        ['6–24 months', 'Axon regeneration dominant recovery mechanism'],
        ['>4 months (gap uncrossed)', 'Distal endoneurial tube shrinks to <3 µm; recovery impeded'],
        ['Up to 2–3 years', 'Late sensory reinnervation may still yield useful protective function'],
    ], col_widths=[5.5*cm, 11*cm]),
    sp(8),

    h2('Factors Determining Outcome'),
    b('<b>Endoneurial tube integrity:</b> if disrupted → axons stray into connective tissue → neuroma → neuropathic pain'),
    b('<b>Gap length:</b> longer gaps delay and mismatch reinnervation'),
    b('<b>Proximity to cell body:</b> very proximal injuries risk cell body apoptosis'),
    b('<b>Muscle viability:</b> tolerates denervation ~1 year before irreversible fibrosis'),
    b('<b>Sensory receptor survival:</b> Meissner/Merkel corpuscles survive years; late reinnervation at 2–3 years may restore protective sensation'),
    sp(8),

    h2('PNS vs. CNS Regeneration'),
    table([
        ['Feature', 'PNS', 'CNS'],
        ['Support cell response', 'Schwann cells rapidly dedifferentiate; form Büngner bands', 'Oligodendrocytes do not phagocytose debris efficiently'],
        ['Macrophage access', 'Blood-nerve barrier permissive; macrophages recruited freely', 'Blood-brain barrier restricts macrophage entry'],
        ['Myelin debris clearance', 'Rapid (~1 week)', 'Slow; debris persists and inhibits regeneration'],
        ['Outcome', 'Axon regeneration generally occurs', 'Axons usually cannot regenerate; astrocyte scar forms'],
    ], col_widths=[4.5*cm, 6.5*cm, 5.5*cm]),
    sp(4),
    source("Histology: A Text and Atlas (Pawlina)"),
    PageBreak(),
]

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 2: MUSCLE FIBRE TYPES
# ══════════════════════════════════════════════════════════════════════════════
story += [
    h1('2. White Muscle Fibres and Classification of Muscle Fibre Types'),
    hr(),
    sp(4),

    h2('Classification Overview'),
    p('Skeletal muscle fibres are classified as <b>slow-twitch (Type I)</b> or <b>fast-twitch (Type II)</b> '
      'based on rate of force development, histological appearance, and fatigue resistance. '
      'Fast-twitch fibres are subdivided into Type IIa and Type IIx/IIb.'),
    source("Medical Physiology (Boron & Boulpaep)"),
    sp(6),

    h2('Full Comparison Table'),
    table([
        ['Property', 'Type I (Slow-twitch)', 'Type IIa (Fast oxidative)', 'Type IIx/IIb (Fast glycolytic)'],
        ['Colour', 'Red', 'Red', 'White'],
        ['Myoglobin', 'High', 'High', 'Low'],
        ['Metabolism', 'Oxidative (aerobic)', 'Oxidative + glycolytic', 'Glycolytic (anaerobic)'],
        ['Mitochondria', 'Many', 'More than Type I', 'Few'],
        ['Glycogen', 'Low', 'Abundant', 'High'],
        ['Glycolytic enzymes', 'Low', 'Moderate', 'High'],
        ['Myosin ATPase', 'Slow', 'Fast', 'Fastest'],
        ['Fatigue', 'Resistant', 'Resistant', 'Easily fatigable'],
        ['Diameter', 'Smaller', 'Intermediate', '~2× Type I'],
        ['Capillary density', 'High', 'High', 'Lower'],
        ['Use', 'Endurance, posture', 'Mixed', 'Power, sprint'],
    ], col_widths=[4.2*cm, 4.5*cm, 4.5*cm, 4.2*cm]),
    sp(8),

    h2('White Muscle Fibres (Type IIx/IIb) — Key Properties'),
    p('White colour results directly from <b>low myoglobin content</b>. Key properties:'),
    b('<b>Large diameter</b> — about twice that of slow-twitch fibres; generates greater contractile force'),
    b('<b>High myosin ATPase activity</b> — enzymes promoting rapid energy release are <b>2–3× as active</b> as in slow-twitch; ~twice the maximal power for short bursts'),
    b('<b>Anaerobic (glycolytic) metabolism</b> — rely on stored glycogen and phosphocreatine; cannot sustain oxidative metabolism'),
    b('<b>Rapid fatigue</b> — finite glycogen/phosphocreatine stores; deliver extreme power for <b>seconds to ~1 minute</b>'),
    b('<b>Fewer mitochondria and capillaries</b> — reflecting independence from oxidative phosphorylation'),
    source("Guyton & Hall Textbook of Medical Physiology"),
    sp(6),

    h3('Type IIa vs Type IIx/IIb Distinction'),
    p('Type IIa fibres are fast-twitch but <b>fatigue-resistant</b>: significant oxidative capacity, red in colour, '
      'rich in myoglobin and mitochondria (<i>fast oxidative</i>). '
      'Type IIx/IIb are true white fibres — <b>fatigable</b> due to insufficient oxidative metabolism.'),
    sp(6),

    h2('Genetic and Athletic Relevance'),
    p('Fast- vs slow-twitch fibre ratio is largely <b>genetically determined</b>; training shifts proportions ~10%. '
      'Examples: <b>gastrocnemius</b> (fast-twitch dominant — jumping), <b>soleus</b> (slow-twitch dominant — sustained posture).'),
    sp(4),
    table([
        ['Athlete Type', 'Fast-Twitch %', 'Slow-Twitch %'],
        ['Marathoners', '18', '82'],
        ['Swimmers', '26', '74'],
        ['Average person', '55', '45'],
        ['Weight lifters', '55', '45'],
        ['Sprinters / Jumpers', '63', '37'],
    ], col_widths=[7*cm, 5.5*cm, 5.5*cm]),
    source("Guyton & Hall Textbook of Medical Physiology"),
    PageBreak(),
]

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 3: NERVE FIBRE CLASSIFICATION
# ══════════════════════════════════════════════════════════════════════════════
story += [
    h1('3. Classification and Properties of Nerve Fibres'),
    hr(),
    sp(4),
    p('Nerve fibres are classified by <b>conduction velocity</b>, which depends on two factors:'),
    b('<b>Fibre diameter:</b> larger diameter = higher conduction velocity'),
    b('<b>Myelination:</b> myelin sheath dramatically increases velocity via saltatory conduction'),
    p('Two classification systems are used:'),
    source("Costanzo Physiology, 7th Edition"),
    sp(8),
]
story += img('nerve_fiber_classification.png',
             'Fig. 47.6 — Physiological classifications and functions of nerve fibres. Shows both the '
             'general (A/C) and sensory (I–IV) systems, with fibre diameter, conduction velocity, '
             'sensory functions, and motor functions. (Guyton & Hall)', width_cm=11)
story += [
    sp(6),
    h2('System 1: Erlanger-Gasser Classification (A, B, C)'),
    p('Applies to <b>both sensory and motor</b> fibres. Uses letters and Greek-letter subdivisions.'),
    sp(4),
    h3('Type A Fibres (Large to medium, myelinated)'),
    table([
        ['Subtype', 'Diameter (µm)', 'Velocity (m/s)', 'Function'],
        ['Aα (alpha)', '15–20', '80–120', 'Alpha motor neurons to extrafusal muscle; proprioception (muscle spindle primary, Golgi tendon organ)'],
        ['Aβ (beta)', '8–15', '30–70', 'Touch, pressure (skin mechanoreceptors); small motor'],
        ['Aγ (gamma)', '4–8', '30–70', 'Gamma motor neurons to intrafusal muscle spindle fibres'],
        ['Aδ (delta)', '3–4', '10–30', 'Temperature, sharp/pricking pain, nociception, crude touch'],
    ], col_widths=[2.5*cm, 3*cm, 3*cm, 8.5*cm]),
    sp(6),
    h3('Type B Fibres (Small, myelinated)'),
    table([
        ['Diameter (µm)', 'Velocity (m/s)', 'Function'],
        ['3–4', '10–15', 'Preganglionic autonomic fibres only'],
    ], col_widths=[4*cm, 4*cm, 9*cm]),
    sp(6),
    h3('Type C Fibres (Unmyelinated)'),
    table([
        ['Diameter (µm)', 'Velocity (m/s)', 'Function'],
        ['0.5–2', '0.5–2', 'Slow/aching pain, temperature, crude touch; postganglionic autonomic; olfaction'],
    ], col_widths=[4*cm, 4*cm, 9*cm]),
    sp(6),
    p('C fibres constitute <b>more than half</b> of all sensory fibres in most peripheral nerves, '
      'and <b>all postganglionic autonomic fibres</b> are C fibres.'),
    p('A large Aα fibre conducts at up to <b>120 m/sec</b>. A C fibre at 0.5 m/sec takes ~<b>2 seconds</b> '
      'from the big toe to the spinal cord.'),
    source("Guyton & Hall"),
    sp(8),

    h2('System 2: Lloyd-Hunt Classification (I, II, III, IV)'),
    p('Applies to <b>sensory fibres only</b>. Preferred by sensory physiologists.'),
    sp(4),
    table([
        ['Group', 'Diameter (µm)', 'Corresponds to', 'Origin / Function'],
        ['Ia', '~17', 'Aα', 'Annulospiral (primary) endings of muscle spindles — muscle length + velocity'],
        ['Ib', '~16', 'Aα', 'Golgi tendon organ afferents — muscle tension'],
        ['II', '~8', 'Aβ, Aγ', 'Secondary (flower-spray) endings of muscle spindles; cutaneous tactile receptors (touch, pressure)'],
        ['III', '~3', 'Aδ', 'Temperature, crude touch, pricking pain'],
        ['IV', '0.5–2', 'C', 'Pain, temperature, itch, crude touch (unmyelinated)'],
    ], col_widths=[2*cm, 3*cm, 3*cm, 9*cm]),
    source("Guyton & Hall, p. 587 | Costanzo Physiology, p. 80"),
    sp(8),

    h2('Sensitivity to Local Anaesthetics'),
    p('Smaller fibres are blocked at lower anaesthetic concentrations — basis for differential spinal blocks:'),
    table([
        ['Fibre', 'Diameter (µm)', 'Block conc. (% approx.)', 'Blocked first/last'],
        ['Aα', '15–20', '~1%', 'Last (motor)'],
        ['Aδ', '3–4', '~0.5%', 'Intermediate (pain)'],
        ['B', '3–4', '~0.25%', 'Early (autonomic)'],
        ['C', '1–2', '~0.5%', 'Early (slow pain)'],
    ], col_widths=[3*cm, 3.5*cm, 4.5*cm, 6*cm]),
    p('Classic differential spinal sequence: <b>autonomic → sensory → motor</b> block.'),
    source("Campbell's Operative Orthopaedics, 15th Ed. 2026"),
    sp(8),

    h2('Mnemonic: A-B-C'),
    b('<b>A fibres</b> — All myelinated, All motor + sensory'),
    b('<b>B fibres</b> — Barely myelinated, Before the ganglion (preganglionic autonomic only)'),
    b('<b>C fibres</b> — Cannot see myelin (unmyelinated), Chronic pain and postganglionic autonomic'),
    PageBreak(),
]

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 4: SALTATORY CONDUCTION
# ══════════════════════════════════════════════════════════════════════════════
story += [
    h1('4. Saltatory Conduction'),
    hr(),
    sp(4),

    h2('The Problem It Solves'),
    p('In unmyelinated fibres, an action potential propagates by depolarising every adjacent patch of membrane '
      'in sequence — slow and energetically costly. The largest mammalian axons conduct ~400× faster than the '
      'thinnest, but occupy ~40,000× the volume. A squid-giant-axon-sized nervous system would not fit in a '
      'barn. Vertebrates evolved myelin as the solution.'),
    source("Neuroscience: Exploring the Brain, 5th Ed."),
    sp(6),

    h2('Structural Basis'),
    b('The <b>myelin sheath</b> is formed by Schwann cells (PNS) or oligodendrocytes (CNS)'),
    b('<b>Nodes of Ranvier</b>: gaps in myelin, only <b>1–2 µm long</b>'),
    b('<b>Internodal segments</b>: <b>0.2–2.0 mm</b> long (thicker axons = longer internodes, up to 1,000× the node length)'),
    b('<b>Voltage-gated Na⁺ channels are densely concentrated at nodes</b>, essentially absent under myelin'),
    b('K⁺ channels present at nodes and adjacent regions — drive repolarisation'),
    sp(8),
]
story += img('saltatory_guyton.png',
             'Fig. 5.17 — Saltatory conduction along a myelinated axon. Action potential fires at one node '
             '(Na⁺ influx), current flows through axoplasm under the myelin sheath to the next node, '
             'triggering depolarisation there while the previous node repolarises (K⁺ efflux). (Guyton & Hall)',
             width_cm=14)
story += [
    sp(6),

    h2('Mechanism'),
    table([
        ['Step', 'Event'],
        ['1', 'Action potential fires at Node 1: Na⁺ rushes in, membrane depolarises to ~+35 mV'],
        ['2', 'Positive current flows through axoplasm and extracellular fluid toward Node 2'],
        ['3', 'Myelin insulation prevents current leakage through internode — current arrives intact at Node 2'],
        ['4', 'Node 2 depolarised above threshold → new action potential fires'],
        ['5', 'Node 1 repolarises via K⁺ efflux. Impulse has effectively "jumped" from node to node'],
    ], col_widths=[1.5*cm, 15*cm]),
    p('The term <i>saltatory</i> derives from the Latin <i>saltare</i> ("to leap").'),
    sp(6),
]
story += img('saltatory_node_detail.png',
             'Saltatory conduction detail: Na⁺ influx at node (Time zero, top) depolarises the node. '
             '1 msec later (bottom), current has jumped to the next node; previous node shows K⁺ efflux and '
             'repolarisation. (Neuroscience: Exploring the Brain, 5th Ed.)', width_cm=13)
story += [
    sp(6),
    h2('Advantages'),
    b('<b>Speed:</b> Conduction velocity increases <b>5- to 50-fold</b> vs equivalent-sized unmyelinated fibres. '
      'Myelinated axons: 5–120 m/sec. A 1,000 µm squid giant axon (unmyelinated): only ~25 m/sec. '
      'In myelinated axons, velocity is <b>linearly related to diameter</b> (vs. square-root in unmyelinated).'),
    b('<b>Energy efficiency:</b> Only nodes depolarise → ~<b>100× less ion movement</b> required → '
      'far less Na⁺/K⁺-ATPase work needed. Myelin also reduces membrane capacitance ~50-fold.'),
    source("Guyton & Hall, p. 87"),
    sp(6),

    h2('Clinical Relevance: Demyelinating Disease'),
    p('When myelin is damaged (e.g., <b>multiple sclerosis</b>), Na⁺ channels are absent from the bare internode. '
      'Current leaking through the denuded membrane is insufficient to excite the next node. Results:'),
    b('<b>Slowed conduction velocity</b> (early demyelination)'),
    b('<b>Conduction block</b> (severe demyelination)'),
    b('Clinical: weakness, numbness, loss of coordination, impaired vision (optic nerve)'),
    source("Neuroscience: Exploring the Brain, 5th Ed."),
    PageBreak(),
]

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 5: RIGOR MORTIS
# ══════════════════════════════════════════════════════════════════════════════
story += [
    h1('5. Rigor Mortis'),
    hr(),
    sp(4),

    h2('Definition'),
    p('<b>Rigor mortis</b> (Latin: <i>rigor</i> = rigidity, <i>mortis</i> = of death) is the stiffening and '
      'shortening of muscles that follows the initial period of primary relaxation after death. '
      'It indicates the <b>molecular death of muscle cells</b> and results from chemical changes '
      'in the structural proteins of muscle fibres.'),
    source("Parikh's Textbook of Medical Jurisprudence & Forensic Medicine"),
    sp(6),

    h2('Biochemical Mechanism'),
    p('<b>Normal physiology:</b>'),
    b('In a relaxed muscle, actin and myosin interdigitate only minimally'),
    b('Contraction requires ATP: myosin head binds actin, executes power stroke, then <b>detaches using ATP</b>'),
    b('<b>ATP is required for cross-bridge detachment</b> — not just formation'),
    sp(4),
    p('<b>After death:</b>'),
    b('ATP production ceases. For a short time, ATP is re-synthesised from remaining glycogen (anaerobic glycolysis → lactic acid) — this is why primary relaxation precedes rigor'),
    b('Once glycogen is exhausted, ATP cannot be resynthesised'),
    b('Without ATP, <b>myosin heads bind actin and cannot detach</b> — cross-bridges permanently locked'),
    b('Actin and myosin fuse into a <b>dehydrated stiff gel</b> — rigor mortis'),
    b('Muscle pH shifts from slightly alkaline to <b>distinctly acid</b> (lactic acid accumulation)'),
    b('Rigor persists until <b>autolysis of actin and myosin</b> during putrefaction → secondary relaxation'),
    source("DiMaio's Forensic Pathology, 3rd Ed. | Parikh's Textbook"),
    sp(6),

    h2('Sequence of Appearance'),
    p('All muscles are involved simultaneously at the same rate, but smaller muscles show it first:'),
    table([
        ['Time After Death', 'Muscles Affected'],
        ['~1 hour', 'Heart (involuntary muscle) — left chambers more than right'],
        ['3–4 hours', 'Eyelids'],
        ['4–5 hours', 'Face'],
        ['5–7 hours', 'Neck and trunk'],
        ['7–9 hours', 'Upper extremities'],
        ['9–11 hours', 'Lower extremities'],
        ['11–12 hours', 'Small muscles of fingers and toes'],
        ['~12 hours total', 'Full rigor established'],
        ['12 hours more', 'Rigor persists (passes off in same order as onset)'],
        ['~36 hours total', 'Duration in temperate climates'],
    ], col_widths=[5*cm, 12*cm]),
    p('In hot climates, the process compresses dramatically. Cold preserves it — a drowned boy in a '
      'cold lake remained in full rigor after <b>17 days</b>.'),
    source("DiMaio's Forensic Pathology"),
    sp(6),

    h2('Factors Influencing Rigor Mortis'),
    h3('1. Age and Body Condition'),
    b('<b>Children and elderly:</b> earlier onset, shorter duration (less muscle mass, less glycogen)'),
    b('<b>Muscular adults:</b> later onset, longer duration (more glycogen to deplete, more actin-myosin to lock)'),
    sp(4),
    h3('2. Mode of Death'),
    table([
        ['Mode', 'Effect on Rigor'],
        ['Violent exercise, convulsions, hyperthermia', 'Rapid onset (pre-death ATP depletion)'],
        ['Strychnine poisoning', 'Nearly immediate onset (massive convulsions)'],
        ['Drowning', 'Early onset (2–3 hours) from violent struggling; longer duration due to cold water'],
        ['Chronic disease / septicaemia', 'Early onset, short duration; absent in septicaemic limb'],
        ['Sudden death in healthy adult', 'Late onset, long duration'],
    ], col_widths=[6.5*cm, 10.5*cm]),
    sp(4),
    h3('3. Temperature (Surroundings)'),
    b('<b>Heat</b> — accelerates onset, shortens duration'),
    b('<b>Cold</b> — delays onset, prolongs duration'),
    p('<b>General rule:</b> the longer rigor takes to appear, the longer it lasts (and vice versa).'),
    source("Parikh's Textbook"),
    sp(6),

    h2('Cadaveric Spasm'),
    p('When ATP is so severely depleted at the moment of death (extreme emotion, violent exertion, '
      'sudden death at peak activity) that rigor mortis sets in <b>instantaneously</b> — without any '
      'preceding primary relaxation. The body freezes in its posture of death. Examples: victims found '
      'clutching weapons, drowning victims clutching vegetation.'),
    sp(6),

    h2('Conditions Simulating Rigor Mortis'),
    table([
        ['Condition', 'Cause', 'Key Difference from Rigor'],
        ['Cadaveric spasm', 'Instantaneous ATP depletion', 'No primary relaxation; cannot be "broken" and does not return'],
        ['Cold/freeze stiffening', 'Freezing of tissues', 'Disappears on thawing; body then enters true rigor (rapid, brief)'],
        ['Heat stiffening', 'Protein coagulation at >65°C', 'Permanent; not broken by passive stretching'],
        ['Putrefaction stiffening', 'Gas and tissue decomposition', 'Associated with other decomposition signs'],
    ], col_widths=[4*cm, 5*cm, 8*cm]),
    sp(6),

    h2('Medicolegal Importance'),
    b('<b>1. Sign of death</b> — unambiguous evidence that death has occurred'),
    b('<b>2. Time since death</b> — rough guide only; highly variable; unreliable for precision'),
    b('<b>3. Detection of body movement</b> — if moved after rigor, limbs remain in original position'),
    b('<b>4. Not nerve-dependent</b> — develops in paralysed limbs; purely chemical'),
    p('"Like livor mortis, rigor mortis displays far too much variability to be used to '
      'determine time of death, however, it can indicate whether a body has been moved."'),
    source("DiMaio's Forensic Pathology, 3rd Ed."),
    sp(20),

    hr(),
    p('<b>End of Notes</b>', caption_style),
    p('Sources: Bradley & Daroff\'s Neurology in Clinical Practice • Guyton & Hall Textbook of Medical Physiology • '
      'Medical Physiology (Boron & Boulpaep) • Costanzo Physiology 7th Ed. • '
      'Neuroscience: Exploring the Brain 5th Ed. (Bear, Connors, Paradiso) • '
      'Histology: A Text and Atlas (Pawlina) • THIEME Atlas of Anatomy — General Anatomy & Musculoskeletal System • '
      'Parikh\'s Textbook of Medical Jurisprudence & Forensic Medicine • '
      'DiMaio\'s Forensic Pathology 3rd Ed. • Campbell\'s Operative Orthopaedics 15th Ed. 2026',
      caption_style),
]

# ── Build PDF ────────────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    # Header bar
    canvas.setFillColor(colors.HexColor('#0d47a1'))
    canvas.rect(MARGIN, PAGE_H - 1.5*cm, PAGE_W - 2*MARGIN, 0.35*cm, fill=1, stroke=0)
    canvas.setFont('Helvetica', 8)
    canvas.setFillColor(colors.HexColor('#546e7a'))
    canvas.drawString(MARGIN, 1.2*cm, 'Neuroscience Notes — Orris Study Guide')
    canvas.drawRightString(PAGE_W - MARGIN, 1.2*cm, f'Page {doc.page}')
    canvas.restoreState()

doc = SimpleDocTemplate(
    OUT,
    pagesize=A4,
    leftMargin=MARGIN,
    rightMargin=MARGIN,
    topMargin=2.5*cm,
    bottomMargin=2.5*cm,
    title='Neuroscience Notes',
    author='Orris AI',
    subject='Neuroscience Study Guide',
)

doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print(f"PDF created: {OUT}")
Running Command

cd /home/daytona/workspace/neuroscience-notes && python3 generate_pdf.py 2>&1

Editing File

~/neuroscience-notes/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/neuroscience-notes/generate_pdf.py'
Running Command

cd /home/daytona/workspace/neuroscience-notes && python3 generate_pdf.py 2>&1

Editing File

~/neuroscience-notes/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/neuroscience-notes/generate_pdf.py'
Running Command

cd /home/daytona/workspace/neuroscience-notes && python3 generate_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/neuroscience-notes/Neuroscience_Notes.pdf

Your PDF is ready — 3.1 MB, fully formatted with all content and images from the entire chat.

Neuroscience Notes

PDF Document · PDF

What's included:
  • Cover page with topic list and sources
  • Section 1 - Wallerian Degeneration & Regeneration - with the Wallerian degeneration diagram (Fig. 64.4), growth cone diagram (Fig. 64.5), and the Normal→Early→Late→Recovering stages diagram
  • Section 2 - White Muscle Fibres & Classification - full comparison table across Type I, IIa, IIx/IIb, athlete fibre percentage data
  • Section 3 - Nerve Fibre Classification - Erlanger-Gasser (A/B/C) and Lloyd-Hunt (I-IV) tables, local anaesthetic sensitivity table, with the Guyton nerve fibre classification chart image
  • Section 4 - Saltatory Conduction - mechanism step-by-step, both diagrams (Guyton overview + Neuroscience: Exploring the Brain node detail)
  • Section 5 - Rigor Mortis - biochemistry, sequence table, factors, cadaveric spasm, medicolegal importance
Each page has a blue header bar and page number footer. All tables are colour-striped for readability.

I’m not able to download the pdf file

Running Command

ls -lh /home/daytona/workspace/neuroscience-notes/Neuroscience_Notes.pdf && pyth…

Running Command

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

Running Command

cd /home/daytona/workspace/neuroscience-notes && python3 -c " from PIL import Im…

Running Command

cd /home/daytona/workspace/neuroscience-notes && sed 's|images/|images_compresse…

Running Command

cd /home/daytona/workspace/neuroscience-notes && python3 -c " import subprocess,…

Running Command

cd /home/daytona/workspace/neuroscience-notes && python3 -c " # Rewrite the img(…

Running Command

cd /home/daytona/workspace/neuroscience-notes && python3 -c " content = open('ge…

Writing File

~/neuroscience-notes/fix_paths.py

import re

content = open('generate_pdf.py').read()

# Fix the image folder
content = content.replace(
    "IMG = os.path.join(BASE, 'images')",
    "IMG = os.path.join(BASE, 'images_compressed')"
)

# Fix .png -> .jpg in img() calls
content = re.sub(
    r"img\('([^']+)\.png'",
    lambda m: "img('" + m.group(1) + ".jpg'",
    content
)

# Fix output filename
content = content.replace(
    "OUT = os.path.join(BASE, 'Neuroscience_Notes.pdf')",
    "OUT = os.path.join(BASE, 'Neuroscience_Notes_compressed.pdf')"
)

open('generate_pdf_compressed.py', 'w').write(content)

# Verify
for line in content.split('\n'):
    if 'IMG =' in line or 'OUT =' in line or "img('" in line:
        print(repr(line.strip()[:90]))
Running Command

cd /home/daytona/workspace/neuroscience-notes && python3 fix_paths.py 2>&1

Editing File

~/neuroscience-notes/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/neuroscience-notes/generate_pdf.py'
Editing File

~/neuroscience-notes/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/neuroscience-notes/generate_pdf.py'
Editing File

~/neuroscience-notes/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/neuroscience-notes/generate_pdf.py'
Editing File

~/neuroscience-notes/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/neuroscience-notes/generate_pdf.py'
Editing File

~/neuroscience-notes/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/neuroscience-notes/generate_pdf.py'
Editing File

~/neuroscience-notes/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/neuroscience-notes/generate_pdf.py'
Editing File

~/neuroscience-notes/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/neuroscience-notes/generate_pdf.py'
Running Command

cd /home/daytona/workspace/neuroscience-notes && python3 generate_pdf.py 2>&1 &&…

This is a shared conversation. Sign in to Orris to start your own chat.