# AutEng > AI-native technical documentation platform. Create and share documents with Markdown, Mermaid diagrams, KaTeX math equations, and AI-assisted generation. AutEng is a documentation platform for engineers, scientists, and technical writers. It supports rich Markdown editing with live preview, Mermaid diagram rendering, KaTeX mathematical notation, AI-powered content generation, CAS (Computer Algebra System) verification of mathematical proofs, and Lean 4 formal theorem proving integration. ## Documentation - [Documentation Best Practices — Markdown + Mermaid + KaTeX](https://auteng.ai/docs/guides/best-practices/documentation-best-practices.md): Comprehensive guide to creating exceptional technical documentation using Markdown, Mermaid diagrams, and KaTeX equations together - [Features](https://auteng.ai/docs/guides/features.md): Explore all the powerful features AutEng offers for technical documentation - [Getting Started](https://auteng.ai/docs/guides/getting-started.md): Learn the basics of AutEng and create your first document - [Using KaTeX in AutEng](https://auteng.ai/docs/guides/katex-guide.md): Practical guide to integrating mathematical equations in your documentation - [Markdown, Mermaid & KaTeX Syntax](https://auteng.ai/docs/guides/markdown-syntax.md): Complete syntax reference for Markdown, Mermaid diagrams, and KaTeX math equations - [Markdown Tables — Complete Guide with Examples](https://auteng.ai/docs/guides/markdown-tables.md): Learn how to create and format tables in Markdown with alignment, styling, and advanced techniques for technical documentation - [Calculus in Technical Documentation — Derivatives and Integrals](https://auteng.ai/docs/math/calculus/calculus-technical-docs.md): Master calculus notation in technical docs with KaTeX. Learn derivatives, integrals, limits, and differential equations for software, physics, and engineering documentation. - [Set Theory and Logic Notation — Mathematical Foundations](https://auteng.ai/docs/math/discrete/set-theory-logic.md): Complete guide to set theory and logic notation in technical documentation. Learn sets, operations, logic symbols, quantifiers, and proof notation with KaTeX. - [KaTeX Syntax Quick Reference — Math Equations in Markdown](https://auteng.ai/docs/math/notation/katex-syntax.md): Complete reference for KaTeX mathematical notation including common formulas, symbols, and usage patterns for technical documentation. - [CAS Verification Demo — Automated Math Checking](https://auteng.ai/docs/math/verification/cas-demo.md): Interactive examples demonstrating AutEng's Computer Algebra System (CAS) verification. See how mathematical expressions and derivations are automatically verified with SymPy. - [Lean 4 Theorem Proving — Formal Proof Verification](https://auteng.ai/docs/math/verification/lean-theorem-proving.md): Machine-checked mathematical proofs using Lean 4 and Mathlib. Learn how to write and verify formal proofs with induction, case analysis, and powerful tactics. - [Quadratic Formula Derivation — Step-by-Step CAS Verification](https://auteng.ai/docs/math/verification/quadratic-formula-derivation.md): Complete derivation of the quadratic formula with automated CAS verification. Learn how mode=solve verifies equation-solving steps and detects lost or extraneous solutions. - [Electromagnetism — Maxwell's Equations Explained](https://auteng.ai/docs/physics/electromagnetism/maxwells-equations.md): Master Maxwell's equations with clear explanations, KaTeX notation, and Mermaid diagrams. Learn Gauss's law, Faraday's law, and electromagnetic wave theory. - [Physics Equations and Diagrams — Documenting Scientific Concepts](https://auteng.ai/docs/physics/general/physics-equations-diagrams.md): Complete guide to documenting physics concepts with KaTeX equations, Mermaid diagrams, and scientific notation - [API Documentation](https://auteng.ai/docs/software/api/api-documentation.md): Document REST APIs and GraphQL schemas with examples - [Architecture Documentation](https://auteng.ai/docs/software/architecture/architecture-docs.md): Document system architecture and design with diagrams and flows - [Technical Specifications](https://auteng.ai/docs/software/architecture/technical-specs.md): Write ADRs, RFCs, and design documents - [OAuth 2.0 Client Credentials Flow](https://auteng.ai/docs/software/authentication/oauth-client-credentials.md): Complete guide to implementing server-to-server authentication with OAuth 2.0 - [Comparing OAuth 2.0 Flows — Authorization Code vs Client Credentials](https://auteng.ai/docs/software/authentication/oauth-flows.md): Complete comparison of OAuth 2.0 flows with sequence diagrams, implementation examples, and use cases ## Optional - [Pricing](https://auteng.ai/pricing): Simple, transparent pricing for individuals and teams - [x402 Compute API — Pay-Per-Request Code Execution for AI Agents](https://auteng.ai/docs/x402): Execute Python and Node.js code in sandboxed environments with USDC micropayments. No accounts, no API keys — just pay and compute. - [Privacy Policy](https://auteng.ai/legal/privacy-policy): How we collect, use, and protect your data - [Terms of Service](https://auteng.ai/legal/terms-of-service): Terms and conditions for using AutEng --- # Getting Started > Learn the basics of AutEng and create your first document ## Quick Start ### Sign Up Create your free account using GitHub, Google, or email. Get started in seconds. ### Create a Document Click "New Document" and start writing. Use Markdown, Mermaid diagrams, or KaTeX math. ### Use AI to Generate Let AI help you create diagrams, expand sections, or draft entire documents. "Generate a sequence diagram for user authentication" ### Share with Your Team Generate a public share link or export to PDF. Your docs are always beautifully formatted. ## Key Features ### GitHub Flavored Markdown Write docs the way developers think. Full GFM support including tables, task lists, and code blocks. ### Mermaid Diagrams Create flowcharts, sequence diagrams, class diagrams, and more. No external tools needed. ### KaTeX Math Write mathematical equations with LaTeX syntax. Perfect for algorithms and data science docs. ### AI-Powered Generation Describe what you need and let AI create diagrams, expand sections, or draft entire documents. ### Version History Track changes over time with visual diffs. Never lose work or wonder what changed. ### Public Sharing Generate beautiful public share links. Perfect for sharing with stakeholders or the community. ## Common Use Cases ### Architecture Documentation → System designs, component diagrams, data flows, and technical specifications ### API Documentation → REST APIs, GraphQL schemas, authentication flows, and endpoint specifications ### Technical Specifications → ADRs, RFCs, design docs, and implementation plans ### Authentication Flows → OAuth 2.0, JWT, and other authentication patterns ## Tips for Success - Start with structure: Use headings to organize your document before filling in details - Let AI help: Describe what you want instead of writing complex diagrams manually - Use visual elements: Diagrams and tables make technical concepts easier to understand - Share early: Get feedback while you're writing, not after you're done - Keep it updated: Use version history to track changes and maintain accuracy --- # Features > Explore all the powerful features AutEng offers for technical documentation ## Core Features ### {feature.title} {feature.description} - {detail} ## Why AutEng? ### Built for Developers Markdown, diagrams as code, and keyboard shortcuts. Everything works the way developers expect. ### AI-Powered Let AI handle the heavy lifting. Generate diagrams, expand sections, and draft docs in seconds. ### Beautiful Output Professional-looking docs that you're proud to share. No design skills required. ### Version Control Friendly Plain text means easy diffs, merges, and integration with your existing workflow. ## Coming Soon ### Team Workspaces Organize docs by team with shared access controls and collaboration features. ### API Access Programmatic access to create and update docs from your CI/CD pipeline. ### Custom Domains Host your public docs on your own domain with custom branding. ### Advanced Search Full-text search across all your docs with filters and advanced queries. --- # Markdown, Mermaid & KaTeX Syntax > Complete syntax reference for Markdown, Mermaid diagrams, and KaTeX math equations ## AI Generation Tips ### Let AI do the heavy lifting Instead of writing complex diagrams or equations manually, describe what you want: - "Create a sequence diagram showing OAuth authentication flow" - "Generate an ER diagram for a blog database schema" - "Write the mathematical proof for gradient descent convergence" - "Draft an architecture document for a microservices system" --- # Using KaTeX in AutEng > Practical guide to integrating mathematical equations in your documentation ## Why KaTeX for Documentation? KaTeX is a fast, self-contained JavaScript library for rendering TeX math notation on the web. Unlike MathJax, KaTeX is designed for speed and doesn't require external fonts or network requests after initial load. ### AutEng Has KaTeX Built-In - **No setup required:** KaTeX is fully integrated and configured in AutEng - **Just start writing:** Use standard LaTeX math syntax in your markdown - **Fast rendering:** Equations render instantly as you type - **AI-powered generation:** AutEng can generate markdown with KaTeX equations - **LaTeX compatibility:** Supports most common LaTeX math commands For technical documentation, especially in fields like computer science, mathematics, physics, or data science, the ability to render equations inline with your prose is essential. AutEng makes this seamless with zero configuration. ## Using KaTeX in AutEng AutEng has KaTeX fully integrated and configured. You don't need to install anything or configure any processors. Just start writing math equations using standard LaTeX syntax in your markdown documents. ### Quick Start 1. **Create a new document** in AutEng or open an existing one 2. **Write your markdown** with math equations using $...$ for inline or $$...$$ for display math 3. **See instant preview** - equations render automatically as you type 4. **Use AI generation** - Ask AutEng to generate markdown with mathematical equations ### AI-Powered Math Generation AutEng's AI can generate markdown documents with properly formatted KaTeX equations. Try prompts like: - "Generate a proof that √2 is irrational" - "Create documentation for the gradient descent algorithm with equations" - "Write a guide to Big O notation with mathematical examples" - "Document the backpropagation algorithm with all the math" ## Math Syntax in Markdown KaTeX uses standard LaTeX delimiters for inline and display math. Understanding these delimiters is crucial for proper rendering. ### Inline Math Use single dollar signs $...$ for inline equations: ```markdown The quadratic formula $x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$ solves quadratic equations. Einstein's famous equation $E = mc^2$ relates energy and mass. The derivative $\\frac{dy}{dx}$ represents the rate of change. ``` ### Display Math (Block) Use double dollar signs $$...$$ for centered display equations: ```markdown $$ \\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi} $$ $$ \\sum_{i=1}^{n} i = \\frac{n(n+1)}{2} $$ $$ \\nabla \\times \\mathbf{E} = -\\frac{\\partial \\mathbf{B}}{\\partial t} $$ ``` ### Multi-line Equations Use the aligned environment for aligned equations: ```markdown $$ \\begin{aligned} f(x) &= x^2 + 2x + 1 \\\\ &= (x + 1)^2 \\\\ &= (x + 1)(x + 1) \\end{aligned} $$ ``` ## Common Use Cases ### Algorithm Complexity ### Probability & Statistics ### Linear Algebra ### Machine Learning ## Best Practices ### 1. Use Semantic Variable Names Choose variable names that convey meaning, especially in documentation: ### 2. Add Explanatory Text Always explain equations in prose. Don't assume readers understand notation: ### 3. Break Complex Equations Split complex derivations into steps for clarity: ### 4. Use Consistent Notation Maintain consistent notation throughout your documentation. If you use $\theta$ for parameters in one section, don't switch to $w$ in another without explanation. ### 5. Test Rendering Always preview your equations in the actual rendering environment. What works in one KaTeX setup might not work in another due to configuration differences. ## Common Pitfalls & Solutions ### Pitfall: Escaping Backslashes In many Markdown processors, backslashes need to be escaped: ### Pitfall: Underscore Conflicts Underscores in math can conflict with Markdown emphasis: ### Pitfall: Unsupported Commands KaTeX doesn't support all LaTeX commands. Check the [supported functions list](https://katex.org/docs/supported.html) . ### Pitfall: Missing CSS If equations render as plain text or look broken, ensure you've imported the KaTeX CSS file. This is the most common setup issue. ## Advanced Techniques ### Custom Macros Define custom macros for frequently used notation: ### Colored Equations Use color to highlight parts of equations: ### Equation Numbering Add equation numbers for reference: ## Performance Considerations ### Optimization Tips - **Server-side rendering:** Pre-render equations on the server to reduce client-side processing - **Lazy loading:** Load KaTeX only on pages that contain math - **Caching:** Cache rendered equations to avoid re-rendering on every page load - **Minimize equations:** Use inline math sparingly; too many equations can slow page rendering - **Font subsetting:** If using custom fonts, subset them to include only needed glyphs --- # Documentation Best Practices — Markdown + Mermaid + KaTeX > Comprehensive guide to creating exceptional technical documentation using Markdown, Mermaid diagrams, and KaTeX equations together ## Introduction Great technical documentation is the foundation of successful software projects, research papers, and educational content. By combining Markdown's simplicity, Mermaid's visual power, and KaTeX's mathematical precision, you can create documentation that is both beautiful and functional. This comprehensive guide covers best practices for creating exceptional technical documentation using all three tools together. Whether you're documenting APIs, explaining algorithms, or writing research papers, these principles will help you communicate complex ideas clearly and effectively. > **What You'll Learn:** This guide covers the complete documentation workflow: structuring content, writing clear explanations, creating effective diagrams, integrating mathematical notation, and maintaining consistency across large documentation projects. ## The Power of the Trilogy Markdown, Mermaid, and KaTeX form a powerful trilogy for technical documentation. Each tool excels in its domain, and together they cover virtually every documentation need: Structure and prose. Headers, lists, tables, code blocks, and formatted text for clear communication. Visual diagrams. Flowcharts, sequence diagrams, architecture diagrams, and state machines for system visualization. Mathematical precision. Equations, formulas, algorithms, and mathematical notation for technical accuracy. ```markdown # Algorithm Analysis: Binary Search ## Overview Binary search is an efficient algorithm for finding an item in a sorted array. It works by repeatedly dividing the search interval in half. ## Time Complexity The time complexity of binary search is $O(\\log n)$, where $n$ is the number of elements in the array. This is because we eliminate half of the remaining elements with each comparison. $$ T(n) = T\\left(\\frac{n}{2}\\right) + O(1) = O(\\log n) $$ ## Algorithm Flow \`\`\`mermaid flowchart TD A[Start: Array and Target] --> B{Is array empty?} B -->|Yes| C[Return: Not Found] B -->|No| D[Calculate mid = low + high / 2] D --> E{arr[mid] == target?} E -->|Yes| F[Return: mid] E -->|No| G{arr[mid] > target?} G -->|Yes| H[Search left half] G -->|No| I[Search right half] H --> B I --> B \`\`\` ## Implementation \`\`\`python def binary_search(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] > target: high = mid - 1 else: low = mid + 1 return -1 \`\`\` ## Space Complexity Binary search uses $O(1)$ auxiliary space for the iterative version, making it very memory-efficient. ``` ## Document Structure Best Practices ### Hierarchical Organization Use a clear heading hierarchy to organize your content. Start with a single H1 for the document title, then use H2 for major sections, H3 for subsections, and so on. This creates a logical structure that's easy to navigate and understand. ```markdown # Main Document Title ## Introduction Brief overview of the topic. ## Core Concepts ### Concept 1 Detailed explanation of the first concept. #### Implementation Details Specific implementation notes. ### Concept 2 Detailed explanation of the second concept. ## Advanced Topics ### Performance Optimization Tips for improving performance. ## Conclusion Summary and next steps. ``` ### Progressive Disclosure Start with high-level concepts and progressively reveal details. This approach helps readers build mental models before diving into complexity. Use this pattern: Overview → Core Concepts → Details → Advanced Topics. > **Structure Pattern:** **Introduction** (What and Why) → **Core Concepts** (How it works) → **Examples** (Practical usage) → **Advanced Topics** (Edge cases and optimization) → **Reference** (Complete API/syntax) ## Writing Clear Explanations ### The Explanation Pattern Great technical explanations follow a consistent pattern: **Concept** → **Analogy** → **Example** → **Visualization**. This multi-modal approach ensures understanding across different learning styles. ```markdown ## Understanding Recursion ### The Concept Recursion is when a function calls itself to solve smaller instances of the same problem. ### The Analogy Think of Russian nesting dolls. To see the smallest doll, you must first open each larger doll. Each doll contains a smaller version of itself, until you reach the base case—the smallest doll that doesn't open. ### The Example Here's a recursive function to calculate factorial: \`\`\`python def factorial(n): # Base case: factorial of 0 or 1 is 1 if n <= 1: return 1 # Recursive case: n! = n × (n-1)! return n * factorial(n - 1) \`\`\` ### The Visualization \`\`\`mermaid graph TD A[factorial 4] --> B[4 × factorial 3] B --> C[4 × 3 × factorial 2] C --> D[4 × 3 × 2 × factorial 1] D --> E[4 × 3 × 2 × 1] E --> F[Result: 24] \`\`\` The mathematical representation: $n! = n \\times (n-1)!$ with base case $0! = 1$ ``` ### Active Voice and Clarity Use active voice and direct language. Instead of "The function can be called," write "Call the function." Instead of "It should be noted that," write "Note that." This makes documentation more engaging and easier to follow. "The data should be validated before it is processed by the system." "It is recommended that error handling be implemented." "Validate the data before processing it." "Implement error handling for all API calls." ## Creating Effective Diagrams ### Choose the Right Diagram Type Mermaid offers many diagram types. Choose based on what you're trying to communicate: **Use for:** Algorithms, decision trees, process flows **Best when:** Showing step-by-step logic with branches and loops **Use for:** API interactions, message passing, time-ordered events **Best when:** Showing communication between components over time **Use for:** Object-oriented design, data models, relationships **Best when:** Documenting class hierarchies and associations **Use for:** State machines, lifecycle management, mode transitions **Best when:** Showing how systems change state based on events ### Diagram Design Principles ```markdown ## System Architecture Our microservices architecture separates concerns and enables independent scaling: \`\`\`mermaid graph TB Client[Web Client] API[API Gateway] Auth[Auth Service] User[User Service] Order[Order Service] DB1[(User DB)] DB2[(Order DB)] Cache[Redis Cache] Client -->|HTTPS| API API -->|Authenticate| Auth API -->|User Data| User API -->|Orders| Order User -->|Read/Write| DB1 Order -->|Read/Write| DB2 User -.->|Cache| Cache Order -.->|Cache| Cache style Client fill:#e1f5ff style API fill:#fff4e1 style Auth fill:#ffe1e1 style User fill:#e1ffe1 style Order fill:#e1ffe1 \`\`\` **Key Components:** - **API Gateway**: Single entry point, handles routing and rate limiting - **Auth Service**: JWT-based authentication, session management - **User Service**: User profiles, preferences, and settings - **Order Service**: Order processing, inventory management - **Redis Cache**: Reduces database load, improves response times ``` > **Diagram Best Practices:** **Keep it simple:** Show only what's necessary for understanding **Use consistent styling:** Same colors/shapes for similar components **Label everything:** No unlabeled boxes or arrows **Show direction:** Use arrows to indicate data/control flow **Add a legend:** Explain colors, line styles, and symbols ## Integrating Mathematical Notation ### When to Use Math Notation Use mathematical notation when it adds precision and clarity. Don't use it just to look technical. Good candidates include: algorithm complexity, formulas, statistical measures, and mathematical proofs. ```markdown ## Time Complexity Analysis ### Bubble Sort Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they're in the wrong order. **Best Case:** $O(n)$ - Array is already sorted, only one pass needed **Average Case:** $O(n^2)$ - Random order requires multiple passes **Worst Case:** $O(n^2)$ - Array is reverse sorted The number of comparisons in the worst case is: $$ \\sum_{i=1}^{n-1} i = \\frac{n(n-1)}{2} = O(n^2) $$ \`\`\`python def bubble_sort(arr): n = len(arr) for i in range(n): swapped = False for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True if not swapped: # Optimization for best case break return arr \`\`\` **Space Complexity:** $O(1)$ - Sorts in place with no additional arrays ``` ### Explain Before You Formalize Always explain concepts in plain language before introducing mathematical notation. The formula should reinforce understanding, not replace explanation. "The Euclidean distance is calculated as:" $d = \sqrt{'{(x_2-x_1)^2 + (y_2-y_1)^2}'}$ "To find the straight-line distance between two points, we use the Pythagorean theorem. The distance $d$ is the length of the hypotenuse:" $d = \sqrt{'{(x_2-x_1)^2 + (y_2-y_1)^2}'}$ ## Code Examples Best Practices ### Complete, Runnable Examples Code examples should be complete and runnable. Include imports, setup, and teardown. Readers should be able to copy-paste and run your examples without modifications. ```markdown ## Binary Search Implementation Here's a complete implementation of binary search with error handling: \`\`\`python from typing import List, Optional def binary_search(arr: List[int], target: int) -> Optional[int]: """ Search for target in sorted array using binary search. Args: arr: Sorted list of integers target: Value to search for Returns: Index of target if found, None otherwise Time Complexity: O(log n) Space Complexity: O(1) """ if not arr: return None low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] > target: high = mid - 1 else: low = mid + 1 return None # Example usage numbers = [1, 3, 5, 7, 9, 11, 13, 15] result = binary_search(numbers, 7) print(f"Found at index: {result}") # Output: Found at index: 3 result = binary_search(numbers, 6) print(f"Found at index: {result}") # Output: Found at index: None \`\`\` **Key Points:** - Type hints for clarity - Docstring with complexity analysis - Handles edge case (empty array) - Includes example usage with expected output ``` ### Annotate Complex Logic Add inline comments for non-obvious logic, but don't comment the obvious. Comments should explain "why," not "what." > **Comment Quality:** **Bad comment:** `// Increment i` (obvious from code) **Good comment:** `// Skip even numbers to optimize for prime checking` (explains reasoning) ## Combining All Three Tools The real power comes from using Markdown, Mermaid, and KaTeX together. Here's a complete example documenting a sorting algorithm with all three tools: ```markdown # Merge Sort: A Divide-and-Conquer Algorithm ## Overview Merge sort is an efficient, stable sorting algorithm that uses the divide-and-conquer paradigm. It divides the array into smaller subarrays, sorts them recursively, and then merges them back together. ## Algorithm Visualization \`\`\`mermaid graph TD A["[38, 27, 43, 3]"] --> B["[38, 27]"] A --> C["[43, 3]"] B --> D["[38]"] B --> E["[27]"] C --> F["[43]"] C --> G["[3]"] D --> H["[27, 38]"] E --> H F --> I["[3, 43]"] G --> I H --> J["[3, 27, 38, 43]"] I --> J style A fill:#ffe1e1 style J fill:#e1ffe1 \`\`\` ## Time Complexity The recurrence relation for merge sort is: $$ T(n) = 2T\\left(\\frac{n}{2}\\right) + O(n) $$ Using the Master Theorem, this resolves to: $$ T(n) = O(n \\log n) $$ This holds for all cases (best, average, and worst), making merge sort very predictable. ## Space Complexity Merge sort requires $O(n)$ auxiliary space for the temporary arrays used during merging. ## Implementation \`\`\`python def merge_sort(arr): """ Sort array using merge sort algorithm. Time: O(n log n) Space: O(n) """ if len(arr) <= 1: return arr # Divide mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) # Conquer (merge) return merge(left, right) def merge(left, right): """Merge two sorted arrays.""" result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:]) result.extend(right[j:]) return result \`\`\` ## When to Use Merge Sort **Advantages:** - Guaranteed $O(n \\log n)$ performance - Stable sort (preserves relative order) - Predictable performance **Disadvantages:** - Requires $O(n)$ extra space - Slower than quicksort in practice for small arrays **Best for:** Large datasets where stability matters and extra space is available. ``` ## Consistency and Style ### Establish Conventions Create and follow consistent conventions throughout your documentation: Use the same terms consistently. If you call something a "handler" in one place, don't call it a "processor" elsewhere. Create a glossary for domain-specific terms. Follow language conventions. Use PEP 8 for Python, follow the language's official style guide. Consistent formatting makes code examples easier to read. Use consistent colors and shapes. For example, always use blue for user-facing components, green for backend services, and red for external dependencies. Be consistent with variable names. If you use $n$ for array size, use it everywhere. If you use $O(n)$ for complexity, don't switch to $\Theta(n)$ without explanation. ### Document Templates Create templates for common documentation types. This ensures consistency and speeds up documentation creation: ```markdown ## POST /api/users Create a new user account. ### Request \`\`\`http POST /api/users HTTP/1.1 Content-Type: application/json Authorization: Bearer { "email": "user@example.com", "name": "John Doe", "role": "developer" } \`\`\` ### Response **Success (201 Created):** \`\`\`json { "id": "usr_123", "email": "user@example.com", "name": "John Doe", "role": "developer", "created_at": "2024-01-15T10:30:00Z" } \`\`\` **Error (400 Bad Request):** \`\`\`json { "error": "validation_error", "message": "Invalid email format", "field": "email" } \`\`\` ### Parameters | Field | Type | Required | Description | |-------|------|----------|-------------| | email | string | Yes | Valid email address | | name | string | Yes | User's full name | | role | string | No | User role (default: "user") | ### Authentication Requires a valid JWT token with \`users:create\` permission. ### Rate Limiting - 10 requests per minute per IP - 100 requests per hour per account ### Example \`\`\`python import requests response = requests.post( "https://api.example.com/api/users", headers={"Authorization": f"Bearer {token}"}, json={ "email": "user@example.com", "name": "John Doe", "role": "developer" } ) if response.status_code == 201: user = response.json() print(f"Created user: {user['id']}") \`\`\` ``` ## Maintenance and Updates ### Keep Documentation Current Documentation becomes outdated quickly. Establish processes to keep it current: > **Documentation Maintenance Checklist:** Review documentation with every code change Add "Last Updated" dates to pages Mark deprecated features clearly Update examples when APIs change Test code examples regularly Remove outdated content rather than leaving it ### Version Documentation For APIs and libraries, maintain documentation for multiple versions. Clearly indicate which version each document applies to. ```markdown # Authentication API > **Version:** 2.0 | **Last Updated:** 2024-01-15 ## What's New in v2.0 - JWT tokens replace API keys - OAuth 2.0 support added - Refresh token rotation implemented ## Migration from v1.0 If you're using v1.0 API keys, follow this migration guide: ### Before (v1.0) \`\`\`python headers = {"X-API-Key": "your-api-key"} response = requests.get(url, headers=headers) \`\`\` ### After (v2.0) \`\`\`python headers = {"Authorization": f"Bearer {jwt_token}"} response = requests.get(url, headers=headers) \`\`\` ## Deprecation Notice ⚠️ **v1.0 API keys will be deprecated on June 1, 2024.** Please migrate to JWT tokens before this date. **Note:** This is a hypothetical example showing version-specific documentation. ``` ## Accessibility and Inclusivity ### Write for Everyone Good documentation is accessible to readers with different backgrounds and abilities: > **Use Descriptive Link Text:** Instead of "click here," use descriptive text: "See the [authentication guide](#) for details." > **Provide Alt Text for Diagrams:** While Mermaid diagrams render visually, include a text description for screen readers: "This flowchart shows the user authentication process, starting with login credentials and ending with a JWT token." > **Avoid Jargon:** Define technical terms on first use. Not everyone knows what "idempotent" or "eventual consistency" means. > **Use Inclusive Language:** Use "they" instead of "he/she," "allowlist" instead of "whitelist," and avoid unnecessarily gendered examples. ## Best Practices Summary > **Structure:** Use clear heading hierarchy (H1 → H2 → H3) Follow progressive disclosure (simple → complex) Create consistent document templates > **Writing:** Use active voice and direct language Follow the pattern: Concept → Analogy → Example → Visualization Explain before formalizing with math > **Diagrams:** Choose the right diagram type for your content Keep diagrams simple and focused Use consistent styling and colors Label everything clearly > **Code:** Provide complete, runnable examples Include imports and setup code Add comments for non-obvious logic Show expected output > **Math:** Use math notation to add precision, not complexity Explain concepts before showing formulas Be consistent with variable names Include units and context > **Maintenance:** Review docs with every code change Add "Last Updated" dates Test code examples regularly Version documentation for APIs ## Common Pitfalls to Avoid > **Assuming Knowledge:** Don't assume readers know your domain. Define terms, provide context, and link to prerequisite reading. > **Incomplete Examples:** Code snippets that can't run frustrate readers. Always provide complete, working examples with all necessary imports and setup. > **Outdated Content:** Nothing erodes trust faster than documentation that doesn't match the actual behavior. Keep docs current or clearly mark deprecated content. > **Over-Complicated Diagrams:** A diagram with 50 boxes and 100 arrows helps no one. Break complex systems into multiple focused diagrams. > **Math Without Explanation:** Dropping formulas without context alienates readers. Always explain what the math represents and why it matters. > **Inconsistent Terminology:** Using different terms for the same concept confuses readers. Create a glossary and stick to it. ## Next Steps Now that you understand the principles of great documentation, explore these related guides: Complete guide to Markdown, Mermaid, and KaTeX syntax Practical guide to mathematical notation in documentation Learn the basics and create your first document Complete reference for creating diagrams and formatting --- # Markdown Tables — Complete Guide with Examples > Learn how to create and format tables in Markdown with alignment, styling, and advanced techniques for technical documentation ## Introduction Yes, Markdown fully supports tables! Markdown tables are a powerful way to organize and present structured data in your documentation. Whether you're documenting API endpoints, comparing features, or displaying configuration options, tables help readers quickly scan and understand information. In this guide, you'll learn how to create tables in Markdown, format them with alignment options, and apply best practices for readable, maintainable tables in technical documentation. We'll cover everything from basic syntax to advanced formatting techniques. ## What Is a Markdown Table? A Markdown table is a way to structure data in rows and columns using plain text characters. Tables use pipes (|) to separate columns and hyphens (-) to define the header row. They're part of GitHub Flavored Markdown (GFM) and are widely supported across Markdown processors. Tables are ideal for presenting: - API endpoint documentation - Configuration parameters - Feature comparisons - Data specifications - Status codes and error messages - Version compatibility matrices ## Basic Table Syntax To create a table in Markdown, you need three components: a header row, a separator row, and data rows. Here's the basic structure: ```markdown | Column 1 | Column 2 | Column 3 | | -------- | -------- | -------- | | Row 1 | Data A | Value 1 | | Row 2 | Data B | Value 2 | ``` > **Syntax Breakdown:** **Header row:** Column names separated by pipes (`|`) **Separator row:** At least three hyphens (`---`) per column, separated by pipes **Data rows:** Cell content separated by pipes ## How to Make a Table in Markdown Let's walk through creating a table step by step. We'll build a table documenting HTTP status codes: ### Step 1: Define Headers Start by writing your column headers, separated by pipes: ```markdown | Status Code | Description | Category | ``` ### Step 2: Add Separator Row Add a row of hyphens below the headers. Use at least three hyphens per column: ```markdown | Status Code | Description | Category | | ----------- | ----------- | -------- | ``` ### Step 3: Add Data Rows Add your data rows below the separator: ```markdown | Status Code | Description | Category | | ----------- | ----------- | -------- | | 200 | OK | Success | | 201 | Created | Success | | 400 | Bad Request | Client Error | | 401 | Unauthorized | Client Error | | 500 | Internal Server Error | Server Error | ``` ## Table Alignment You can control how content is aligned within each column by adding colons (`:`) to the separator row: - **Left-aligned (default):** `| --- |` or `| :--- |` - **Center-aligned:** `| :---: |` - **Right-aligned:** `| ---: |` ```markdown | Feature | Status | Price | | :------ | :----: | ----: | | Basic Plan | ✓ | $9.99 | | Pro Plan | ✓ | $29.99 | | Enterprise | ✓ | $99.99 | | Custom | Contact | TBD | ``` > **Alignment Best Practices:** **Text columns:** Use left alignment (default) for readability **Status/icons:** Use center alignment for visual balance **Numbers:** Use right alignment for easier comparison ## Formatting Cell Content You can use inline Markdown formatting within table cells, including bold, italic, code, and links: ```markdown | Parameter | Type | Description | | --------- | ---- | ----------- | | **name** | \`string\` | User's full name | | *email* | \`string\` | Email address (required) | | \`age\` | \`number\` | Age in years | | [docs](/docs) | \`link\` | Documentation link | ``` > **Supported Formatting:** You can use these inline Markdown elements in table cells: **Bold:** `**text**` **Italic:** `*text*` **Code:** ``code`` **Links:** `[text](url)` **Strikethrough:** `~~text~~` ## Real-World Examples Here are practical examples of tables commonly used in technical documentation: ### API Endpoint Documentation ```markdown | Method | Endpoint | Description | Auth Required | | :----- | :------- | :---------- | :-----------: | | GET | \`/api/users\` | List all users | ✓ | | GET | \`/api/users/:id\` | Get user by ID | ✓ | | POST | \`/api/users\` | Create new user | ✓ | | PUT | \`/api/users/:id\` | Update user | ✓ | | DELETE | \`/api/users/:id\` | Delete user | ✓ | ``` ### Configuration Parameters ```markdown | Variable | Type | Default | Description | | :------- | :--: | :-----: | :---------- | | \`PORT\` | number | 3000 | Server port | | \`NODE_ENV\` | string | development | Environment mode | | \`DATABASE_URL\` | string | *required* | Database connection string | | \`LOG_LEVEL\` | string | info | Logging verbosity | ``` ### Feature Comparison ```markdown | Feature | Free | Pro | Enterprise | | :------ | :--: | :-: | :--------: | | Users | 1 | 10 | Unlimited | | Storage | 1 GB | 100 GB | 1 TB | | API Access | ✗ | ✓ | ✓ | | Support | Community | Email | 24/7 Phone | | Custom Domain | ✗ | ✓ | ✓ | | SSO | ✗ | ✗ | ✓ | ``` ### Version Compatibility ```markdown | Framework | Version | Node.js | TypeScript | | :-------- | :-----: | :-----: | :--------: | | Next.js | 14.x | ≥18.17 | ≥5.0 | | React | 18.x | ≥16.8 | ≥4.7 | | Vue | 3.x | ≥16.0 | ≥4.5 | | Angular | 17.x | ≥18.13 | ≥5.2 | ``` ## Advanced Techniques Here are some advanced techniques for working with Markdown tables: ### Empty Cells Leave cells empty by using pipes without content between them: ```markdown | Feature | v1.0 | v2.0 | v3.0 | | :------ | :--: | :--: | :--: | | Basic Auth | ✓ | ✓ | ✓ | | OAuth 2.0 | | ✓ | ✓ | | SSO | | | ✓ | ``` ### Long Content For cells with long content, the table will automatically wrap or expand: ```markdown | Error Code | Description | | :--------- | :---------- | | E001 | Invalid authentication credentials provided. Please check your API key. | | E002 | Rate limit exceeded. Please wait before making additional requests. | | E003 | Resource not found. The requested endpoint does not exist. | ``` ### Escaping Pipe Characters If you need to include a literal pipe character in a cell, escape it with a backslash: ```markdown | Operator | Syntax | Example | | :------- | :----- | :------ | | OR | \`\\|\` | \`a \\| b\` | | AND | \`&&\` | \`a && b\` | | NOT | \`!\` | \`!a\` | ``` ## Best Practices Follow these best practices to create clear, maintainable tables: ### 1. Keep Tables Readable in Source Align pipes vertically in your source code for better readability: ```markdown | Name | Role | Status | | --------- | ---------- | ------ | | Alice | Developer | Active | | Bob | Designer | Active | | Charlie | Manager | Away | ``` ### 2. Use Descriptive Headers Make column headers clear and specific: - ✓ Good: `Response Time (ms)` - ✗ Avoid: `Time` - ✓ Good: `HTTP Status Code` - ✗ Avoid: `Code` ### 3. Limit Column Count Keep tables to 5-6 columns maximum for readability. For wider data, consider splitting into multiple tables or using a different format. ### 4. Use Consistent Formatting Apply formatting consistently across similar tables in your documentation. For example, always use code formatting for parameter names or always center-align status indicators. ### 5. Consider Mobile Responsiveness Tables with many columns may not display well on mobile devices. Test your tables on different screen sizes or provide alternative views for complex data. ## Common Mistakes to Avoid > **Missing Separator Row:** **Problem:** Forgetting the separator row between headers and data **Result:** The table won't render correctly **Solution:** Always include a row of hyphens after the header row > **Inconsistent Column Count:** **Problem:** Different numbers of pipes in different rows **Result:** Malformed table or missing cells **Solution:** Ensure every row has the same number of columns (pipes) > **Overly Complex Tables:** **Problem:** Trying to create tables with merged cells or nested structures **Result:** Markdown tables don't support cell merging **Solution:** Simplify your data structure or use multiple tables ## When Not to Use Tables While tables are powerful, they're not always the best choice. Consider alternatives when: - **Data is hierarchical:** Use nested lists or tree structures instead - **Content is narrative:** Use paragraphs with inline formatting - **Only two columns:** Consider a definition list or key-value pairs - **Data is very wide:** Consider splitting into multiple focused tables - **Complex relationships:** Use diagrams (like Mermaid) to show connections ## Quick Reference ```markdown | Syntax | Description | | :----- | :---------- | | \`\\| Header \\|\` | Column header | | \`\\| --- \\|\` | Left-aligned separator | | \`\\| :---: \\|\` | Center-aligned separator | | \`\\| ---: \\|\` | Right-aligned separator | | \`\\| Cell \\|\` | Table cell content | | \`**bold**\` | Bold text in cell | | \`*italic*\` | Italic text in cell | | \`\\\`code\\\`\` | Code in cell | | \`[link](url)\` | Link in cell | ``` ## Next Steps Now that you know how to create tables in Markdown, explore these related topics: - Learn more about Markdown syntax in our comprehensive Markdown guide - Combine tables with Mermaid diagrams for rich technical documentation - Explore API documentation best practices for structuring endpoint tables - Check out documentation best practices for organizing complex information --- # OAuth 2.0 Client Credentials Flow > Complete guide to implementing server-to-server authentication with OAuth 2.0 ## Introduction The OAuth 2.0 Client Credentials flow is designed for machine-to-machine (M2M) authentication where a client application needs to access protected resources on its own behalf, not on behalf of a user. This flow is ideal for backend services, microservices, CLI tools, and automated processes that need to authenticate with APIs. Unlike the Authorization Code flow which involves user interaction, Client Credentials is a direct exchange between the client and the authorization server. The client authenticates using its own credentials (client ID and client secret) and receives an access token that can be used to call protected APIs. ### Key Benefits - **Simple Implementation:** No user interaction or redirects required - **Server-to-Server:** Perfect for backend services and microservices - **Secure:** Client credentials never exposed to end users - **Scalable:** Supports high-volume API access patterns - **Standardized:** Industry-standard OAuth 2.0 protocol ### When to Use Client Credentials Use Client Credentials flow when: - Your application is a backend service or daemon - You need server-to-server authentication - The client is confidential and can securely store credentials - No user interaction is required - You're accessing resources owned by the application itself ## How Client Credentials Flow Works The Client Credentials flow is the simplest OAuth 2.0 flow, consisting of just two steps: the client authenticates with the authorization server and receives an access token. Here's the complete sequence: ### Sequence Diagram This diagram shows the complete authentication flow between the client application and the authorization server: ### Step-by-Step Breakdown The client application sends a POST request to the authorization server's token endpoint with its credentials: - grant_type: Must be "client_credentials" - client_id: The client's unique identifier - client_secret: The client's secret key - scope: (Optional) Requested permissions The authorization server validates the client credentials and returns an access token: - access_token: JWT or opaque token for API access - token_type: Usually "Bearer" - expires_in: Token lifetime in seconds - scope: Granted permissions The client includes the access token in the Authorization header when calling protected APIs. When the token expires, the client requests a new one using the same credentials. ## Implementation Examples Here are practical examples of implementing the Client Credentials flow in different programming languages and frameworks. ## Security Best Practices The Client Credentials flow involves sensitive credentials that must be protected. Follow these security best practices to ensure your implementation is secure. ### 1. Secure Credential Storage Never hardcode client credentials in your source code or commit them to version control. ### 2. Use HTTPS Only Always use HTTPS for token requests and API calls. Never send credentials or tokens over unencrypted connections. ### 3. Implement Token Caching Cache access tokens and reuse them until they expire. This reduces load on the authorization server and improves performance. ### 4. Use Minimal Scopes Request only the scopes (permissions) your application needs. This follows the principle of least privilege. ### 5. Implement Proper Error Handling Handle token expiration, network errors, and authentication failures gracefully. ### 6. Rotate Client Secrets Regularly Implement a process to rotate client secrets periodically (e.g., every 90 days). Many authorization servers support multiple active secrets to enable zero-downtime rotation. ### 7. Monitor and Log Authentication Events Log authentication attempts and monitor for suspicious activity: - Failed authentication attempts - Unusual access patterns - Token usage from unexpected locations - High-frequency token requests ## Common Pitfalls & Solutions ### Pitfall 1: Not Caching Access Tokens Requesting a new token for every API call wastes resources and can hit rate limits. ### Pitfall 2: Exposing Client Credentials Never use Client Credentials flow in frontend applications or mobile apps where credentials can be extracted. ❌ NEVER DO THIS: - Embedding credentials in frontend JavaScript - Including credentials in mobile app binaries - Committing credentials to public repositories - Sharing credentials in documentation or examples ✅ INSTEAD: - Use Authorization Code flow for user-facing apps - Keep credentials on backend servers only - Use environment variables or secrets managers - Implement a backend proxy for frontend API calls ### Pitfall 3: Ignoring Token Expiration Not handling token expiration leads to failed API calls and poor user experience. ### Pitfall 4: Using HTTP Instead of HTTPS Sending credentials or tokens over HTTP exposes them to interception. ❌ INSECURE: ✅ SECURE: ### Pitfall 5: Not Validating Token Responses Always validate the token response structure and handle errors properly. ## Real-World Use Cases Here are common scenarios where Client Credentials flow is the right choice: ### Microservices Communication Service A needs to call Service B's API. Each service has its own client credentials and authenticates independently. ```markdown \`\`\`mermaid sequenceDiagram participant ServiceA participant AuthServer participant ServiceB ServiceA->>AuthServer: POST /token (client_credentials) AuthServer->>ServiceA: access_token ServiceA->>ServiceB: GET /api/data (Bearer token) ServiceB->>AuthServer: Validate token AuthServer->>ServiceB: Token valid ServiceB->>ServiceA: Return data \`\`\` ``` ### Scheduled Jobs and Cron Tasks Background jobs that run on a schedule need to authenticate to access APIs. Client Credentials provides a simple, secure way to authenticate without user interaction. ### CLI Tools and Scripts Command-line tools that need to access APIs can use Client Credentials for authentication. Users configure credentials once, and the tool handles token management automatically. ### IoT Devices and Sensors IoT devices that send data to backend APIs can use Client Credentials for authentication. Each device has unique credentials and can be individually revoked if compromised. ### Data Integration and ETL Pipelines ETL processes that extract data from APIs, transform it, and load it into data warehouses use Client Credentials to authenticate with source and destination APIs. ## Documenting OAuth Flows with AutEng AutEng makes it easy to document OAuth flows with Mermaid sequence diagrams and code examples. Here's how to create comprehensive OAuth documentation: ### Create Sequence Diagrams Use Mermaid's sequence diagram syntax to visualize the authentication flow: ### Add Code Examples Include working code examples in multiple languages to help developers implement the flow quickly. ### Document Security Considerations Always include security best practices and common pitfalls to help developers avoid security vulnerabilities. ### Why AutEng for OAuth Documentation? - **Real-time Preview:** See your diagrams and code as you write - **Version Control:** Track changes to your authentication flows - **Collaboration:** Share documentation with your team - **AI Generation:** Generate diagrams and code examples with AI --- # Comparing OAuth 2.0 Flows — Authorization Code vs Client Credentials > Complete comparison of OAuth 2.0 flows with sequence diagrams, implementation examples, and use cases ## Introduction OAuth 2.0 defines multiple authentication flows (grant types) for different use cases. The two primary flows you'll use in modern applications are **Authorization Code** for user authentication and **Client Credentials** for machine-to-machine communication. Understanding when and how to use each flow is essential for building secure, scalable applications. This guide provides a comprehensive comparison of these flows with practical implementation examples, sequence diagrams, and real-world use cases. We'll show you how to document OAuth flows using AutEng's markdown, Mermaid diagrams, and code examples. ### Quick Decision Guide - You need to authenticate users - Your application acts on behalf of users - You're building web apps, mobile apps, or SPAs - No user is involved (machine-to-machine) - Your application acts on its own behalf - You're building backend services or API clients ## Authorization Code Flow The Authorization Code flow is the most secure OAuth 2.0 flow for user authentication. It's designed for applications where users need to grant permission for the app to access their data. The flow involves redirecting users to an authorization server, where they authenticate and grant consent. ### Complete Flow Diagram Here's how the Authorization Code flow works from start to finish. Notice how the authorization code is exchanged for tokens on the backend, keeping the client secret secure. ### Key Benefits - **Most Secure:** Client secret never exposed to browser or user - **User Consent:** Users explicitly grant permissions to your application - **Refresh Tokens:** Long-lived sessions without requiring re-authentication - **CSRF Protection:** State parameter prevents cross-site request forgery - **PKCE Support:** Can be enhanced with PKCE for public clients (SPAs, mobile apps) ### Perfect For - Web applications with backend servers - Mobile applications (with PKCE extension) - Single-page applications (with PKCE extension) - Any application that needs to act on behalf of a user - Applications requiring long-lived access via refresh tokens ### Implementation Example Here's a practical implementation of the Authorization Code flow in Python and TypeScript, showing how to handle the complete authentication process including token refresh. ### PKCE Extension Proof Key for Code Exchange (PKCE, pronounced "pixie") is an extension that makes Authorization Code flow secure for public clients like mobile apps and single-page applications that can't securely store a client secret. PKCE adds a dynamically generated code verifier and code challenge to prevent authorization code interception attacks. It's now recommended for all OAuth 2.0 clients, even those with a backend server. ## Client Credentials Flow The Client Credentials flow is designed for machine-to-machine (M2M) authentication where no user is involved. This is the simplest OAuth 2.0 flow - the client directly authenticates with the authorization server using its credentials and receives an access token. ### Complete Flow Diagram The Client Credentials flow is straightforward: authenticate with credentials, receive a token, use the token to access APIs. No user interaction or browser redirects are involved. ### Key Benefits - **Simplest Flow:** Direct credential exchange with no redirects or user interaction - **High Performance:** Minimal overhead, perfect for high-volume API access - **Secure:** Credentials stored securely on backend servers only - **Scope-Based:** Fine-grained access control through scopes - **Easy to Implement:** Simple HTTP POST request to get tokens ### Perfect For - Microservices communicating with each other - Backend services and daemons - CLI tools and scripts - Scheduled jobs and cron tasks - IoT devices and sensors - Data integration and ETL pipelines ### Implementation Example Here's a production-ready implementation with automatic token caching and refresh. The client manages token expiration automatically, ensuring your API calls always use valid tokens. ### Security Best Practices - **Store credentials securely:** Use environment variables or secrets managers (AWS Secrets Manager, HashiCorp Vault) - **Use HTTPS only:** Never send credentials or tokens over unencrypted connections - **Implement token caching:** Reuse tokens until they expire to reduce load on auth server - **Use minimal scopes:** Request only the permissions your application needs - **Rotate secrets regularly:** Change client secrets periodically (e.g., every 90 days) - **Monitor access patterns:** Log authentication events and watch for suspicious activity ## Side-by-Side Comparison Here's a comprehensive comparison to help you choose the right OAuth 2.0 flow for your application: | Feature | Authorization Code | Client Credentials | | --- | --- | --- | | User Involvement | ✅ Yes - user authenticates and grants consent | ❌ No - machine-to-machine only | | Client Secret Required | ✅ Yes (or PKCE for public clients) | ✅ Yes - must be kept confidential | | Refresh Tokens | ✅ Yes - enables long-lived sessions | ❌ No - request new access token when expired | | Token Exposure | 🔒 Secure - tokens handled on backend | 🔒 Secure - backend only | | Security Level | 🟢 High - most secure for user auth | 🟢 High - when used correctly | | Implementation Complexity | 🟡 Medium - requires backend and redirects | 🟢 Low - simple direct exchange | | Best Use Case | Web apps, mobile apps, SPAs with users | Backend services, APIs, CLIs, automation | | Typical Token Lifetime | Access: 15-60 min, Refresh: days/weeks | Access: 1-24 hours (no refresh) | ### Choosing the Right Flow - Your application has users who need to log in - You need to access user-specific data or act on behalf of users - You want long-lived sessions with refresh tokens - You're building a web app, mobile app, or SPA - No user is involved in the authentication process - Your application acts on its own behalf, not on behalf of users - You're building backend services, APIs, or automation tools - You can securely store client credentials on a server ## Real-World Use Cases Here are practical examples of when to use each OAuth 2.0 flow in real-world applications: ### Use Case 1: Social Media Web Application **Scenario:** A web application where users sign in with Google or GitHub to access their profile, post content, and interact with other users. **Flow:** Authorization Code with PKCE **Why:** Users need to authenticate and grant permissions. The app acts on behalf of users to access their data. Refresh tokens enable long-lived sessions without requiring users to log in repeatedly. ### Use Case 2: Microservices Architecture **Scenario:** A payment service needs to call an inventory service to check stock levels before processing orders. Both services are part of the same system. **Flow:** Client Credentials **Why:** No user is involved - this is pure service-to-service communication. Each service has its own credentials and authenticates independently. Simple, secure, and performant for backend services. ### Use Case 3: Mobile Banking App **Scenario:** A mobile banking app where users log in to view their accounts, make transfers, and pay bills. **Flow:** Authorization Code with PKCE **Why:** Mobile apps are public clients that can't securely store secrets. PKCE provides security without requiring a client secret. Users authenticate and the app acts on their behalf to access banking services. ### Use Case 4: Scheduled Data Sync Job **Scenario:** A cron job that runs nightly to sync customer data between your CRM and data warehouse via their APIs. **Flow:** Client Credentials **Why:** No user interaction is possible in a scheduled job. The job acts on its own behalf to sync data between systems. Client Credentials provides simple, secure authentication for automated processes. ### Use Case 5: Single-Page Application (SPA) **Scenario:** A React dashboard that displays analytics data from an API, where users log in to see their personalized data. **Flow:** Authorization Code with PKCE **Why:** SPAs are public clients, so PKCE is essential. Authorization Code with PKCE is more secure than the deprecated Implicit flow. Modern browsers support CORS for token exchange, making this the recommended approach. ### Use Case 6: CLI Developer Tool **Scenario:** A command-line tool that developers use to deploy applications to a cloud platform. **Flow:** Client Credentials (for service accounts) or Device Flow (for user accounts) **Why:** For service accounts, use Client Credentials. For user-specific actions, use Device Flow (a variant of Authorization Code for devices without browsers). The choice depends on whether actions are service-specific or user-specific. ## Documenting OAuth Flows with AutEng AutEng makes it easy to create comprehensive OAuth documentation with Mermaid sequence diagrams, comparison tables, and code examples. Here's how this page was created: ### 1. Sequence Diagrams All the sequence diagrams on this page were created using Mermaid syntax. AutEng renders them in real-time as you type: ```markdown \`\`\`mermaid sequenceDiagram participant Client participant Auth as Auth Server participant API Client->>Auth: POST /token (credentials) Auth->>Client: access_token Client->>API: GET /resource (Bearer token) API->>Client: Protected data \`\`\` ``` ### 2. Comparison Tables Use markdown tables to create side-by-side comparisons. AutEng renders them with proper styling: ```markdown | Feature | Auth Code | Client Credentials | |---------|-----------|-------------------| | User Involved | ✅ Yes | ❌ No | | Refresh Tokens | ✅ Yes | ❌ No | | Use Case | Web/Mobile Apps | Backend Services | ``` ### 3. Code Examples Include working code examples in multiple languages. AutEng provides syntax highlighting and copy functionality: ```markdown \`\`\`python # OAuth 2.0 Client Credentials Example import requests response = requests.post( 'https://auth.example.com/token', data={ 'grant_type': 'client_credentials', 'client_id': 'your_client_id', 'client_secret': 'your_client_secret' } ) token = response.json()['access_token'] \`\`\` ``` ### Why AutEng for OAuth Documentation? - **Real-time Preview:** See your diagrams and code as you write - **Mermaid Support:** Built-in support for sequence diagrams, flowcharts, and more - **Syntax Highlighting:** Automatic highlighting for 100+ programming languages - **Version Control:** Track changes to your authentication documentation - **Collaboration:** Share documentation with your team via public links - **AI Generation:** Generate diagrams and code examples with AI assistance --- # Architecture Documentation > Document system architecture and design with diagrams and flows ## Introduction Create comprehensive architecture documentation with system designs, component diagrams, data flows, and technical specifications. Use Markdown, Mermaid diagrams, and AI assistance to document your architecture in a way that your team actually wants to read. Good architecture documentation helps teams understand system design, make informed decisions, and onboard new engineers quickly. It should be visual, up-to-date, and easy to maintain. ## Why AutEng for Architecture Docs? ### Diagrams as Code Create Mermaid diagrams with simple text. Version control friendly and easy to update. No more fighting with drawing tools or losing diagram source files. ### AI-Generated Diagrams Describe your architecture and let AI create the diagrams. Iterate quickly with natural language instead of manually positioning boxes and arrows. ### Beautiful Sharing Generate public links that look professional. Perfect for design reviews, stakeholder presentations, and team documentation. ## System Architecture Document high-level system designs showing components, services, and their interactions. Perfect for microservices architectures, cloud infrastructure, and deployment diagrams. ```markdown # E-Commerce Platform Architecture ## Overview Our platform uses a microservices architecture with the following key components: \`\`\`mermaid flowchart TB Client[Web/Mobile Client] --> Gateway[API Gateway] Gateway --> Auth[Auth Service] Gateway --> Products[Product Service] Gateway --> Orders[Order Service] Gateway --> Payments[Payment Service] Products --> ProductDB[(Product DB)] Orders --> OrderDB[(Order DB)] Auth --> UserDB[(User DB)] Orders --> Queue[Message Queue] Queue --> Inventory[Inventory Service] Queue --> Notifications[Notification Service] Payments --> PaymentGateway[Payment Gateway] \`\`\` ## Key Components - **API Gateway**: Routes requests, handles authentication, rate limiting - **Auth Service**: User authentication and authorization - **Product Service**: Product catalog and search - **Order Service**: Order management and processing - **Payment Service**: Payment processing and refunds - **Inventory Service**: Stock management - **Notification Service**: Email and push notifications ``` ## Data Flow Diagrams Visualize how data moves through your system from input to output. Show ETL pipelines, event-driven architectures, and message queue flows. ```markdown # Order Processing Data Flow \`\`\`mermaid sequenceDiagram participant User participant API participant OrderService participant PaymentService participant Queue participant InventoryService participant NotificationService User->>API: Create Order API->>OrderService: POST /orders OrderService->>OrderService: Validate order OrderService->>PaymentService: Process payment PaymentService->>PaymentService: Charge card PaymentService-->>OrderService: Payment confirmed OrderService->>Queue: Publish OrderCreated event OrderService-->>API: Return order ID API-->>User: Order confirmation Queue->>InventoryService: OrderCreated event InventoryService->>InventoryService: Reserve items InventoryService->>Queue: Publish InventoryReserved Queue->>NotificationService: OrderCreated event NotificationService->>User: Send confirmation email \`\`\` This flow shows how an order moves through the system: 1. User creates order via API 2. Payment is processed synchronously 3. Order events are published to message queue 4. Inventory and notifications are processed asynchronously ``` ## Component Diagrams Detail the internal structure of services and their dependencies. Show service dependencies, module relationships, and package structures. ```markdown # Order Service Architecture \`\`\`mermaid flowchart TB subgraph "Order Service" API[REST API Layer] Business[Business Logic] Data[Data Access Layer] API --> Business Business --> Data Business --> Events[Event Publisher] Business --> Cache[Redis Cache] end Data --> DB[(PostgreSQL)] Events --> Queue[RabbitMQ] External[External Services] --> API API --> Auth[Auth Service] Business --> Payment[Payment Service] \`\`\` ## Layers ### API Layer - HTTP request handling - Input validation - Response formatting - Error handling ### Business Logic - Order validation - State management - Business rules - Event publishing ### Data Access - Database queries - Transaction management - Data mapping ``` ## Database Schemas Document your data models with entity relationship diagrams. Show table relationships, foreign keys, and schema structure. ```markdown # Database Schema \`\`\`mermaid erDiagram User ||--o{ Order : places Order ||--|{ OrderItem : contains Product ||--o{ OrderItem : "ordered in" Order ||--|| Payment : has User { uuid id PK string email string name timestamp created_at } Order { uuid id PK uuid user_id FK string status decimal total timestamp created_at } OrderItem { uuid id PK uuid order_id FK uuid product_id FK int quantity decimal price } Product { uuid id PK string name string description decimal price int stock } Payment { uuid id PK uuid order_id FK string status decimal amount timestamp processed_at } \`\`\` ## Key Relationships - Users can place multiple orders - Each order contains multiple items - Products can appear in multiple orders - Each order has one payment ``` ## Best Practices - **Start high-level:** Begin with system overview before diving into component details - **Use consistent notation:** Stick to standard diagram types (flowchart, sequence, ER) for clarity - **Include context:** Explain why architectural decisions were made, not just what they are - **Show data flows:** Use sequence diagrams to illustrate how components interact - **Document dependencies:** Make service and module dependencies explicit - **Keep it current:** Update diagrams as architecture evolves to maintain accuracy --- # Technical Specifications > Write ADRs, RFCs, and design documents ## Introduction Write technical specifications, Architecture Decision Records (ADRs), Request for Comments (RFCs), and design documents that drive better technical decisions. Use structured templates, version history, and AI assistance to create clear, comprehensive technical documentation. Good technical specs are the foundation of successful engineering projects. They capture context, document decisions, and provide a reference for future work. ## Why AutEng for Technical Specs? ### Structured Templates Follow best practices with structured formats for ADRs, RFCs, and design docs. AI helps you fill in the sections and ensures you don't miss important details. ### Decision Tracking Version history tracks every decision and change. See why decisions were made and how they evolved over time. Never lose context again. ### Easy Review Process Share specs with stakeholders using public links. Visual diffs make it easy to see what changed between versions during review cycles. ## Architecture Decision Records (ADRs) ADRs document important architectural decisions, their context, and consequences. They help teams understand why decisions were made and provide a historical record. ```markdown # ADR 001: Use PostgreSQL for Primary Database ## Status Accepted ## Context We need to choose a database for our new application. Requirements: - ACID compliance for financial transactions - Support for complex queries and joins - Strong ecosystem and community support - Ability to scale vertically and horizontally ## Decision We will use PostgreSQL as our primary database. ## Consequences ### Positive - Excellent ACID compliance and data integrity - Rich feature set (JSON, full-text search, etc.) - Strong community and tooling support - Good performance for our use case ### Negative - Requires more operational expertise than managed NoSQL - Vertical scaling has limits - Need to plan for replication and backups ## Alternatives Considered - **MySQL**: Similar features but weaker JSON support - **MongoDB**: Better horizontal scaling but no ACID guarantees - **DynamoDB**: Fully managed but vendor lock-in concerns ``` ## Request for Comments (RFCs) RFCs propose changes and gather feedback from your team. They're perfect for planning major features, architectural changes, or process improvements. ```markdown # RFC: Implement Rate Limiting for Public API ## Summary Implement rate limiting on our public API to prevent abuse and ensure fair usage. ## Motivation We've seen increased API usage that's impacting performance for all users. We need to: - Prevent abuse and DoS attacks - Ensure fair resource allocation - Protect backend services from overload ## Proposed Solution Implement token bucket rate limiting at the API gateway level: \`\`\`mermaid flowchart LR Client[Client] --> Gateway[API Gateway] Gateway --> RateLimit[Rate Limiter] RateLimit -->|Allowed| Backend[Backend Services] RateLimit -->|Denied| Error[429 Too Many Requests] \`\`\` ### Rate Limits | Tier | Requests/minute | Burst | |------|----------------|-------| | Free | 60 | 10 | | Pro | 600 | 100 | | Enterprise | Custom | Custom | ## Implementation Plan 1. **Phase 1**: Add rate limiting middleware (Week 1) 2. **Phase 2**: Implement Redis-backed storage (Week 2) 3. **Phase 3**: Add monitoring and alerts (Week 3) 4. **Phase 4**: Roll out to production with logging only (Week 4) 5. **Phase 5**: Enable enforcement (Week 5) ## Alternatives Considered - **Application-level limiting**: More complex, harder to maintain - **Third-party service**: Additional cost and latency ``` ## Design Documents Design documents detail system designs before implementation. They help teams align on approach and identify issues early. ```markdown # Design: Real-time Notification System ## Goals - Deliver notifications to users in real-time - Support multiple channels (web, mobile, email) - Handle 10,000+ concurrent connections - Ensure message delivery (at-least-once) ## Architecture \`\`\`mermaid flowchart TB App[Application] --> Queue[Message Queue] Queue --> Worker[Notification Workers] Worker --> WebSocket[WebSocket Server] Worker --> Push[Push Service] Worker --> Email[Email Service] WebSocket --> Client[Web Clients] Push --> Mobile[Mobile Apps] \`\`\` ## Components ### Message Queue - Use Redis Streams for message buffering - Supports consumer groups for scaling - Persistence for reliability ### WebSocket Server - Node.js with Socket.io - Horizontal scaling with Redis adapter - Automatic reconnection handling ### Notification Workers - Python workers using Dramatiq - Process messages from queue - Route to appropriate channel ## Data Model \`\`\`typescript interface Notification { id: string userId: string type: 'info' | 'warning' | 'error' title: string message: string channels: ('web' | 'mobile' | 'email')[] createdAt: Date } \`\`\` ## Security Considerations - Authenticate WebSocket connections with JWT - Rate limit notification creation - Validate user permissions before delivery ``` ## Best Practices - **Start with context:** Explain the problem and why it matters before jumping to solutions - **Document alternatives:** Show what options you considered and why you chose your approach - **Use diagrams:** Visual representations make complex systems easier to understand - **Be specific:** Include concrete examples, data models, and implementation details - **Track decisions:** Use version history to see how specs evolved during review - **Keep it updated:** Update specs as implementation reveals new information --- # API Documentation > Document REST APIs and GraphQL schemas with examples ## Introduction Create comprehensive API documentation that developers actually want to read. Document REST APIs, GraphQL schemas, authentication flows, and endpoint specifications using Markdown, Mermaid diagrams, and AI assistance. Modern API documentation needs to be more than just a list of endpoints. It should include interactive examples, visual flows, and clear explanations that help developers integrate quickly and correctly. ## Why AutEng for API Documentation? ### Interactive Examples Include code examples in multiple languages with syntax highlighting. Show request/response examples that developers can copy and use immediately. ### Visual API Flows Use sequence diagrams to show authentication flows, request lifecycles, and error handling. Make complex APIs easy to understand at a glance. ### Always Up-to-Date Version history tracks every change. Update docs as your API evolves and maintain accuracy with visual diffs. ## REST API Endpoints Document your REST API with clear endpoint specifications including HTTP methods, URLs, parameters, and response formats. ```markdown # GET /api/users/:id Retrieve a user by ID. ## Request \`\`\`http GET /api/users/123 Authorization: Bearer \`\`\` ## Response \`\`\`json { "user_id": "123", "name": "John Doe", "email": "john@example.com", "created_at": "2025-01-01T00:00:00Z" } \`\`\` ## Status Codes - **200 OK** - User found - **401 Unauthorized** - Invalid or missing token - **404 Not Found** - User does not exist ``` ## GraphQL Schemas Document GraphQL APIs with schema definitions, queries, mutations, and field-level documentation. ```markdown # User Type \`\`\`graphql type User { id: ID! name: String! email: String! posts: [Post!]! } \`\`\` ## Query Example \`\`\`graphql query GetUser($id: ID!) { user(id: $id) { id name email posts { title content } } } \`\`\` ## Variables \`\`\`json { "id": "123" } \`\`\` ``` ## Authentication Flows Visualize authentication and authorization processes with sequence diagrams. Show OAuth flows, JWT token handling, and API key management. ```markdown # OAuth 2.0 Authorization Code Flow \`\`\`mermaid sequenceDiagram participant User participant Client participant AuthServer participant API User->>Client: Click "Login" Client->>AuthServer: Redirect to /authorize AuthServer->>User: Show login page User->>AuthServer: Enter credentials AuthServer->>Client: Redirect with code Client->>AuthServer: POST /token with code AuthServer->>Client: Return access_token Client->>API: Request with Bearer token API->>Client: Return protected resource \`\`\` The authorization code flow is the most secure OAuth 2.0 flow for web applications. ``` ## Error Handling Document error responses, status codes, and troubleshooting guides to help developers handle edge cases. ```markdown # Error Responses All errors follow a consistent format: \`\`\`json { "error": { "code": "INVALID_REQUEST", "message": "The request is missing required parameters", "details": { "missing_fields": ["email", "password"] } } } \`\`\` ## Common Error Codes | Code | Status | Description | |------|--------|-------------| | INVALID_REQUEST | 400 | Missing or invalid parameters | | UNAUTHORIZED | 401 | Invalid or expired token | | FORBIDDEN | 403 | Insufficient permissions | | NOT_FOUND | 404 | Resource does not exist | | RATE_LIMITED | 429 | Too many requests | ``` ## Best Practices - **Start with the basics:** Document endpoints, methods, and parameters before adding advanced features - **Include real examples:** Show actual request/response payloads that developers can copy - **Use sequence diagrams:** Visualize complex flows like authentication and multi-step processes - **Document error cases:** Show what happens when things go wrong and how to handle it - **Keep it updated:** Use version history to track changes as your API evolves --- # KaTeX Syntax Quick Reference — Math Equations in Markdown > Complete reference for KaTeX mathematical notation including common formulas, symbols, and usage patterns for technical documentation. ## Introduction KaTeX is a fast, easy-to-use JavaScript library for rendering mathematical notation in web browsers. It supports a large subset of LaTeX syntax and is perfect for technical documentation, research papers, and educational content. This comprehensive reference covers the most commonly used KaTeX syntax patterns, from basic arithmetic to advanced mathematical notation. Whether you're documenting algorithms, writing research papers, or creating educational content, this guide will help you express mathematical concepts clearly and beautifully. > **Quick Start:** In AutEng, wrap your math expressions in `$...$` for inline math or `$$...$$` for display (block) math. The rendering happens automatically in real-time. All math content must be wrapped in these delimiters to render correctly. For display math, place the `$$` delimiters on their own lines. ## Basic Syntax ### Inline vs Display Math Use single dollar signs `$...$` for inline math that flows with text, and double dollar signs `$$...$$` for display math that appears on its own line. ```markdown The quadratic formula $x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$ is used to solve quadratic equations. For a more prominent display: $$ x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} $$ ``` ### Superscripts and Subscripts Use `^` for superscripts and `_` for subscripts. Wrap multi-character superscripts/subscripts in curly braces. ```markdown Basic: $x^2$, $x_i$, $x^{10}$, $x_{max}$ Combined: $x_i^2$, $x_{i,j}^{(k)}$ Nested: $e^{x^2}$, $x_{y_z}$ ``` ## Fractions and Roots ### Fractions Use `\frac{'{numerator}'} {'{denominator}'}` for fractions. For inline fractions, consider using `\tfrac` (text-style) or the slash notation. ```markdown Display fraction: $$ \\frac{a}{b} $$ Inline fraction: $\\frac{1}{2}$ or $\\tfrac{1}{2}$ or $1/2$ Nested fractions: $$ \\frac{1}{1 + \\frac{1}{2}} $$ Complex fractions: $$ \\frac{x^2 + 2x + 1}{x^2 - 1} $$ ``` ### Roots Use `\sqrt` for square roots and `\sqrt[n]` for nth roots. ```markdown Square root: $\\sqrt{x}$, $\\sqrt{x^2 + y^2}$ Cube root: $\\sqrt[3]{x}$ nth root: $\\sqrt[n]{x}$ Nested: $\\sqrt{1 + \\sqrt{x}}$ ``` ## Greek Letters Greek letters are essential in mathematics. Use backslash followed by the letter name. Capitalize for uppercase Greek letters. ```markdown Lowercase: $\\alpha$, $\\beta$, $\\gamma$, $\\delta$, $\\epsilon$, $\\theta$, $\\lambda$, $\\mu$, $\\pi$, $\\sigma$, $\\phi$, $\\omega$ Uppercase: $\\Gamma$, $\\Delta$, $\\Theta$, $\\Lambda$, $\\Sigma$, $\\Phi$, $\\Omega$ Variants: $\\varepsilon$, $\\vartheta$, $\\varphi$ In equations: $$ \\theta = \\arctan\\left(\\frac{y}{x}\\right) $$ ``` ## Operators and Symbols ### Basic Operators ```markdown Arithmetic: $+$, $-$, $\\times$, $\\div$, $\\pm$, $\\mp$ Comparison: $=$, $\\neq$, $<$, $>$, $\\leq$, $\\geq$, $\\approx$, $\\equiv$ Set operations: $\\in$, $\\notin$, $\\subset$, $\\subseteq$, $\\cup$, $\\cap$, $\\emptyset$ Logic: $\\land$, $\\lor$, $\\neg$, $\\implies$, $\\iff$ ``` ### Large Operators Large operators like sums, products, and integrals automatically adjust their size in display mode. ```markdown Summation: $$ \\sum_{i=1}^{n} i = \\frac{n(n+1)}{2} $$ Product: $$ \\prod_{i=1}^{n} i = n! $$ Integral: $$ \\int_{0}^{\\infty} e^{-x} dx = 1 $$ Multiple integrals: $$ \\iint_D f(x,y) \\, dA $$ Limits: $$ \\lim_{x \\to \\infty} \\frac{1}{x} = 0 $$ ``` ## Brackets and Delimiters Use `\left` and `\right` to make brackets automatically size to their contents. This works with parentheses, brackets, braces, and absolute value bars. ```markdown Without auto-sizing: $$ (\\frac{x}{y}) $$ With auto-sizing: $$ \\left(\\frac{x}{y}\\right) $$ Different delimiters: - Parentheses: $\\left(x\\right)$ - Brackets: $\\left[x\\right]$ - Braces: $\\left\\{x\\right\\}$ - Absolute value: $\\left|x\\right|$ - Norms: $\\left\\|x\\right\\|$ - Angle brackets: $\\left\\langle x \\right\\rangle$ Mixed: $$ \\left[\\frac{x^2}{y} + \\left(\\frac{a}{b}\\right)^2\\right] $$ ``` ## Matrices and Arrays Use `\begin{'{matrix}'}` environments for matrices. Use `&` to separate columns and `\\` for new rows. > **Delimiters Required:** Matrix environments must be wrapped in `$$...$$` delimiters to render correctly. Place the `$$` on separate lines before and after the matrix environment. ```markdown Basic matrix: $$ \\begin{matrix} a & b \\\\ c & d \\end{matrix} $$ With parentheses: $$ \\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix} $$ With brackets: $$ \\begin{bmatrix} 1 & 2 & 3 \\\\ 4 & 5 & 6 \\\\ 7 & 8 & 9 \\end{bmatrix} $$ Determinant: $$ \\begin{vmatrix} a & b \\\\ c & d \\end{vmatrix} = ad - bc $$ ``` ## Calculus Notation ### Derivatives ```markdown Prime notation: $f'(x)$, $f''(x)$, $f'''(x)$ Leibniz notation: $\\frac{df}{dx}$, $\\frac{d^2f}{dx^2}$ Partial derivatives: $\\frac{\\partial f}{\\partial x}$, $\\frac{\\partial^2 f}{\\partial x \\partial y}$ Dot notation: $\\dot{x}$, $\\ddot{x}$ Example: $$ \\frac{d}{dx}\\left(x^2\\right) = 2x $$ ``` ### Integrals ```markdown Indefinite: $\\int f(x) \\, dx$ Definite: $\\int_{a}^{b} f(x) \\, dx$ Multiple: $\\iiint_V f(x,y,z) \\, dV$ Contour: $\\oint_C f(z) \\, dz$ Example: $$ \\int_{0}^{\\pi} \\sin(x) \\, dx = 2 $$ ``` ## Special Functions Common mathematical functions have special formatting to distinguish them from variables. ```markdown Trigonometric: $\\sin(x)$, $\\cos(x)$, $\\tan(x)$, $\\sec(x)$, $\\csc(x)$, $\\cot(x)$ Inverse trig: $\\arcsin(x)$, $\\arccos(x)$, $\\arctan(x)$ Hyperbolic: $\\sinh(x)$, $\\cosh(x)$, $\\tanh(x)$ Logarithms: $\\log(x)$, $\\ln(x)$, $\\log_{10}(x)$ Other: $\\exp(x)$, $\\max(x,y)$, $\\min(x,y)$, $\\gcd(a,b)$ Example: $$ \\sin^2(x) + \\cos^2(x) = 1 $$ ``` ## Accents and Decorations Add accents and decorations to variables for additional notation. ```markdown Hat: $\\hat{x}$, $\\widehat{xyz}$ Bar: $\\bar{x}$, $\\overline{xyz}$ Tilde: $\\tilde{x}$, $\\widetilde{xyz}$ Dot: $\\dot{x}$, $\\ddot{x}$ Vector: $\\vec{v}$, $\\overrightarrow{AB}$ Underline: $\\underline{x}$ Example: $$ \\vec{F} = m\\vec{a} $$ ``` ## Text in Math Mode Use `\text{'{...}'}` to include regular text within math expressions. This is essential for units, labels, and explanations. ```markdown With units: $v = 50 \\text{ m/s}$ With labels: $$ f(x) = \\begin{cases} x^2 & \\text{if } x \\geq 0 \\\\ -x^2 & \\text{if } x < 0 \\end{cases} $$ With explanations: $P(A|B) = \\frac{P(B|A)P(A)}{P(B)} \\text{ (Bayes' Theorem)}$ ``` ## Spacing and Alignment ### Manual Spacing Sometimes you need to adjust spacing manually. KaTeX provides several spacing commands. ```markdown Thin space: $a\\,b$ (\\,) Medium space: $a\\:b$ (\\:) Thick space: $a\\;b$ (\\;) Quad space: $a\\quad b$ (\\quad) Double quad: $a\\qquad b$ (\\qquad) Negative space: $a\\!b$ (\\!) ``` ### Aligned Equations Use the `aligned` environment to align multiple equations at specific points (usually the equals sign). Like matrix environments, `aligned` must be wrapped in `$$...$$` delimiters on separate lines. ```markdown $$ \\begin{aligned} x &= a + b \\\\ &= c + d \\\\ &= e + f \\end{aligned} $$ With explanations: $$ \\begin{aligned} (x + y)^2 &= (x + y)(x + y) \\\\ &= x^2 + xy + yx + y^2 \\\\ &= x^2 + 2xy + y^2 \\end{aligned} $$ ``` ## Common Patterns ### Piecewise Functions ```markdown $$ f(x) = \\begin{cases} x^2 & \\text{if } x \\geq 0 \\\\ -x^2 & \\text{if } x < 0 \\end{cases} $$ $$ |x| = \\begin{cases} x & \\text{if } x \\geq 0 \\\\ -x & \\text{if } x < 0 \\end{cases} $$ ``` ### Binomial Coefficients ```markdown Binomial coefficient: $\\binom{n}{k}$ In equations: $$ (x + y)^n = \\sum_{k=0}^{n} \\binom{n}{k} x^{n-k} y^k $$ Alternative notation: $C(n,k) = \\binom{n}{k} = \\frac{n!}{k!(n-k)!}$ ``` ### Set Notation ```markdown Set definition: $S = \\{x \\in \\mathbb{R} : x > 0\\}$ Set operations: $A \\cup B$, $A \\cap B$, $A \\setminus B$ Special sets: $\\mathbb{N}$, $\\mathbb{Z}$, $\\mathbb{Q}$, $\\mathbb{R}$, $\\mathbb{C}$ Cardinality: $|S|$ or $\\#S$ Example: $$ \\mathbb{N} = \\{1, 2, 3, \\ldots\\} $$ ``` ## Best Practices > **Use Display Math for Complex Equations:** Complex equations are easier to read when displayed on their own line. Use `$$...$$` for equations that are the focus of discussion. > **Add Spacing Around Operators:** Use `\,` to add thin spaces around differentials and between function arguments for better readability: `$\int f(x) \, dx$` > **Use \text for Units and Labels:** Always wrap units and text labels in `\text{'{...}'}` to ensure proper formatting and spacing. > **Consistent Notation:** Be consistent with your notation throughout your document. If you use `$\vec{'{v}'}$` for vectors, use it everywhere. > **Avoid Overuse of Inline Math:** Too much inline math can make text hard to read. Consider using display math or breaking up dense mathematical content. ## Common Mistakes > **Forgetting Curly Braces:** `$x^10$` renders as $x^10$ (wrong), while `$x^{'{10}'}$` renders correctly as $x^ {'{10}'}$. Always use braces for multi-character superscripts/subscripts. > **Missing \left and \right:** Brackets don't auto-size without `\left` and `\right`. Compare `$(\frac{'{x}'} {'{y}'}$` vs `$\left(\frac{'{x}'} {'{y}'}\right)$` . > **Incorrect Function Names:** Use `\sin`, not `sin`. The backslash ensures proper formatting and spacing. > **Forgetting Spacing in Integrals:** Always add `\,` before `dx` in integrals: `$\int f(x) \, dx$` > **Missing Math Delimiters:** All math content must be wrapped in `$...$` or `$$...$$` delimiters. Environments like `\begin{'{matrix}'}`, `\begin{'{aligned}'}`, and `\begin{'{cases}'}` will not render without these delimiters. For display math, place `$$` on separate lines. ## Quick Reference Table | Category | Syntax | Example | | --- | --- | --- | | Superscript | x^2 | $x^2$ | | Subscript | x_i | $x_i$ | | Fraction | `\frac{'{a}'} {'{b}'}` | $\frac{'{a}'} {'{b}'}$ | | Square root | `\sqrt{'{x}'}` | $\sqrt{'{x}'}$ | | Sum | `\sum_{'{i=1}'}^{'{n}'}` | $\sum_{'{i=1}'}^{'{n}'}$ | | Integral | `\int_{'{a}'}^{'{b}'}` | $\int_{'{a}'}^{'{b}'}$ | | Limit | `\lim_{'{x \\to \\infty}'}` | $\lim_{'{x \\to \\infty}'}$ | | Greek letter | `\alpha, \beta, \gamma` | $\alpha, \beta, \gamma$ | --- # Calculus in Technical Documentation — Derivatives and Integrals > Master calculus notation in technical docs with KaTeX. Learn derivatives, integrals, limits, and differential equations for software, physics, and engineering documentation. ## Introduction Calculus is the mathematical foundation for describing change and accumulation. Whether you're documenting machine learning algorithms, physics simulations, financial models, or engineering systems, calculus notation appears everywhere in technical documentation. This guide covers how to express derivatives, integrals, limits, and differential equations using KaTeX in your technical documentation. You'll learn the standard notation conventions and see practical examples from software engineering, physics, and data science. > **Prerequisites:** This guide assumes familiarity with basic KaTeX syntax. If you're new to KaTeX, start with our [KaTeX Syntax Quick Reference](/docs/math/notation/katex-syntax) first. ## Derivatives Derivatives measure the rate of change of a function. There are several notation styles, each suited to different contexts in technical documentation. ### Leibniz Notation Leibniz notation explicitly shows the variable of differentiation, making it ideal for physics and engineering documentation where multiple variables are involved. ```markdown First derivative: $$ \\frac{dy}{dx} $$ Second derivative: $$ \\frac{d^2y}{dx^2} $$ nth derivative: $$ \\frac{d^n y}{dx^n} $$ Derivative of a specific function: $$ \\frac{d}{dx}\\left(x^3 + 2x\\right) = 3x^2 + 2 $$ ``` ### Prime Notation (Lagrange) Prime notation is compact and commonly used in pure mathematics and algorithm analysis where the independent variable is clear from context. ```markdown First derivative: $f'(x)$ Second derivative: $f''(x)$ Third derivative: $f'''(x)$ Higher derivatives: $f^{(n)}(x)$ Example - velocity and acceleration: $$ \\text{Position: } s(t), \\quad \\text{Velocity: } s'(t), \\quad \\text{Acceleration: } s''(t) $$ ``` ### Dot Notation (Newton) Dot notation is standard in physics for time derivatives, particularly in mechanics and dynamics. ```markdown First time derivative: $\\dot{x}$ Second time derivative: $\\ddot{x}$ Newton's second law: $$ F = m\\ddot{x} $$ Velocity and acceleration: $$ v = \\dot{x}, \\quad a = \\ddot{x} $$ ``` ### Operator Notation The differential operator D is useful when discussing derivatives abstractly or in differential equations. ```markdown Differential operator: $$ D = \\frac{d}{dx} $$ Applied to a function: $$ Df = \\frac{df}{dx}, \\quad D^2f = \\frac{d^2f}{dx^2} $$ Linear differential equation: $$ (D^2 + 3D + 2)y = 0 $$ ``` ## Partial Derivatives Partial derivatives are essential for documenting multivariable functions, which appear frequently in machine learning (gradient descent), physics (field equations), and optimization problems. ```markdown First partial derivatives: $$ \\frac{\\partial f}{\\partial x}, \\quad \\frac{\\partial f}{\\partial y} $$ Second partial derivatives: $$ \\frac{\\partial^2 f}{\\partial x^2}, \\quad \\frac{\\partial^2 f}{\\partial y^2} $$ Mixed partial derivatives: $$ \\frac{\\partial^2 f}{\\partial x \\partial y} $$ Example - gradient of a function: $$ f(x, y) = x^2 + xy + y^2 $$ $$ \\nabla f = \\left(\\frac{\\partial f}{\\partial x}, \\frac{\\partial f}{\\partial y}\\right) = (2x + y, x + 2y) $$ ``` ### Subscript Notation Subscript notation is a compact alternative commonly used in physics and engineering documentation. ```markdown Partial derivatives: $$ f_x = \\frac{\\partial f}{\\partial x}, \\quad f_y = \\frac{\\partial f}{\\partial y} $$ Second partials: $$ f_{xx} = \\frac{\\partial^2 f}{\\partial x^2}, \\quad f_{xy} = \\frac{\\partial^2 f}{\\partial x \\partial y} $$ Heat equation example: $$ u_t = \\alpha u_{xx} $$ ``` ## Gradient, Divergence, and Curl Vector calculus operators are fundamental in physics documentation, particularly for electromagnetic fields, fluid dynamics, and machine learning optimization. ```markdown Gradient (scalar to vector): $$ \\nabla f = \\left(\\frac{\\partial f}{\\partial x}, \\frac{\\partial f}{\\partial y}, \\frac{\\partial f}{\\partial z}\\right) $$ Divergence (vector to scalar): $$ \\nabla \\cdot \\vec{F} = \\frac{\\partial F_x}{\\partial x} + \\frac{\\partial F_y}{\\partial y} + \\frac{\\partial F_z}{\\partial z} $$ Curl (vector to vector): $$ \\nabla \\times \\vec{F} = \\begin{vmatrix} \\hat{i} & \\hat{j} & \\hat{k} \\\\ \\frac{\\partial}{\\partial x} & \\frac{\\partial}{\\partial y} & \\frac{\\partial}{\\partial z} \\\\ F_x & F_y & F_z \\end{vmatrix} $$ Laplacian: $$ \\nabla^2 f = \\frac{\\partial^2 f}{\\partial x^2} + \\frac{\\partial^2 f}{\\partial y^2} + \\frac{\\partial^2 f}{\\partial z^2} $$ ``` ## Integrals Integrals represent accumulation and are used extensively in probability theory, physics, and signal processing documentation. ### Indefinite Integrals ```markdown Basic indefinite integral: $$ \\int f(x) \\, dx $$ Power rule: $$ \\int x^n \\, dx = \\frac{x^{n+1}}{n+1} + C \\quad (n \\neq -1) $$ Exponential: $$ \\int e^x \\, dx = e^x + C $$ Trigonometric: $$ \\int \\sin(x) \\, dx = -\\cos(x) + C $$ ``` > **Spacing Tip:** Always use `\,` before `dx` to add proper spacing: `$\int f(x) \, dx$` looks better than `$\int f(x) dx$`. ### Definite Integrals ```markdown Definite integral: $$ \\int_{a}^{b} f(x) \\, dx $$ Fundamental theorem of calculus: $$ \\int_{a}^{b} f'(x) \\, dx = f(b) - f(a) $$ Area under a curve: $$ A = \\int_{0}^{2} x^2 \\, dx = \\left[\\frac{x^3}{3}\\right]_0^2 = \\frac{8}{3} $$ Probability density: $$ P(a \\leq X \\leq b) = \\int_{a}^{b} f(x) \\, dx $$ ``` ### Multiple Integrals ```markdown Double integral: $$ \\iint_D f(x, y) \\, dA $$ Triple integral: $$ \\iiint_V f(x, y, z) \\, dV $$ Iterated integral: $$ \\int_{0}^{1} \\int_{0}^{x} xy \\, dy \\, dx $$ Volume calculation: $$ V = \\iint_R f(x, y) \\, dA = \\int_{a}^{b} \\int_{c}^{d} f(x, y) \\, dy \\, dx $$ ``` ### Line and Surface Integrals ```markdown Line integral (scalar): $$ \\int_C f \\, ds $$ Line integral (vector): $$ \\int_C \\vec{F} \\cdot d\\vec{r} $$ Closed line integral: $$ \\oint_C \\vec{F} \\cdot d\\vec{r} $$ Surface integral: $$ \\iint_S \\vec{F} \\cdot d\\vec{S} $$ Closed surface integral: $$ \\oiint_S \\vec{F} \\cdot d\\vec{S} $$ ``` ## Limits Limits are foundational to calculus and appear in algorithm complexity analysis, convergence proofs, and asymptotic behavior documentation. ```markdown Basic limit: $$ \\lim_{x \\to a} f(x) $$ One-sided limits: $$ \\lim_{x \\to a^+} f(x), \\quad \\lim_{x \\to a^-} f(x) $$ Limit at infinity: $$ \\lim_{x \\to \\infty} \\frac{1}{x} = 0 $$ Limit definition of derivative: $$ f'(x) = \\lim_{h \\to 0} \\frac{f(x + h) - f(x)}{h} $$ Limit definition of e: $$ e = \\lim_{n \\to \\infty} \\left(1 + \\frac{1}{n}\\right)^n $$ ``` ### Limits in Series ```markdown Sequence limit: $$ \\lim_{n \\to \\infty} a_n = L $$ Infinite series: $$ \\sum_{n=1}^{\\infty} a_n = \\lim_{N \\to \\infty} \\sum_{n=1}^{N} a_n $$ Geometric series: $$ \\sum_{n=0}^{\\infty} r^n = \\frac{1}{1-r} \\quad (|r| < 1) $$ Taylor series: $$ f(x) = \\sum_{n=0}^{\\infty} \\frac{f^{(n)}(a)}{n!}(x-a)^n $$ ``` ## Differential Equations Differential equations model dynamic systems and appear throughout physics, engineering, and computational science documentation. ### Ordinary Differential Equations ```markdown First-order ODE: $$ \\frac{dy}{dx} = f(x, y) $$ Second-order ODE: $$ \\frac{d^2y}{dx^2} + p(x)\\frac{dy}{dx} + q(x)y = g(x) $$ Simple harmonic oscillator: $$ \\frac{d^2x}{dt^2} + \\omega^2 x = 0 $$ Solution: $$ x(t) = A\\cos(\\omega t) + B\\sin(\\omega t) $$ ``` ### Partial Differential Equations ```markdown Heat equation: $$ \\frac{\\partial u}{\\partial t} = \\alpha \\nabla^2 u $$ Wave equation: $$ \\frac{\\partial^2 u}{\\partial t^2} = c^2 \\nabla^2 u $$ Laplace equation: $$ \\nabla^2 \\phi = 0 $$ Schrödinger equation: $$ i\\hbar \\frac{\\partial \\Psi}{\\partial t} = -\\frac{\\hbar^2}{2m}\\nabla^2\\Psi + V\\Psi $$ ``` ## Applications in Technical Documentation Here are practical examples of calculus notation in common technical documentation scenarios. ### Machine Learning: Gradient Descent ```markdown **Gradient Descent Update Rule** The parameters $\\theta$ are updated iteratively: $$ \\theta_{n+1} = \\theta_n - \\alpha \\nabla J(\\theta_n) $$ where: - $\\alpha$ is the learning rate - $\\nabla J(\\theta)$ is the gradient of the cost function For a single parameter: $$ \\theta_{n+1} = \\theta_n - \\alpha \\frac{\\partial J}{\\partial \\theta} $$ **Cost Function Gradient** For mean squared error: $$ J(\\theta) = \\frac{1}{2m}\\sum_{i=1}^{m}(h_\\theta(x^{(i)}) - y^{(i)})^2 $$ $$ \\frac{\\partial J}{\\partial \\theta_j} = \\frac{1}{m}\\sum_{i=1}^{m}(h_\\theta(x^{(i)}) - y^{(i)})x_j^{(i)} $$ ``` ### Physics: Kinematics ```markdown **Position, Velocity, and Acceleration** Position as a function of time: $$ x(t) $$ Velocity (first derivative of position): $$ v(t) = \\frac{dx}{dt} = \\dot{x} $$ Acceleration (second derivative of position): $$ a(t) = \\frac{dv}{dt} = \\frac{d^2x}{dt^2} = \\ddot{x} $$ **Constant Acceleration** $$ \\begin{aligned} v(t) &= v_0 + at \\\\ x(t) &= x_0 + v_0 t + \\frac{1}{2}at^2 \\\\ v^2 &= v_0^2 + 2a(x - x_0) \\end{aligned} $$ ``` ### Statistics: Probability Distributions ```markdown **Probability Density Function** For a continuous random variable $X$: $$ P(a \\leq X \\leq b) = \\int_{a}^{b} f(x) \\, dx $$ **Normal Distribution** $$ f(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}} $$ **Expected Value** $$ E[X] = \\int_{-\\infty}^{\\infty} x \\cdot f(x) \\, dx $$ **Variance** $$ \\text{Var}(X) = E[X^2] - (E[X])^2 = \\int_{-\\infty}^{\\infty} (x - \\mu)^2 f(x) \\, dx $$ ``` ### Algorithm Analysis: Big O ```markdown **Asymptotic Analysis** Big O notation using limits: $$ f(n) = O(g(n)) \\iff \\lim_{n \\to \\infty} \\frac{f(n)}{g(n)} < \\infty $$ **Summation to Integral Approximation** For large $n$: $$ \\sum_{i=1}^{n} f(i) \\approx \\int_{1}^{n} f(x) \\, dx $$ Example - sum of squares: $$ \\sum_{i=1}^{n} i^2 \\approx \\int_{1}^{n} x^2 \\, dx = \\frac{n^3}{3} = O(n^3) $$ **Stirling's Approximation** $$ n! \\approx \\sqrt{2\\pi n}\\left(\\frac{n}{e}\\right)^n $$ $$ \\ln(n!) \\approx n\\ln(n) - n $$ ``` ## Best Practices > **Choose Notation Consistently:** Pick one notation style (Leibniz, prime, or dot) and use it consistently throughout your document. Mix only when conventions demand it (e.g., dot notation for time derivatives in physics). > **Use Display Math for Complex Expressions:** Complex derivatives and integrals are much easier to read in display mode. Reserve inline math for simple expressions like $f'(x)$ or $\int f \, dx$. > **Add Context and Definitions:** Always define your variables. Write "where $x$ is position and $t$ is time" after introducing equations. This helps readers unfamiliar with your specific domain. > **Use Aligned Environments for Multi-Step Derivations:** When showing step-by-step calculations, use the `aligned` environment to align equals signs, making the logic flow clear. > **Include Units Where Appropriate:** In physics and engineering docs, include units using `\text{'{}'}`: `$v = 10 \text{'{ m/s}'}$` ## Common Mistakes > **Missing Spacing in Integrals:** Always add `\,` before differentials. Write `$\int f(x) \, dx$` not `$\int f(x)dx$`. > **Incorrect Partial Derivative Symbol:** Use `\partial` for partial derivatives, not `d`. Write `$\frac{'{\\partial f}{\\partial x}'}$` not `$\frac{'{df}{dx}'}$` for multivariable functions. > **Forgetting Limits on Operators:** Large operators need limits. Write `$\lim_{'x \\to 0'}$` not just `$\lim$`, and `$\sum_{'i=1'}^{'n'}$` not just `$\sum$`. > **Inconsistent Vector Notation:** Choose one style for vectors: `$\vec{'{v}'}$`, `$\mathbf{'{v}'}$`, or bold. Don't mix them in the same document. > **Missing Parentheses in Function Arguments:** Write `$\sin(x)$` not `$\sin x$` when the argument is complex. This prevents ambiguity in expressions like `$\sin(x+y)$`. ## Quick Reference | Operation | KaTeX Syntax | Result | | --- | --- | --- | | Derivative (Leibniz) | `\frac{'{dy}{dx}'}` | $\frac{'{dy}{dx}'}$ | | Derivative (Prime) | f'(x) | $f'(x)$ | | Partial Derivative | `\frac{'\\partial f'} {'{\\partial x}'}` | $\frac{'\\partial f'} {'{\\partial x}'}$ | | Gradient | `\nabla f` | $\nabla f$ | | Indefinite Integral | `\int f(x) \, dx` | $\int f(x) \, dx$ | | Definite Integral | `\int_{'{a}'}^{'{b}'} f(x) \, dx` | $\int_{'{a}'}^{'{b}'} f(x) \, dx$ | | Double Integral | `\iint_D f \, dA` | $\iint_D f \, dA$ | | Limit | `\lim_{'{x \\to a}'} f(x)` | $\lim_{'{x \\to a}'} f(x)$ | | Time Derivative | `\dot{'{x}'}, \ddot{'{x}'}` | $\dot{'{x}'}$, $\ddot{'{x}'}$ | | Laplacian | `\nabla^2 f` | $\nabla^2 f$ | --- # Set Theory and Logic Notation — Mathematical Foundations > Complete guide to set theory and logic notation in technical documentation. Learn sets, operations, logic symbols, quantifiers, and proof notation with KaTeX. ## Introduction Set theory and logic form the foundation of mathematics and computer science. From database queries to type systems, from algorithm correctness proofs to formal verification, these concepts appear throughout technical documentation. This guide covers the essential notation for sets, set operations, propositional logic, predicate logic, and proof structures. You'll learn how to express these concepts clearly using KaTeX in your technical documentation. > **Prerequisites:** This guide assumes familiarity with basic KaTeX syntax. If you're new to KaTeX, start with our [KaTeX Syntax Quick Reference](/docs/math/notation/katex-syntax) first. ## Set Notation Basics Sets are collections of distinct objects. Understanding set notation is essential for documenting data structures, type systems, and mathematical specifications. ### Defining Sets ```markdown **Roster notation** (listing elements): $$ A = \{1, 2, 3, 4, 5\} $$ **Set-builder notation** (defining by property): $$ B = \{x \in \mathbb{Z} : x > 0\} $$ Alternative set-builder with vertical bar: $$ C = \{x \mid x^2 < 10\} $$ **Interval notation**: $$ [a, b] = \{x \in \mathbb{R} : a \leq x \leq b\} $$ $$ (a, b) = \{x \in \mathbb{R} : a < x < b\} $$ ``` ### Special Sets ```markdown **Number sets**: - Natural numbers: $\mathbb{N} = \{1, 2, 3, \ldots\}$ - Integers: $\mathbb{Z} = \{\ldots, -2, -1, 0, 1, 2, \ldots\}$ - Rationals: $\mathbb{Q} = \{\frac{p}{q} : p, q \in \mathbb{Z}, q \neq 0\}$ - Real numbers: $\mathbb{R}$ - Complex numbers: $\mathbb{C}$ **Special sets**: - Empty set: $\emptyset$ or $\{\}$ - Universal set: $U$ or $\mathcal{U}$ - Power set: $\mathcal{P}(A)$ or $2^A$ **Positive/negative variants**: $$ \mathbb{Z}^+ = \{1, 2, 3, \ldots\}, \quad \mathbb{R}^- = \{x \in \mathbb{R} : x < 0\} $$ ``` ### Set Membership and Relations ```markdown **Element membership**: - $x \in A$ — $x$ is an element of $A$ - $x \notin A$ — $x$ is not an element of $A$ **Subset relations**: - $A \subset B$ — $A$ is a proper subset of $B$ - $A \subseteq B$ — $A$ is a subset of $B$ (possibly equal) - $A \supset B$ — $A$ is a proper superset of $B$ - $A \supseteq B$ — $A$ is a superset of $B$ - $A \not\subset B$ — $A$ is not a subset of $B$ **Set equality**: $$ A = B \iff (A \subseteq B) \land (B \subseteq A) $$ ``` ## Set Operations Set operations are fundamental to database queries, type systems, and algorithm design. These operations combine or modify sets to create new sets. ### Basic Operations ```markdown **Union** (elements in either set): $$ A \cup B = \{x : x \in A \lor x \in B\} $$ **Intersection** (elements in both sets): $$ A \cap B = \{x : x \in A \land x \in B\} $$ **Set difference** (elements in $A$ but not $B$): $$ A \setminus B = \{x : x \in A \land x \notin B\} $$ Alternative notation: $A - B$ **Symmetric difference** (elements in exactly one set): $$ A \triangle B = (A \setminus B) \cup (B \setminus A) $$ Alternative: $A \oplus B$ ``` ### Complement and Power Set ```markdown **Complement** (elements not in $A$): $$ A^c = \overline{A} = U \setminus A = \{x \in U : x \notin A\} $$ **Power set** (set of all subsets): $$ \mathcal{P}(A) = \{S : S \subseteq A\} $$ Example: $$ \mathcal{P}(\{1, 2\}) = \{\emptyset, \{1\}, \{2\}, \{1, 2\}\} $$ **Cardinality of power set**: $$ |\mathcal{P}(A)| = 2^{|A|} $$ ``` ### Cartesian Product ```markdown **Cartesian product**: $$ A \times B = \{(a, b) : a \in A \land b \in B\} $$ Example: $$ \{1, 2\} \times \{a, b\} = \{(1, a), (1, b), (2, a), (2, b)\} $$ **n-fold Cartesian product**: $$ A^n = A \times A \times \cdots \times A \quad (n \text{ times}) $$ **Cardinality**: $$ |A \times B| = |A| \cdot |B| $$ ``` ### Indexed Operations ```markdown **Indexed union**: $$ \bigcup_{i=1}^{n} A_i = A_1 \cup A_2 \cup \cdots \cup A_n $$ $$ \bigcup_{i \in I} A_i = \{x : \exists i \in I, x \in A_i\} $$ **Indexed intersection**: $$ \bigcap_{i=1}^{n} A_i = A_1 \cap A_2 \cap \cdots \cap A_n $$ $$ \bigcap_{i \in I} A_i = \{x : \forall i \in I, x \in A_i\} $$ **Disjoint union**: $$ \bigsqcup_{i \in I} A_i $$ ``` ## Propositional Logic Propositional logic deals with statements that are either true or false. It's the foundation for boolean algebra, circuit design, and programming conditionals. ### Logical Connectives ```markdown **Negation** (NOT): $$ \neg P, \quad \lnot P, \quad \sim P, \quad \overline{P} $$ **Conjunction** (AND): $$ P \land Q, \quad P \cdot Q, \quad P \& Q $$ **Disjunction** (OR): $$ P \lor Q, \quad P + Q $$ **Exclusive OR** (XOR): $$ P \oplus Q, \quad P \veebar Q $$ **Implication** (IF...THEN): $$ P \implies Q, \quad P \to Q, \quad P \Rightarrow Q $$ **Biconditional** (IF AND ONLY IF): $$ P \iff Q, \quad P \leftrightarrow Q, \quad P \Leftrightarrow Q $$ ``` ### Truth Tables ```markdown **Implication truth table**: | $P$ | $Q$ | $P \implies Q$ | |:---:|:---:|:---:| | T | T | T | | T | F | F | | F | T | T | | F | F | T | **De Morgan's Laws**: $$ \neg(P \land Q) \equiv \neg P \lor \neg Q $$ $$ \neg(P \lor Q) \equiv \neg P \land \neg Q $$ ``` ### Logical Equivalences ```markdown **Contrapositive**: $$ (P \implies Q) \equiv (\neg Q \implies \neg P) $$ **Material implication**: $$ (P \implies Q) \equiv (\neg P \lor Q) $$ **Distributive laws**: $$ P \land (Q \lor R) \equiv (P \land Q) \lor (P \land R) $$ $$ P \lor (Q \land R) \equiv (P \lor Q) \land (P \lor R) $$ **Double negation**: $$ \neg(\neg P) \equiv P $$ **Absorption**: $$ P \lor (P \land Q) \equiv P $$ ``` ## Predicate Logic Predicate logic extends propositional logic with quantifiers and predicates, allowing us to make statements about objects and their properties. It's essential for formal specifications and mathematical proofs. ### Quantifiers ```markdown **Universal quantifier** (for all): $$ \forall x \in A, P(x) $$ "For all $x$ in $A$, property $P(x)$ holds" **Existential quantifier** (there exists): $$ \exists x \in A, P(x) $$ "There exists an $x$ in $A$ such that $P(x)$ holds" **Unique existence**: $$ \exists! x, P(x) $$ "There exists exactly one $x$ such that $P(x)$" **Negation of quantifiers**: $$ \neg(\forall x, P(x)) \equiv \exists x, \neg P(x) $$ $$ \neg(\exists x, P(x)) \equiv \forall x, \neg P(x) $$ ``` ### Nested Quantifiers ```markdown **Order matters**: "For every $x$, there exists a $y$": $$ \forall x, \exists y, P(x, y) $$ "There exists a $y$ for every $x$": $$ \exists y, \forall x, P(x, y) $$ **Example - Continuity**: $$ \forall \epsilon > 0, \exists \delta > 0, \forall x, (|x - a| < \delta \implies |f(x) - f(a)| < \epsilon) $$ **Example - Limit definition**: $$ \lim_{x \to a} f(x) = L \iff \forall \epsilon > 0, \exists \delta > 0, (0 < |x - a| < \delta \implies |f(x) - L| < \epsilon) $$ ``` ### Predicates and Relations ```markdown **Unary predicate** (property): $$ P(x) \text{ — "$x$ has property $P$"} $$ **Binary predicate** (relation): $$ R(x, y) \text{ — "$x$ is related to $y$ by $R$"} $$ Alternative notation: $xRy$ **Examples**: - $\text{Prime}(n)$ — "$n$ is prime" - $x < y$ — "$x$ is less than $y$" - $x \equiv y \pmod{n}$ — "$x$ is congruent to $y$ modulo $n$" **Relation properties**: - Reflexive: $\forall x, xRx$ - Symmetric: $\forall x, y, (xRy \implies yRx)$ - Transitive: $\forall x, y, z, (xRy \land yRz \implies xRz)$ ``` ## Proof Notation Mathematical proofs require specific notation to express logical structure clearly. This notation is essential for formal verification, algorithm correctness, and mathematical documentation. ### Proof Structure Symbols ```markdown **Therefore / Hence**: $$ \therefore \quad \text{(therefore)} $$ **Because / Since**: $$ \because \quad \text{(because)} $$ **QED / End of proof**: $$ \square \quad \blacksquare \quad \text{Q.E.D.} $$ **Contradiction**: $$ \bot \quad \text{(contradiction/false)} $$ **Tautology**: $$ \top \quad \text{(tautology/true)} $$ **Turnstile** (proves/entails): $$ \vdash \quad \text{(syntactic entailment)} $$ $$ \models \quad \text{(semantic entailment)} $$ ``` ### Proof by Contradiction ```markdown **Proof by contradiction**: To prove $P$: 1. Assume $\neg P$ 2. Derive a contradiction: $Q \land \neg Q$ 3. Conclude $P$ must be true **Example - $\sqrt{2}$ is irrational**: Assume $\sqrt{2} = \frac{p}{q}$ where $\gcd(p, q) = 1$. Then $2 = \frac{p^2}{q^2}$, so $p^2 = 2q^2$. $\therefore p^2$ is even, so $p$ is even. Let $p = 2k$. Then $4k^2 = 2q^2$, so $q^2 = 2k^2$. $\therefore q$ is even. But $\gcd(p, q) = 1$. $\bot$ $\therefore \sqrt{2}$ is irrational. $\square$ ``` ### Mathematical Induction ```markdown **Principle of Mathematical Induction**: To prove $\forall n \in \mathbb{N}, P(n)$: 1. **Base case**: Prove $P(1)$ 2. **Inductive step**: Prove $P(k) \implies P(k+1)$ **Example - Sum formula**: **Claim**: $\sum_{i=1}^{n} i = \frac{n(n+1)}{2}$ **Base case** ($n = 1$): $$ \sum_{i=1}^{1} i = 1 = \frac{1 \cdot 2}{2} \checkmark $$ **Inductive step**: Assume true for $k$. Then: $$ \sum_{i=1}^{k+1} i = \sum_{i=1}^{k} i + (k+1) = \frac{k(k+1)}{2} + (k+1) $$ $$ = \frac{k(k+1) + 2(k+1)}{2} = \frac{(k+1)(k+2)}{2} \checkmark $$ $\therefore$ By induction, the formula holds $\forall n \in \mathbb{N}$. $\square$ ``` ## Applications in Technical Documentation Here are practical examples of set theory and logic notation in common technical documentation scenarios. ### Type Systems ```markdown **Type as a set**: $$ \text{Int} = \{\ldots, -2, -1, 0, 1, 2, \ldots\} $$ **Union types**: $$ \text{String} \cup \text{Number} $$ **Intersection types**: $$ \text{Serializable} \cap \text{Comparable} $$ **Subtyping**: $$ \text{Integer} \subseteq \text{Number} \subseteq \text{Object} $$ **Generic types**: $$ \text{List}\langle T \rangle = \{[x_1, x_2, \ldots] : x_i \in T\} $$ **Function types**: $$ f: A \to B \quad \text{means} \quad f \in B^A $$ ``` ### Database Queries ```markdown **Selection** (filter rows): $$ \sigma_{\text{age} > 21}(\text{Users}) $$ **Projection** (select columns): $$ \pi_{\text{name, email}}(\text{Users}) $$ **Join**: $$ \text{Users} \bowtie_{\text{Users.id} = \text{Orders.user\_id}} \text{Orders} $$ **Set operations on tables**: $$ \text{ActiveUsers} \cup \text{PremiumUsers} $$ $$ \text{AllUsers} \setminus \text{BannedUsers} $$ **Query composition**: $$ \pi_{\text{name}}(\sigma_{\text{status} = \text{'active'}}(\text{Users})) $$ ``` ### Algorithm Specifications ```markdown **Precondition**: $$ \text{Pre}: \forall i \in [0, n), A[i] \in \mathbb{Z} $$ **Postcondition**: $$ \text{Post}: \forall i \in [0, n-1), A[i] \leq A[i+1] $$ **Loop invariant**: $$ \text{Inv}: \forall j \in [0, i), A[j] \leq A[j+1] $$ **Termination**: $$ \text{Variant}: n - i \geq 0 \land \text{decreasing} $$ **Hoare triple**: $$ \{P\} \, S \, \{Q\} $$ "If precondition $P$ holds before executing $S$, then postcondition $Q$ holds after." ``` ### Boolean Algebra in Circuits ```markdown **Basic gates**: - AND: $Y = A \cdot B$ - OR: $Y = A + B$ - NOT: $Y = \overline{A}$ - XOR: $Y = A \oplus B$ - NAND: $Y = \overline{A \cdot B}$ **Boolean simplification**: $$ \overline{A \cdot B} + A = \overline{A} + \overline{B} + A = 1 $$ **Sum of products**: $$ F = \overline{A}BC + A\overline{B}C + AB\overline{C} $$ **Product of sums**: $$ F = (A + B)(\overline{A} + C)(B + \overline{C}) $$ ``` ## Best Practices > **Use Standard Notation:** Stick to widely recognized symbols. Use $\\in$ for membership, $\\subseteq$ for subsets, and $\\forall$/$\\exists$ for quantifiers. Avoid inventing new notation unless absolutely necessary. > **Define Your Universe:** Always specify the domain of discourse. Write "$\\forall x \\in \\mathbb{R}$" rather than just "$\\forall x$" to avoid ambiguity about what values x can take. > **Use Set-Builder Notation for Complex Sets:** When a set cannot be easily listed, use set-builder notation like `$\\{x \\in A : P(x)\\}$` to clearly express "all elements of $A$ satisfying property $P$". > **Break Down Complex Formulas:** For nested quantifiers or complex logical expressions, introduce intermediate definitions or break the formula across multiple lines with explanations. > **Use Aligned Environments for Proofs:** When showing step-by-step derivations, use the `aligned` environment to align equals signs and implications for clarity. ## Common Mistakes > **Confusing $\\in$ and $\\subseteq$:** Use $\\in$ for element membership ($x \\in A$) and $\\subseteq$ for subset relations ($B \\subseteq A$). An element is not a subset, and a set is not an element (usually). > **Wrong Quantifier Order:** "$\\forall x, \\exists y, P(x, y)$" and "$\\exists y, \\forall x, P(x, y)$" mean different things. The first says "for each $x$, there is some $y$" (possibly different for each $x$). The second says "there is one $y$ that works for all $x$". > **Forgetting Negation Rules:** When negating quantified statements, flip the quantifier and negate the predicate: $\\neg(\\forall x, P(x)) \\equiv \\exists x, \\neg P(x)$. > **Misusing Implication:** Remember that $P \\implies Q$ is true when $P$ is false, regardless of $Q$. This "vacuous truth" often confuses readers unfamiliar with formal logic. > **Inconsistent Set Notation:** Do not mix `{1,2,3}` with `(1,2,3)` for sets. Curly braces denote sets; parentheses denote ordered tuples or intervals. ## Quick Reference | Concept | KaTeX Syntax | Result | |---|---|---| | Element of | `x \in A` | $x \in A$ | | Subset | `A \subseteq B` | $A \subseteq B$ | | Union | `A \cup B` | $A \cup B$ | | Intersection | `A \cap B` | $A \cap B$ | | Empty set | `\emptyset` | $\emptyset$ | | For all | `\forall x` | $\forall x$ | | There exists | `\exists x` | $\exists x$ | | Negation | `\neg P` | $\neg P$ | | AND | `P \land Q` | $P \land Q$ | | OR | `P \lor Q` | $P \lor Q$ | | Implies | `P \implies Q` | $P \implies Q$ | | If and only if | `P \iff Q` | $P \iff Q$ | | Therefore | `\therefore` | $\therefore$ | --- # CAS Verification Demo — Automated Math Checking > Interactive examples demonstrating AutEng's Computer Algebra System (CAS) verification. See how mathematical expressions and derivations are automatically verified with SymPy. ## Introduction AutEng's Computer Algebra System (CAS) automatically verifies mathematical expressions and derivations. Every math step is either **verified** (✅), **failed** (❌), or explicitly **unknown** (⚠️). This eliminates "math-looking slop" and ensures your derivations are trustworthy. The CAS uses SymPy for symbolic computation, running in a secure sandbox environment. > **How It Works:** Wrap your math in a `:::cas` block with the verification mode. The system will automatically check equivalence using symbolic computation and numeric testing. ## Quick Start Examples ### Example 1: Pythagorean Identity ✅ The fundamental trigonometric identity: ```markdown :::cas mode=equivalence engine=sympy $$ \\sin^2(x) + \\cos^2(x) = 1 $$ ::: ``` **Expected Result:** ✅ PASS — This identity holds for all values of x. ### Example 2: Common Algebra Mistake ❌ A frequent error in algebra — the binomial expansion is wrong: ```markdown :::cas mode=equivalence engine=sympy $$ (a+b)^2 = a^2 + b^2 $$ ::: ``` **Expected Result:** ❌ FAIL — Counterexample: a=1, b=1 gives 4 ≠ 2. The missing term is 2ab. ### Example 3: Double Angle Formula ✅ Verifying a trigonometric identity: ```markdown :::cas mode=equivalence engine=sympy $$ \\sin(2x) = 2\\sin(x)\\cos(x) $$ ::: ``` **Expected Result:** ✅ PASS ## Chain Verification (Step-by-Step Derivations) Use `mode=chain` to verify multi-step algebraic derivations. Each step is checked against the previous one. ### Example 4: Factoring with Assumptions This derivation requires the assumption x ≠ 1 to allow cancellation: ```markdown :::cas mode=chain engine=sympy assumptions="x != 1" $$ \\frac{x^2 - 1}{x - 1} $$ $$ = \\frac{(x-1)(x+1)}{x-1} $$ $$ = x + 1 $$ ::: ``` **Expected Result:** ✅ PASS — All steps verified with assumption x ≠ 1. ### Example 5: Difference of Squares ```markdown :::cas mode=chain engine=sympy assumptions="a != b" $$ \\frac{a^2 - b^2}{a - b} $$ $$ = \\frac{(a-b)(a+b)}{a-b} $$ $$ = a + b $$ ::: ``` **Expected Result:** ✅ PASS ## The Power of Assumptions Assumptions are critical for expressions involving square roots, logarithms, and division. ### Example 6: Square Root Identity **Without assumptions** — finds a counterexample: ```markdown :::cas mode=equivalence engine=sympy $$ \\sqrt{x^2} = x $$ ::: ``` **Expected Result:** ❌ FAIL — Counterexample: x = -2 gives √4 = 2 ≠ -2 **With the correct assumption:** ```markdown :::cas mode=equivalence engine=sympy assumptions="x >= 0" $$ \\sqrt{x^2} = x $$ ::: ``` **Expected Result:** ✅ PASS — With x ≥ 0, the identity holds. ### Example 7: Logarithm Identities **Product rule** (requires positive arguments): ```markdown :::cas mode=equivalence engine=sympy assumptions="x > 0, y > 0" $$ \\ln(xy) = \\ln(x) + \\ln(y) $$ ::: ``` **Expected Result:** ✅ PASS **Inverse relationship:** ```markdown :::cas mode=equivalence engine=sympy assumptions="x is real" $$ \\ln(e^x) = x $$ ::: ``` **Expected Result:** ✅ PASS ### Example 8: Invalid Logarithm Property ❌ A common mistake — this is NOT how logarithms work: ```markdown :::cas mode=equivalence engine=sympy $$ \\ln(x + y) = \\ln(x) + \\ln(y) $$ ::: ``` **Expected Result:** ❌ FAIL — Counterexample found. The product rule is ln(xy), not ln(x+y). ## Solution-Set Verification (mode=solve) Use `mode=solve` for equation-solving derivations where steps transform solution sets rather than just expressions. > **When to Use mode=solve:** Use `mode=solve` when your derivation involves operations like dividing both sides, taking square roots, or any step that might lose or introduce solutions. ### Example 9: Simple Equation Solving ```markdown :::cas mode=solve engine=sympy domain=R solve_var=x $$ 2x + 3 = 7 $$ $$ 2x = 4 $$ $$ x = 2 $$ ::: ``` **Expected Result:** ✅ EQUIV — All steps preserve the solution set. ### Example 10: Detecting Lost Solutions (NARROWS) When taking a square root without ±, solutions are lost: ```markdown :::cas mode=solve engine=sympy domain=R solve_var=x $$ x^2 = 4 $$ $$ x = 2 $$ ::: ``` **Expected Result:** ⚠️ NARROWS — Lost solution x = -2. The first equation has {'{-2, 2}'}, but the second only has {'{2}'}. ### Example 11: Correct Use of ± Using ± preserves all solutions: ```markdown :::cas mode=solve engine=sympy domain=R solve_var=x $$ x^2 = 4 $$ $$ x = \\pm 2 $$ ::: ``` **Expected Result:** ✅ EQUIV — Both equations have solution set {'{-2, 2}'}. ### Example 12: Detecting Extraneous Solutions (WIDENS) Squaring both sides can introduce extraneous solutions: ```markdown :::cas mode=solve engine=sympy domain=R solve_var=x $$ x = 2 $$ $$ x^2 = 4 $$ ::: ``` **Expected Result:** ⚠️ WIDENS — Added extraneous solution x = -2. ## Handling Unsupported Constructs Some mathematical constructs are not yet supported. The CAS will return UNKNOWN with helpful suggestions. ### Example 13: Integrals (Not Supported) ```markdown :::cas mode=equivalence engine=sympy $$ \\int x \\, dx = \\frac{x^2}{2} + C $$ ::: ``` **Expected Result:** ⚠️ UNKNOWN — Reason: `parse_unsupported`. Suggestion: Integrals, sums, products, and limits are not yet supported. ## Reference ### Supported LaTeX Constructs | Category | Constructs | | --- | --- | | Arithmetic | +, -, *, /, ^ | | Fractions | `\frac{'{a}'} {'{b}'}` | | Powers | x^2, x^{'{n+1}'} | | Trigonometric | `\sin, \cos, \tan, \cot, \sec, \csc` | | Inverse Trig | `\arcsin, \arccos, \arctan` | | Exponential/Log | `\exp, \ln, \log, e^x` | | Square Root | `\sqrt{'{x}'}, \sqrt[n]{'{x}'}` | | Greek Letters | `\alpha, \beta, \theta, etc.` | ### Not Supported (Returns UNKNOWN) - Integrals: `\int`, `\iint`, `\oint` - Sums/Products: `\sum`, `\prod` - Limits: `\lim` - Partial derivatives: `\partial` - Matrices, vectors, tensors ### Assumption Syntax | Format | Meaning | | --- | --- | | x > 0 | x is positive | | x >= 0 | x is non-negative | | x < 0 | x is negative | | x != 0 | x is non-zero | | x is real | x is a real number | | x is integer | x is an integer | ### Verification Modes | Mode | Use Case | | --- | --- | | equivalence | Single identity verification | | chain | Step-by-step expression rewrites | | solve | Equation-solving derivations | ### Status Indicators | Status | Meaning | | --- | --- | | ✅ PASS / EQUIV | Verified correct | | ❌ FAIL | Proven incorrect | | ⚠️ UNKNOWN | Cannot determine | | ⚠️ NARROWS | Lost solutions | | ⚠️ WIDENS | Extraneous solutions | ## Best Practices > **Always Include Relevant Assumptions:** For expressions involving square roots (need non-negative), logarithms (need positive), or fractions (need non-zero denominators), always specify the appropriate assumptions. > **Break Complex Derivations into Steps:** Smaller steps are easier to verify and debug. If a step fails, you can identify exactly where the error is. > **Use mode=solve for Equation Solving:** When your derivation involves operations that transform solution sets (dividing, taking roots), use `mode=solve` instead of `mode=chain`. > **Check UNKNOWN Suggestions:** When you get an UNKNOWN result, read the suggestions carefully. They often point to missing assumptions or unsupported constructs. > **Verify Incrementally:** Verify each step as you write to catch errors early. Don't wait until the end of a long derivation. ## Next Steps Ready to see a complete derivation with CAS verification? Check out the [Quadratic Formula Derivation](/docs/math/verification/quadratic-formula-derivation) tutorial, which demonstrates `mode=solve` for equation-solving steps. For proofs requiring induction, case analysis, or complex reasoning, check out [Lean 4 Theorem Proving](/docs/math/verification/lean-theorem-proving) — machine-checked formal proofs with Mathlib. --- # Quadratic Formula Derivation — Step-by-Step CAS Verification > Complete derivation of the quadratic formula with automated CAS verification. Learn how mode=solve verifies equation-solving steps and detects lost or extraneous solutions. ## Introduction This tutorial demonstrates the `mode=solve` feature by deriving the quadratic formula with step-by-step CAS verification. You'll learn why `mode=solve` is essential for equation-solving derivations and how it detects lost or extraneous solutions. > **Why mode=solve?:** The quadratic formula derivation involves operations that transform **solution sets** rather than just expressions. Dividing both sides by `a` is NOT an algebraic equivalence (the expressions differ by factor `a`), but the equations have the same solutions when `a ≠ 0`. ## Understanding the Difference Let's understand why `mode=chain` fails for equation-solving derivations: | Mode | What It Checks | Use For | | --- | --- | --- | | chain | Algebraic equivalence: `simplify(expr1 - expr2) == 0` | Factoring, expanding, simplifying | | solve | Solution-set equivalence: `solveset(eq1) == solveset(eq2)` | Equation solving, isolating variables | Consider the step "divide both sides by a": - `ax² + bx` and `x² + (b/a)x` are NOT algebraically equivalent - But the equations `ax² + bx = -c` and `x² + (b/a)x = -c/a` have the SAME solution set ## The Derivation ### Step 1: Start with the General Quadratic Equation We begin with the standard form of a quadratic equation where `a ≠ 0`: ```markdown $$ ax^2 + bx + c = 0 $$ where $a \\neq 0$. ``` ### Step 2: Subtract c from Both Sides ```markdown :::cas mode=solve engine=sympy domain=R assumptions="a != 0" solve_var=x $$ ax^2 + bx + c = 0 $$ $$ ax^2 + bx = -c $$ ::: ``` **Expected Result:** ✅ EQUIV (same solution set) ### Step 3: Divide Both Sides by a This is where `mode=solve` shines. This step would FAIL with `mode=chain` because the expressions are NOT algebraically equivalent. ```markdown :::cas mode=solve engine=sympy domain=R assumptions="a != 0" solve_var=x $$ ax^2 + bx = -c $$ $$ x^2 + \\frac{b}{a}x = -\\frac{c}{a} $$ ::: ``` **Expected Result:** ✅ EQUIV (same solution set when a ≠ 0) > **Why mode=chain Would Fail Here:** `mode=chain` checks if `ax² + bx` equals `x² + (b/a)x`. These are NOT equal (they differ by factor `a`). But `mode=solve` checks if the equations have the same solutions, which they do. ### Step 4: Complete the Square Add `(b/2a)²` to both sides: ```markdown :::cas mode=solve engine=sympy domain=R assumptions="a != 0" solve_var=x $$ x^2 + \\frac{b}{a}x = -\\frac{c}{a} $$ $$ x^2 + \\frac{b}{a}x + \\frac{b^2}{4a^2} = \\frac{b^2}{4a^2} - \\frac{c}{a} $$ ::: ``` **Expected Result:** ✅ EQUIV ### Step 5a: Simplify the Right Side Combine the fractions on the right side: ```markdown :::cas mode=solve engine=sympy domain=R assumptions="a != 0" solve_var=x $$ x^2 + \\frac{b}{a}x + \\frac{b^2}{4a^2} = \\frac{b^2}{4a^2} - \\frac{c}{a} $$ $$ x^2 + \\frac{b}{a}x + \\frac{b^2}{4a^2} = \\frac{b^2 - 4ac}{4a^2} $$ ::: ``` **Expected Result:** ✅ EQUIV ### Step 5b: Factor the Left Side as a Perfect Square ```markdown :::cas mode=solve engine=sympy domain=R assumptions="a != 0" solve_var=x $$ x^2 + \\frac{b}{a}x + \\frac{b^2}{4a^2} = \\frac{b^2 - 4ac}{4a^2} $$ $$ \\left(x + \\frac{b}{2a}\\right)^2 = \\frac{b^2 - 4ac}{4a^2} $$ ::: ``` **Expected Result:** ✅ EQUIV ### Step 6: Take the Square Root of Both Sides This is a critical step. We must use ± to capture both solutions: ```markdown :::cas mode=solve engine=sympy domain=R assumptions="a != 0" solve_var=x $$ \\left(x + \\frac{b}{2a}\\right)^2 = \\frac{b^2 - 4ac}{4a^2} $$ $$ x + \\frac{b}{2a} = \\pm \\frac{\\sqrt{b^2 - 4ac}}{2a} $$ ::: ``` **Expected Result:** ✅ EQUIV (the ± captures both solutions) > **What Happens Without ±:** If we wrote `x + b/(2a) = sqrt(b² - 4ac)/(2a)` (without ±), the CAS would return **NARROWS** because we'd lose one solution. ### Step 7: Solve for x ```markdown :::cas mode=solve engine=sympy domain=R assumptions="a != 0" solve_var=x $$ x + \\frac{b}{2a} = \\pm \\frac{\\sqrt{b^2 - 4ac}}{2a} $$ $$ x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} $$ ::: ``` **Expected Result:** ✅ EQUIV — We've derived the quadratic formula! ## Full Derivation Chain Here's the complete derivation verified in one block: ```markdown :::cas mode=solve engine=sympy domain=R assumptions="a != 0" solve_var=x $$ ax^2 + bx + c = 0 $$ $$ ax^2 + bx = -c $$ $$ x^2 + \\frac{b}{a}x = -\\frac{c}{a} $$ $$ x^2 + \\frac{b}{a}x + \\frac{b^2}{4a^2} = \\frac{b^2 - 4ac}{4a^2} $$ $$ \\left(x + \\frac{b}{2a}\\right)^2 = \\frac{b^2 - 4ac}{4a^2} $$ $$ x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} $$ ::: ``` **Expected Result:** ✅ EQUIV for all steps ## Demonstrating NARROWS and WIDENS The `mode=solve` feature can detect when derivation steps lose or introduce solutions. ### Example: NARROWS (Lost Solutions) When we take a square root without ±, we lose solutions: ```markdown :::cas mode=solve engine=sympy domain=R solve_var=x $$ x^2 = 4 $$ $$ x = 2 $$ ::: ``` **Expected Result:** ⚠️ NARROWS — The first equation has solutions {'{-2, 2}'}, but the second only has {'{2}'}. We lost the x = -2 solution. ### Example: WIDENS (Extraneous Solutions) When we square both sides, we can introduce extraneous solutions: ```markdown :::cas mode=solve engine=sympy domain=R solve_var=x $$ x = 2 $$ $$ x^2 = 4 $$ ::: ``` **Expected Result:** ⚠️ WIDENS — The first equation has solution {'{2}'}, but the second has {'{-2, 2}'}. We added the extraneous solution x = -2. ### Example: Correct Use of ± Using ± preserves the solution set: ```markdown :::cas mode=solve engine=sympy domain=R solve_var=x $$ x^2 = 4 $$ $$ x = \\pm 2 $$ ::: ``` **Expected Result:** ✅ EQUIV — Both equations have the same solution set {'{-2, 2}'}. ## Domain Options The `domain` attribute specifies where to look for solutions: | Domain | Description | Example | | --- | --- | --- | | R (default) | Real numbers | x² = 4 → {'{-2, 2}'} | | C | Complex numbers | x² = -1 → {'{i, -i}'} | | Z | Integers | 2x = 4 → {'{2}'} | | N | Natural numbers | x = 2 → {'{2}'} | ### Example: Complex Domain ```markdown :::cas mode=solve engine=sympy domain=C solve_var=x $$ x^2 = -1 $$ $$ x^2 + 1 = 0 $$ ::: ``` **Expected Result:** ✅ EQUIV — Both have solutions {'{i, -i}'} in the complex domain. ## When to Use Each Mode | Scenario | Mode | Reason | | --- | --- | --- | | Verify identity: sin²(x) + cos²(x) = 1 | equivalence | Expression identity | | Factor: x² - 1 = (x-1)(x+1) | chain | Expression rewrite | | Simplify: (x²-1)/(x-1) = x+1 | chain | Algebraic simplification | | Solve: ax² + bx + c = 0 → quadratic formula | solve | Equation derivation | | Isolate variable: 2x + 3 = 7 → x = 2 | solve | Solution-set transformation | ## Status Indicators for mode=solve | Status | Meaning | Example | | --- | --- | --- | | ✅ EQUIV | Same solution set (valid transformation) | 2x = 4 → x = 2 | | ⚠️ NARROWS | Lost solutions (e.g., forgot ± when taking square root) | x² = 4 → x = 2 | | ⚠️ WIDENS | Extraneous solutions (e.g., squared both sides) | x = 2 → x² = 4 | | ❓ UNKNOWN | Cannot determine relationship | Complex expressions | | ❌ ERROR | Parse or solve failed | Invalid LaTeX | ## Multiple Solutions Syntax Use `\pm` or `\text{'{or}'}` to express multiple solutions: ```markdown Using ±: $$ x = \\pm 2 $$ Using "or": $$ x = 2 \\,\\,\\text{or}\\,\\, x = -2 $$ ``` Both are equivalent to the solution set {'{-2, 2}'}. ## Best Practices > **Always Use mode=solve for Equation Derivations:** When your derivation involves dividing both sides, taking roots, or any operation that might change the solution set, use `mode=solve`. > **Include the a ≠ 0 Assumption:** For the quadratic formula derivation, always include `assumptions="a != 0"` since we divide by `a`. > **Use ± When Taking Square Roots:** Always use `\pm` when taking square roots of both sides to preserve all solutions. The CAS will warn you with NARROWS if you forget. > **Specify the Solve Variable:** Use `solve_var=x` to explicitly tell the CAS which variable you're solving for. This helps when you have multiple variables like `a`, `b`, `c`, and `x`. ## Next Steps Now that you understand `mode=solve`, explore more CAS verification examples in the [CAS Verification Demo](/docs/math/verification/cas-demo) , which covers `mode=equivalence` and `mode=chain` for expression verification. --- # Lean 4 Theorem Proving — Formal Proof Verification > Machine-checked mathematical proofs using Lean 4 and Mathlib. Learn how to write and verify formal proofs with induction, case analysis, and powerful tactics. ## Introduction AutEng integrates **Lean 4** with **Mathlib** for formal theorem proving. Unlike CAS verification (which uses heuristic symbolic computation), Lean provides machine-checked proofs—if your proof compiles, it's mathematically correct. Every Lean proof is either **verified** (✅), has **errors** (❌), or is **pending** (🔄). There's no "unknown" state—Lean's type system guarantees correctness. > **When to Use Lean vs CAS:** **CAS (SymPy)**: Quick algebraic identity checks (e.g., sin²x + cos²x = 1) **Lean 4**: Formal proofs requiring induction, case analysis, or Mathlib lemmas ## Quick Start Wrap your Lean code in a `:::lean` block. The system will compile and verify it using Lean 4 + Mathlib. ### Example 1: Simple Theorem ✅ A basic proof using the omega tactic: ```markdown :::lean mode=check engine=lean4 import Mathlib.Tactic theorem add_comm_example (a b : ℕ) : a + b = b + a := by omega ::: ``` **Expected Result:** ✅ Verified — The proof type-checks successfully. ### Example 2: Proof by Induction ✅ A classic result: the sum of the first n odd numbers equals n². This requires induction and the `ring` tactic. ```markdown :::lean mode=check engine=lean4 import Mathlib.Tactic import Mathlib.Algebra.BigOperators.Group.Finset.Basic open Finset BigOperators theorem sum_odd_numbers (n : ℕ) : ∑ i ∈ range n, (2 * i + 1) = n^2 := by induction n with | zero => simp | succ n ih => rw [sum_range_succ, ih] ring ::: ``` **Expected Result:** ✅ Verified — The induction proof is complete. ### Example 3: Incomplete Proof ❌ Using `sorry` marks a proof as incomplete. Lean will report this as an error: ```markdown :::lean mode=check engine=lean4 import Mathlib.Tactic theorem incomplete_example (n : ℕ) : n + 0 = n := by sorry ::: ``` **Expected Result:** ❌ Failed — Declaration uses 'sorry'. ## Common Tactics Lean 4 with Mathlib provides powerful tactics for constructing proofs: | Tactic | Use Case | | --- | --- | | simp | Simplify using simp lemmas (powerful automation) | | ring | Prove ring equalities (polynomial identities) | | omega | Integer/natural number arithmetic | | linarith | Linear arithmetic reasoning | | norm_num | Numeric computations | | rfl | Reflexivity (terms are definitionally equal) | | exact | Provide an exact proof term | | apply | Apply a lemma or hypothesis | | induction | Proof by induction | | cases | Case analysis | ### Example: Using Multiple Tactics ```markdown :::lean mode=check engine=lean4 import Mathlib.Tactic -- Sum of first n natural numbers theorem sum_naturals (n : ℕ) : 2 * (∑ i ∈ Finset.range (n + 1), i) = n * (n + 1) := by induction n with | zero => simp | succ n ih => simp [Finset.sum_range_succ] linarith ::: ``` ## Common Imports Mathlib provides a vast library of mathematical definitions and lemmas. Here are the most commonly used imports: | Import | Provides | | --- | --- | | Mathlib.Tactic | General tactics (simp, ring, omega, linarith, etc.) | | Mathlib.Data.Nat.Basic | Natural number operations | | Mathlib.Data.Real.Basic | Real number operations | | Mathlib.Data.Nat.Prime.Basic | Prime number definitions | | Mathlib.Algebra.BigOperators.Group.Finset.Basic | Finite sums and products (∑, ∏) | > **Import Loading Time:** The first verification request may take 50-60 seconds while Mathlib imports are loaded. Subsequent requests complete in 2-5 seconds as the server keeps imports cached. ## CAS vs Lean: When to Use Each Both CAS and Lean verify mathematical correctness, but they serve different purposes: - ✓ Algebraic identity verification - ✓ Symbolic simplification - ✓ Equation solving steps - ✓ Fast (~1-5 seconds) - ✗ Heuristic (can return UNKNOWN) - ✓ Induction proofs - ✓ Case analysis - ✓ Complex reasoning chains - ✓ Absolute correctness guarantee - ✗ Slower first request (~50-60s cold) ### Example Comparison **Verifying sin²x + cos²x = 1:** ```markdown :::cas mode=equivalence engine=sympy $$ \\sin^2(x) + \\cos^2(x) = 1 $$ ::: ``` **Proving ∑(2i+1) = n² for all n:** ```markdown :::lean mode=check engine=lean4 import Mathlib.Tactic import Mathlib.Algebra.BigOperators.Group.Finset.Basic open Finset BigOperators theorem sum_odd_eq_square (n : ℕ) : ∑ i ∈ range n, (2 * i + 1) = n^2 := by induction n with | zero => simp | succ n ih => rw [sum_range_succ, ih]; ring ::: ``` ## Error Messages When a proof fails, Lean provides detailed error messages with line numbers and suggestions: ### Type Mismatch ```markdown :::lean mode=check engine=lean4 import Mathlib.Tactic -- This will fail: can't prove n = n + 1 theorem wrong_claim (n : ℕ) : n = n + 1 := by rfl ::: ``` **Expected Error:** type mismatch — rfl requires definitionally equal terms. ### Tactic Failed ```markdown :::lean mode=check engine=lean4 import Mathlib.Tactic -- omega can't prove this (it's false!) theorem false_claim (n : ℕ) : n > n := by omega ::: ``` **Expected Error:** omega could not prove the goal. ## Best Practices > **Start with import Mathlib.Tactic:** This single import gives you access to most common tactics (simp, ring, omega, linarith, norm_num, etc.). > **Use simp for Simplification:** The `simp` tactic is incredibly powerful. It can often solve goals automatically or simplify them significantly. > **Break Complex Proofs into Lemmas:** If a proof is getting long, extract intermediate results as separate lemmas. This makes proofs more readable and reusable. > **Use ring for Polynomial Identities:** The `ring` tactic automatically proves any polynomial identity. It's perfect for algebraic manipulations. > **Check the Goal State:** Use `#check` to see types and `example` to test small proofs before incorporating them into larger theorems. ## Reference ### Block Syntax | Attribute | Values | Default | | --- | --- | --- | | mode | check | check | | engine | lean4 | lean4 | | timeout | integer (ms) | 30000 | ### Status Indicators | Status | Meaning | | --- | --- | | ✅ Verified | Proof type-checks successfully | | ❌ Failed | Compilation errors (type mismatch, tactic failed, etc.) | | ⏱️ Timeout | Verification exceeded time limit | | 🔄 Pending | Verification in progress | ### Performance | Scenario | Time | | --- | --- | | First request (cold start) | 50-60 seconds | | Subsequent requests (warm) | 2-5 seconds | | Different imports needed | 50-60 seconds (re-initialization) | ## Next Steps Ready to explore more verification options? Check out these related guides: - [CAS Verification Demo](/docs/math/verification/cas-demo) — Quick algebraic identity checking with SymPy - [Quadratic Formula Derivation](/docs/math/verification/quadratic-formula-derivation) — Step-by-step equation solving with CAS - [KaTeX Syntax Reference](/docs/math/notation/katex-syntax) — Mathematical notation in Markdown --- # Physics Equations and Diagrams — Documenting Scientific Concepts > Complete guide to documenting physics concepts with KaTeX equations, Mermaid diagrams, and scientific notation ## Introduction Physics documentation requires precise mathematical notation, clear diagrams, and structured explanations. Whether you're documenting classical mechanics, electromagnetism, quantum physics, or any other physics domain, combining KaTeX for equations and Mermaid for diagrams creates professional, accessible scientific documentation. This guide demonstrates how to document physics concepts effectively using AutEng's powerful features. You'll learn to write complex equations, create informative diagrams, and structure scientific content that's both rigorous and readable. ### Why Use AutEng for Physics Documentation? - **KaTeX Support:** Write complex equations with LaTeX syntax - **Mermaid Diagrams:** Create flowcharts, state diagrams, and visual explanations - **Real-time Preview:** See equations and diagrams as you write - **Version Control:** Track changes to your scientific documentation - **Collaboration:** Share documentation with colleagues and students ### What You'll Learn - How to write physics equations using KaTeX - Creating diagrams for physical systems and processes - Documenting derivations and proofs - Best practices for scientific notation - Structuring physics documentation effectively ## Classical Mechanics: Newton's Laws Classical mechanics forms the foundation of physics. Let's document Newton's laws with proper equations and diagrams. ### Newton's Second Law The fundamental equation relating force, mass, and acceleration: ```markdown Newton's Second Law states that the force acting on an object is equal to the mass of the object multiplied by its acceleration: $$\\vec{F} = m\\vec{a}$$ Where: - $\\vec{F}$ is the net force vector (in Newtons, N) - $m$ is the mass (in kilograms, kg) - $\\vec{a}$ is the acceleration vector (in m/s²) In component form: $$F_x = ma_x, \\quad F_y = ma_y, \\quad F_z = ma_z$$ ``` ### Kinetic Energy The energy of motion depends on mass and velocity: ```markdown The kinetic energy of an object with mass $m$ moving at velocity $v$ is: $$KE = \\frac{1}{2}mv^2$$ For a system of particles, the total kinetic energy is: $$KE_{total} = \\sum_{i=1}^{n} \\frac{1}{2}m_i v_i^2$$ **Derivation from Work-Energy Theorem:** Starting with $W = \\int F \\, dx$ and $F = ma = m\\frac{dv}{dt}$: $$W = \\int m\\frac{dv}{dt} \\, dx = \\int m\\frac{dx}{dt} \\, dv = \\int mv \\, dv = \\frac{1}{2}mv^2$$ ``` ### Force Diagram Visualizing forces acting on an object using a flowchart-style diagram: ```markdown \`\`\`mermaid graph TD A[Object on Incline] --> B[Weight: mg downward] A --> C[Normal Force: N perpendicular to surface] A --> D[Friction: f parallel to surface] B --> E[Component parallel: mg sin θ] B --> F[Component perpendicular: mg cos θ] style A fill:#e3f2fd style B fill:#ffebee style C fill:#e8f5e9 style D fill:#fff3e0 style E fill:#fce4ec style F fill:#fce4ec \`\`\` **Equations of Motion:** Parallel to incline: $ma = mg\\sin\\theta - f$ Perpendicular to incline: $N = mg\\cos\\theta$ ``` ## Electromagnetism: Maxwell's Equations Maxwell's equations are the foundation of classical electromagnetism. Here's how to document them with proper notation and context. ### The Four Maxwell Equations ```markdown Maxwell's equations describe how electric and magnetic fields are generated and altered by charges and currents: **1. Gauss's Law (Electric):** $$\\nabla \\cdot \\vec{E} = \\frac{\\rho}{\\epsilon_0}$$ Electric field divergence equals charge density divided by permittivity. **2. Gauss's Law (Magnetic):** $$\\nabla \\cdot \\vec{B} = 0$$ No magnetic monopoles exist; magnetic field lines form closed loops. **3. Faraday's Law:** $$\\nabla \\times \\vec{E} = -\\frac{\\partial \\vec{B}}{\\partial t}$$ A changing magnetic field induces an electric field. **4. Ampère-Maxwell Law:** $$\\nabla \\times \\vec{B} = \\mu_0\\vec{J} + \\mu_0\\epsilon_0\\frac{\\partial \\vec{E}}{\\partial t}$$ Magnetic fields are generated by currents and changing electric fields. **Where:** - $\\vec{E}$ = electric field (V/m) - $\\vec{B}$ = magnetic field (T) - $\\rho$ = charge density (C/m³) - $\\vec{J}$ = current density (A/m²) - $\\epsilon_0$ = permittivity of free space - $\\mu_0$ = permeability of free space ``` ### Electromagnetic Wave Equation ```markdown Taking the curl of Faraday's law and substituting Ampère-Maxwell law (in vacuum, $\\rho = 0$, $\\vec{J} = 0$): $$\\nabla \\times (\\nabla \\times \\vec{E}) = -\\frac{\\partial}{\\partial t}(\\nabla \\times \\vec{B})$$ Using the vector identity $\\nabla \\times (\\nabla \\times \\vec{E}) = \\nabla(\\nabla \\cdot \\vec{E}) - \\nabla^2\\vec{E}$ and $\\nabla \\cdot \\vec{E} = 0$: $$-\\nabla^2\\vec{E} = -\\mu_0\\epsilon_0\\frac{\\partial^2 \\vec{E}}{\\partial t^2}$$ This gives the **wave equation**: $$\\nabla^2\\vec{E} = \\mu_0\\epsilon_0\\frac{\\partial^2 \\vec{E}}{\\partial t^2}$$ The wave speed is: $$c = \\frac{1}{\\sqrt{\\mu_0\\epsilon_0}} \\approx 3 \\times 10^8 \\text{ m/s}$$ ``` ### Electromagnetic Wave Propagation ```markdown \`\`\`mermaid graph LR A[EM Wave] --> B[Electric Field E] A --> C[Magnetic Field B] A --> D[Direction of Propagation k] B --> E[Perpendicular to B] C --> F[Perpendicular to E] D --> G[Perpendicular to both E and B] E --> H[E ⊥ B ⊥ k] F --> H G --> H H --> I[Right-hand rule: E × B = k] style A fill:#e3f2fd style B fill:#ffebee style C fill:#e8f5e9 style D fill:#fff3e0 style H fill:#f3e5f5 style I fill:#fce4ec \`\`\` **Key Properties:** - Electric and magnetic fields oscillate perpendicular to each other - Both fields are perpendicular to the direction of propagation - Energy flows in the direction of $\\vec{E} \\times \\vec{B}$ (Poynting vector) ``` ## Quantum Mechanics: Wave Functions and Operators Quantum mechanics requires careful notation for wave functions, operators, and probability amplitudes. ### Schrödinger Equation ```markdown The time-dependent Schrödinger equation describes how quantum states evolve: $$i\\hbar\\frac{\\partial}{\\partial t}\\Psi(\\vec{r}, t) = \\hat{H}\\Psi(\\vec{r}, t)$$ Where: - $\\Psi(\\vec{r}, t)$ is the wave function - $\\hbar = h/2\\pi$ is the reduced Planck constant - $\\hat{H}$ is the Hamiltonian operator **Time-Independent Form:** For stationary states with $\\Psi(\\vec{r}, t) = \\psi(\\vec{r})e^{-iEt/\\hbar}$: $$\\hat{H}\\psi(\\vec{r}) = E\\psi(\\vec{r})$$ **For a Particle in a Potential:** $$-\\frac{\\hbar^2}{2m}\\nabla^2\\psi + V(\\vec{r})\\psi = E\\psi$$ ``` ### Heisenberg Uncertainty Principle ```markdown The uncertainty principle states that certain pairs of physical properties cannot be simultaneously known to arbitrary precision: **Position-Momentum Uncertainty:** $$\\Delta x \\cdot \\Delta p \\geq \\frac{\\hbar}{2}$$ **Energy-Time Uncertainty:** $$\\Delta E \\cdot \\Delta t \\geq \\frac{\\hbar}{2}$$ **General Form for Operators:** For any two observables $\\hat{A}$ and $\\hat{B}$: $$\\Delta A \\cdot \\Delta B \\geq \\frac{1}{2}|\\langle[\\hat{A}, \\hat{B}]\\rangle|$$ Where $[\\hat{A}, \\hat{B}] = \\hat{A}\\hat{B} - \\hat{B}\\hat{A}$ is the commutator. ``` ### Quantum State Evolution ```markdown \`\`\`mermaid stateDiagram-v2 [*] --> Superposition: Prepare state Superposition --> Measurement: Apply measurement operator Measurement --> Eigenstate1: Probability |⟨ψ₁|ψ⟩|² Measurement --> Eigenstate2: Probability |⟨ψ₂|ψ⟩|² Measurement --> Eigenstate3: Probability |⟨ψ₃|ψ⟩|² Eigenstate1 --> [*]: Definite value Eigenstate2 --> [*]: Definite value Eigenstate3 --> [*]: Definite value note right of Superposition |ψ⟩ = c₁|ψ₁⟩ + c₂|ψ₂⟩ + c₃|ψ₃⟩ Σ|cᵢ|² = 1 end note note right of Measurement Wave function collapse Non-deterministic outcome end note \`\`\` **Key Concepts:** - Before measurement: system exists in superposition of states - Measurement causes wave function collapse - Outcome is probabilistic, determined by $|\\langle\\psi_i|\\psi\\rangle|^2$ - After measurement: system is in definite eigenstate ``` ## Thermodynamics: Laws and Processes Thermodynamics deals with heat, work, and energy transfer. Let's document the fundamental laws and key processes. ### The Four Laws ```markdown **Zeroth Law (Thermal Equilibrium):** If systems A and B are each in thermal equilibrium with system C, then A and B are in thermal equilibrium with each other. **First Law (Energy Conservation):** $$\\Delta U = Q - W$$ Where: - $\\Delta U$ = change in internal energy - $Q$ = heat added to system - $W$ = work done by system **Second Law (Entropy):** For any thermodynamic process: $$\\Delta S_{universe} \\geq 0$$ The entropy of an isolated system never decreases. For a reversible process: $$dS = \\frac{dQ_{rev}}{T}$$ **Third Law (Absolute Zero):** As temperature approaches absolute zero, the entropy of a perfect crystal approaches zero: $$\\lim_{T \\to 0} S = 0$$ ``` ### Carnot Cycle ```markdown The Carnot cycle represents the most efficient heat engine possible between two temperature reservoirs. **Efficiency:** $$\\eta = 1 - \\frac{T_C}{T_H} = \\frac{W}{Q_H}$$ Where: - $T_H$ = hot reservoir temperature (K) - $T_C$ = cold reservoir temperature (K) - $W$ = work output - $Q_H$ = heat input from hot reservoir **Carnot Cycle Stages:** \`\`\`mermaid graph TD A[1. Isothermal Expansion] --> B[2. Adiabatic Expansion] B --> C[3. Isothermal Compression] C --> D[4. Adiabatic Compression] D --> A A --> E[T = T_H, absorb Q_H] B --> F[No heat transfer, T drops] C --> G[T = T_C, release Q_C] D --> H[No heat transfer, T rises] style A fill:#ffebee style B fill:#e3f2fd style C fill:#e8f5e9 style D fill:#fff3e0 \`\`\` **Key Insight:** No real engine can exceed Carnot efficiency. ``` ### Ideal Gas Law ```markdown **Ideal Gas Law:** $$PV = nRT$$ Where: - $P$ = pressure (Pa) - $V$ = volume (m³) - $n$ = number of moles - $R$ = universal gas constant (8.314 J/(mol·K)) - $T$ = temperature (K) **Alternative Forms:** Using $n = N/N_A$ where $N$ is number of molecules: $$PV = NkT$$ Where $k = R/N_A$ is Boltzmann's constant. **Internal Energy of Ideal Gas:** For a monatomic ideal gas: $$U = \\frac{3}{2}nRT$$ For a diatomic ideal gas: $$U = \\frac{5}{2}nRT$$ ``` ## Best Practices for Physics Documentation Follow these guidelines to create clear, accurate, and professional physics documentation. ### 1. Use Standard Notation Follow established conventions for symbols and notation: ### 2. Define All Variables Always explain what each symbol represents and include units: ### 3. Show Derivations Step-by-Step Break complex derivations into clear, logical steps: ### 4. Use Diagrams Effectively Complement equations with visual representations: - Use flowcharts for processes and decision trees - Use state diagrams for quantum states and transitions - Label all components clearly - Use consistent color coding - Keep diagrams simple and focused ### 5. Provide Physical Interpretation Don't just present equations—explain what they mean physically. Connect mathematical formalism to real-world phenomena and intuition. ### 6. Include Worked Examples Demonstrate concepts with concrete numerical examples: ### 7. Cite Assumptions and Limits Clearly state when equations apply and when they break down. For example, specify if an equation assumes non-relativistic speeds, ideal conditions, or classical (non-quantum) behavior. ## Common Pitfalls & Solutions ### Pitfall 1: Inconsistent Notation Using the same symbol for different quantities or switching notation mid-document. ### Pitfall 2: Missing Units or Dimensions Forgetting to specify units makes equations ambiguous and error-prone. ### Pitfall 3: Confusing Scalars and Vectors Not distinguishing between scalar and vector quantities leads to confusion. ### Pitfall 4: Overly Complex Diagrams Trying to show too much in one diagram makes it hard to understand. ❌ AVOID: - Cramming multiple concepts into one diagram - Using too many colors or styles - Unlabeled or poorly labeled components - Overly detailed technical drawings ✅ INSTEAD: - Create separate diagrams for different concepts - Use consistent, minimal color schemes - Label everything clearly - Focus on the key idea ### Pitfall 5: Skipping Mathematical Steps Jumping from one equation to another without showing the intermediate steps. ## Advanced Documentation Techniques Take your physics documentation to the next level with these advanced techniques. ### Tensor Notation For advanced topics like general relativity, use proper tensor notation: ### Bra-Ket Notation For quantum mechanics, use Dirac notation consistently: ### Matrix Representations Use matrices for operators and transformations: ### Combining Multiple Representations Show the same concept in different forms for deeper understanding: - Differential form and integral form - Coordinate representation and abstract notation - Time domain and frequency domain - Position space and momentum space ## Conclusion Effective physics documentation combines precise mathematical notation, clear diagrams, and thoughtful explanations. By using KaTeX for equations and Mermaid for diagrams, you can create professional scientific documentation that's both rigorous and accessible. ### Key Takeaways - Use standard notation and define all variables - Show derivations step-by-step with clear explanations - Complement equations with diagrams and visual aids - Provide physical interpretation alongside mathematical formalism - Include worked examples and specify assumptions - Keep diagrams focused and well-labeled - Maintain consistency throughout your documentation ### Next Steps Ready to create your own physics documentation? Start with: - Review the [KaTeX Syntax Guide](/docs/math/notation/katex-syntax) for equation formatting - Explore [Mermaid diagrams](/docs/guides/markdown-syntax) for visual representations - Check out [documentation best practices](/docs/guides/best-practices/documentation-best-practices) - Start documenting your own physics concepts and experiments --- # Electromagnetism — Maxwell's Equations Explained > Master Maxwell's equations with clear explanations, KaTeX notation, and Mermaid diagrams. Learn Gauss's law, Faraday's law, and electromagnetic wave theory. ## Introduction Maxwell's equations are the foundation of classical electromagnetism, describing how electric and magnetic fields are generated and interact. These four elegant equations unify electricity, magnetism, and optics into a single theoretical framework. This guide covers Maxwell's equations in both integral and differential forms, explains their physical meaning, and shows how to document electromagnetic concepts effectively using KaTeX and Mermaid diagrams. > **Prerequisites:** This guide assumes familiarity with vector calculus (gradient, divergence, curl) and basic KaTeX syntax. See our [Calculus in Technical Documentation](/docs/math/calculus/calculus-technical-docs) guide for vector calculus notation. ## Maxwell's Equations Overview Maxwell's equations consist of four fundamental laws that describe all classical electromagnetic phenomena. Here they are in their most common differential form: ```markdown **Maxwell's Equations in Differential Form** **1. Gauss's Law for Electricity** $$ \\nabla \\cdot \\vec{E} = \\frac{\\rho}{\\varepsilon_0} $$ **2. Gauss's Law for Magnetism** $$ \\nabla \\cdot \\vec{B} = 0 $$ **3. Faraday's Law of Induction** $$ \\nabla \\times \\vec{E} = -\\frac{\\partial \\vec{B}}{\\partial t} $$ **4. Ampère-Maxwell Law** $$ \\nabla \\times \\vec{B} = \\mu_0 \\vec{J} + \\mu_0 \\varepsilon_0 \\frac{\\partial \\vec{E}}{\\partial t} $$ ``` ### Key Symbols ```markdown | Symbol | Meaning | SI Unit | |:------:|:--------|:--------| | $\\vec{E}$ | Electric field | V/m | | $\\vec{B}$ | Magnetic field | T (Tesla) | | $\\rho$ | Charge density | C/m³ | | $\\vec{J}$ | Current density | A/m² | | $\\varepsilon_0$ | Permittivity of free space | F/m | | $\\mu_0$ | Permeability of free space | H/m | | $c$ | Speed of light | m/s | **Fundamental constants**: $$ \\varepsilon_0 \\approx 8.854 \\times 10^{-12} \\text{ F/m} $$ $$ \\mu_0 = 4\\pi \\times 10^{-7} \\text{ H/m} $$ $$ c = \\frac{1}{\\sqrt{\\mu_0 \\varepsilon_0}} \\approx 3 \\times 10^8 \\text{ m/s} $$ ``` ## Gauss's Law for Electricity Gauss's law relates the electric field to the charge distribution that creates it. It states that the electric flux through any closed surface is proportional to the enclosed charge. ```markdown **Differential Form**: $$ \\nabla \\cdot \\vec{E} = \\frac{\\rho}{\\varepsilon_0} $$ **Integral Form**: $$ \\oint_S \\vec{E} \\cdot d\\vec{A} = \\frac{Q_{\\text{enc}}}{\\varepsilon_0} $$ **Physical Meaning**: Electric field lines originate from positive charges and terminate on negative charges. The divergence of $\\vec{E}$ is non-zero only where charges exist. **Example - Point Charge**: For a point charge $q$ at the origin: $$ \\vec{E} = \\frac{q}{4\\pi\\varepsilon_0 r^2} \\hat{r} $$ Using a spherical Gaussian surface of radius $r$: $$ \\oint_S \\vec{E} \\cdot d\\vec{A} = E \\cdot 4\\pi r^2 = \\frac{q}{\\varepsilon_0} $$ ``` ```markdown \`\`\`mermaid flowchart TB subgraph "Electric Field from Point Charge" Q(("+q")) Q --> E1["→"] Q --> E2["↗"] Q --> E3["↑"] Q --> E4["↖"] Q --> E5["←"] Q --> E6["↙"] Q --> E7["↓"] Q --> E8["↘"] end style Q fill:#f59e0b,stroke:#d97706,color:#fff \`\`\` ``` ## Gauss's Law for Magnetism Gauss's law for magnetism states that there are no magnetic monopoles—magnetic field lines always form closed loops. The net magnetic flux through any closed surface is zero. ```markdown **Differential Form**: $$ \\nabla \\cdot \\vec{B} = 0 $$ **Integral Form**: $$ \\oint_S \\vec{B} \\cdot d\\vec{A} = 0 $$ **Physical Meaning**: Unlike electric field lines, magnetic field lines have no beginning or end. They always form closed loops. There are no isolated magnetic "charges" (monopoles). **Consequence**: If you cut a bar magnet in half, you get two smaller magnets, each with both a north and south pole—never an isolated pole. **Mathematical Implication**: $$ \\vec{B} = \\nabla \\times \\vec{A} $$ where $\\vec{A}$ is the magnetic vector potential. Since the divergence of a curl is always zero: $$ \\nabla \\cdot (\\nabla \\times \\vec{A}) = 0 $$ ``` ## Faraday's Law of Induction Faraday's law describes how a changing magnetic field creates an electric field. This is the principle behind electric generators, transformers, and inductors. ```markdown **Differential Form**: $$ \\nabla \\times \\vec{E} = -\\frac{\\partial \\vec{B}}{\\partial t} $$ **Integral Form**: $$ \\oint_C \\vec{E} \\cdot d\\vec{l} = -\\frac{d\\Phi_B}{dt} $$ where the magnetic flux is: $$ \\Phi_B = \\int_S \\vec{B} \\cdot d\\vec{A} $$ **Physical Meaning**: A time-varying magnetic field induces a circulating electric field. The negative sign (Lenz's law) indicates the induced field opposes the change in flux. **EMF in a Loop**: $$ \\mathcal{E} = -\\frac{d\\Phi_B}{dt} = -\\frac{d}{dt}\\int_S \\vec{B} \\cdot d\\vec{A} $$ **Example - Rotating Loop**: For a loop of area $A$ rotating with angular velocity $\\omega$ in a uniform field $B$: $$ \\Phi_B = BA\\cos(\\omega t) $$ $$ \\mathcal{E} = BA\\omega\\sin(\\omega t) $$ ``` ## Ampère-Maxwell Law The Ampère-Maxwell law describes how magnetic fields are generated by electric currents and changing electric fields. Maxwell's crucial addition of the displacement current term completed the equations and predicted electromagnetic waves. ```markdown **Differential Form**: $$ \\nabla \\times \\vec{B} = \\mu_0 \\vec{J} + \\mu_0 \\varepsilon_0 \\frac{\\partial \\vec{E}}{\\partial t} $$ **Integral Form**: $$ \\oint_C \\vec{B} \\cdot d\\vec{l} = \\mu_0 I_{\\text{enc}} + \\mu_0 \\varepsilon_0 \\frac{d\\Phi_E}{dt} $$ **Two Source Terms**: 1. **Conduction current**: $\\mu_0 \\vec{J}$ — moving charges create magnetic fields 2. **Displacement current**: $\\mu_0 \\varepsilon_0 \\frac{\\partial \\vec{E}}{\\partial t}$ — changing electric fields create magnetic fields **Physical Meaning**: Magnetic field lines circulate around both electric currents and regions where the electric field is changing. **Example - Long Straight Wire**: For current $I$ in a long wire: $$ \\oint_C \\vec{B} \\cdot d\\vec{l} = B \\cdot 2\\pi r = \\mu_0 I $$ $$ B = \\frac{\\mu_0 I}{2\\pi r} $$ ``` > **Maxwell's Key Insight:** Maxwell added the displacement current term $\varepsilon_0 \frac{'{\\partial \\vec{E}}{\\partial t}'}$, which was not in Ampère's original law. This term ensures charge conservation and, crucially, predicts that changing electric fields produce magnetic fields—enabling electromagnetic waves to propagate through empty space. ## Electromagnetic Waves Maxwell's equations predict the existence of electromagnetic waves—self-propagating oscillations of electric and magnetic fields. This was one of the greatest theoretical predictions in physics. ```markdown **In Free Space** (no charges or currents): $$ \\nabla \\cdot \\vec{E} = 0, \\quad \\nabla \\cdot \\vec{B} = 0 $$ $$ \\nabla \\times \\vec{E} = -\\frac{\\partial \\vec{B}}{\\partial t}, \\quad \\nabla \\times \\vec{B} = \\mu_0 \\varepsilon_0 \\frac{\\partial \\vec{E}}{\\partial t} $$ **Derivation**: Take the curl of Faraday's law: $$ \\nabla \\times (\\nabla \\times \\vec{E}) = -\\frac{\\partial}{\\partial t}(\\nabla \\times \\vec{B}) $$ Using the vector identity $\\nabla \\times (\\nabla \\times \\vec{E}) = \\nabla(\\nabla \\cdot \\vec{E}) - \\nabla^2 \\vec{E}$: $$ -\\nabla^2 \\vec{E} = -\\mu_0 \\varepsilon_0 \\frac{\\partial^2 \\vec{E}}{\\partial t^2} $$ **Wave Equation**: $$ \\nabla^2 \\vec{E} = \\mu_0 \\varepsilon_0 \\frac{\\partial^2 \\vec{E}}{\\partial t^2} $$ **Wave Speed**: $$ c = \\frac{1}{\\sqrt{\\mu_0 \\varepsilon_0}} = 299,792,458 \\text{ m/s} $$ ``` ```markdown **Plane Wave Solution**: For a wave propagating in the $z$-direction: $$ \\vec{E} = E_0 \\cos(kz - \\omega t) \\hat{x} $$ $$ \\vec{B} = B_0 \\cos(kz - \\omega t) \\hat{y} $$ **Wave Parameters**: - Wave number: $k = \\frac{2\\pi}{\\lambda}$ - Angular frequency: $\\omega = 2\\pi f$ - Phase velocity: $c = \\frac{\\omega}{k} = f\\lambda$ **Field Relationship**: $$ \\frac{E_0}{B_0} = c $$ **Energy Density**: $$ u = \\frac{1}{2}\\varepsilon_0 E^2 + \\frac{1}{2\\mu_0}B^2 = \\varepsilon_0 E^2 $$ **Poynting Vector** (energy flux): $$ \\vec{S} = \\frac{1}{\\mu_0}\\vec{E} \\times \\vec{B} $$ **Intensity**: $$ I = \\langle S \\rangle = \\frac{1}{2}c\\varepsilon_0 E_0^2 $$ ``` ## Integral vs Differential Forms Maxwell's equations can be written in either integral or differential form. Each has its advantages depending on the problem at hand. ```markdown **Gauss's Law (Electricity)**: | Integral | Differential | |:---------|:-------------| | $\\displaystyle\\oint_S \\vec{E} \\cdot d\\vec{A} = \\frac{Q_{\\text{enc}}}{\\varepsilon_0}$ | $\\nabla \\cdot \\vec{E} = \\frac{\\rho}{\\varepsilon_0}$ | **Gauss's Law (Magnetism)**: | Integral | Differential | |:---------|:-------------| | $\\displaystyle\\oint_S \\vec{B} \\cdot d\\vec{A} = 0$ | $\\nabla \\cdot \\vec{B} = 0$ | **Faraday's Law**: | Integral | Differential | |:---------|:-------------| | $\\displaystyle\\oint_C \\vec{E} \\cdot d\\vec{l} = -\\frac{d\\Phi_B}{dt}$ | $\\nabla \\times \\vec{E} = -\\frac{\\partial \\vec{B}}{\\partial t}$ | **Ampère-Maxwell Law**: | Integral | Differential | |:---------|:-------------| | $\\displaystyle\\oint_C \\vec{B} \\cdot d\\vec{l} = \\mu_0 I + \\mu_0\\varepsilon_0\\frac{d\\Phi_E}{dt}$ | $\\nabla \\times \\vec{B} = \\mu_0 \\vec{J} + \\mu_0\\varepsilon_0\\frac{\\partial \\vec{E}}{\\partial t}$ | ``` > **When to Use Each Form:** **Integral form**: Best for problems with high symmetry (spherical, cylindrical, planar) where you can choose a convenient Gaussian surface or Amperian loop. **Differential form**: Best for deriving wave equations, understanding local field behavior, and computational electromagnetics. ## Maxwell's Equations in Matter In materials, we introduce auxiliary fields to account for the response of matter to electromagnetic fields. ```markdown **Auxiliary Fields**: Electric displacement: $\\vec{D} = \\varepsilon_0 \\vec{E} + \\vec{P} = \\varepsilon \\vec{E}$ Magnetic field intensity: $\\vec{H} = \\frac{\\vec{B}}{\\mu_0} - \\vec{M} = \\frac{\\vec{B}}{\\mu}$ **Maxwell's Equations in Matter**: $$ \\nabla \\cdot \\vec{D} = \\rho_f $$ $$ \\nabla \\cdot \\vec{B} = 0 $$ $$ \\nabla \\times \\vec{E} = -\\frac{\\partial \\vec{B}}{\\partial t} $$ $$ \\nabla \\times \\vec{H} = \\vec{J}_f + \\frac{\\partial \\vec{D}}{\\partial t} $$ **Constitutive Relations** (linear media): $$ \\vec{D} = \\varepsilon \\vec{E}, \\quad \\vec{B} = \\mu \\vec{H} $$ where $\\varepsilon = \\varepsilon_0 \\varepsilon_r$ and $\\mu = \\mu_0 \\mu_r$ ``` ## Applications Maxwell's equations have countless applications in technology and science. Here are some key examples with their governing equations. ```markdown **Capacitor**: Electric field between parallel plates: $$ E = \\frac{\\sigma}{\\varepsilon_0} = \\frac{V}{d} $$ Capacitance: $$ C = \\frac{\\varepsilon_0 A}{d} $$ --- **Inductor**: Magnetic field in a solenoid: $$ B = \\mu_0 n I $$ Inductance: $$ L = \\mu_0 n^2 V $$ --- **Transformer**: Voltage ratio: $$ \\frac{V_s}{V_p} = \\frac{N_s}{N_p} $$ --- **Antenna Radiation**: Radiated power: $$ P = \\frac{\\mu_0 c}{12\\pi}\\left(\\frac{I_0 \\ell \\omega}{c}\\right)^2 $$ --- **Waveguide**: Cutoff frequency: $$ f_c = \\frac{c}{2a} $$ ``` ## Best Practices > **Use Vector Notation Consistently:** Always use arrows ($\vec{'{E}'}$) or bold ($\mathbf{'{E}'}$) for vector quantities. Be consistent throughout your documentation. > **Include Units:** Electromagnetic quantities have specific SI units. Include them in definitions and final answers: `$E = 100 \text{'{ V/m}'}$` > **Show Both Forms When Appropriate:** For educational content, showing both integral and differential forms helps readers understand the connection between local and global behavior. > **Use Diagrams for Field Visualization:** Electromagnetic fields are inherently spatial. Use Mermaid diagrams to show field line patterns, wave propagation, and circuit configurations. > **Define Your Coordinate System:** Specify whether you're using Cartesian, cylindrical, or spherical coordinates, especially for problems with specific symmetry. ## Common Mistakes > **Confusing E and D, B and H:** $\vec{'{E}'}$ and $\vec{'{D}'}$ are different fields, as are $\vec{'{B}'}$ and $\vec{'{H}'}$. In vacuum they differ only by constants, but in matter they have different physical meanings. > **Forgetting the Displacement Current:** The term $\varepsilon_0 \frac{'{\\partial \\vec{E}}{\\partial t}'}$ in Ampère's law is essential for wave propagation and charge conservation. Don't omit it. > **Sign Errors in Faraday's Law:** The negative sign in Faraday's law (Lenz's law) is crucial—it determines the direction of induced currents. Always include it. > **Mixing Gaussian and SI Units:** Electromagnetic equations look different in Gaussian (CGS) and SI units. Stick to one system consistently. This guide uses SI units. > **Incorrect Surface/Path Orientation:** In integral forms, the surface normal and path direction must follow the right-hand rule. Incorrect orientation leads to sign errors. ## Quick Reference | Law | Differential Form | Physical Meaning | | --- | --- | --- | | Gauss (E) | $\nabla \cdot \vec{'{E}'} = \rho/\varepsilon_0$ | Charges create E fields | | Gauss (B) | $\nabla \cdot \vec{'{B}'} = 0$ | No magnetic monopoles | | Faraday | $\nabla \times \vec{'{E}'} = -\partial\vec{'{B}'}/\partial t$ | Changing B creates E | | Ampère-Maxwell | $\nabla \times \vec{'{B}'} = \mu_0\vec{'{J}'} + \mu_0\varepsilon_0\partial\vec{'{E}'}/\partial t$ | Currents and changing E create B | ### Key Formulas | Quantity | Formula | | --- | --- | | Speed of light | $c = 1/\sqrt{'{\\mu_0\\varepsilon_0}'}$ | | Wave equation | $\nabla^2\vec{'{E}'} = \mu_0\varepsilon_0 \partial^2\vec{'{E}'}/\partial t^2$ | | Poynting vector | $\vec{'{S}'} = \vec{'{E}'} \times \vec{'{B}'}/\mu_0$ | | Energy density | $u = \varepsilon_0 E^2/2 + B^2/(2\mu_0)$ |