text
stringlengths
313
1.33M
# Tcl Programming/expr ### Overview Arithmetic and logical operations (plus some string comparisons) are in Tcl concentrated in the **expr** command. It takes one or more arguments, evaluates them as an expression, and returns the result. The language of the **expr** command (also used in condition arguments of the **if**, **for**, **while** commands) is basically equivalent to C\'s expressions, with infix operators and functions. Unlike C, references to variables have to be done with *\$var*. Examples: `set a [expr {($b + sin($c))/2.}]`\ `if {$a > $b && $b > $c} {puts "ordered"}`\ `for {set i 10} {$i >= 0} {incr i -1} {puts $i...} ;# countdown` The difference between Tcl syntax and *expr* syntax can be contrasted like this: `[f $x $y]  ;# Tcl:  embedded command`\ ` f($x,$y)  ;# expr: function call, comma between arguments` In another contrast to Tcl syntax, whitespace between \"words\" is optional (but still recommended for better readability :) And string constants must always be quoted (or braced if you wish): `if {$keyword eq "foo"} ...` Then again, Tcl commands can always be embedded into expressions, in square brackets as usual: `proc max {x y} {expr {$x>$y? $x: $y}}`\ `expr {[max $a $b] + [max $c $d]}` In expressions with numbers of mixed types, integers are coerced to doubles: `% expr 1+2.`\ `3.0` It is important to know that division of two integers is done as integer division: `% expr 1/2`\ `0` You get the (probably expected) floating-point division if at least one operand is *double*: `% expr 1/2.`\ `0.5` If you want to evaluate a string input by the user, but always use floating-point division, just transform it, before the call to expr, by replacing \"/\" with \"\*1./\" (multiply with floating-point 1. before every division): `expr [string map {/ *1./} $input]` ### Brace your expressions In most cases it is safer and more efficient to pass a single braced argument to *expr*. Exceptions are: - no variables or embedded commands to substitute - operators or whole expressions to substitute The reason is that the Tcl parser parses unbraced expressions, while expr parses that result again. This may result in success for malicious code exploits: `% set e {[file delete -force *]}`\ `% expr $e   ;# will delete all files and directories`\ `% expr {$e} ;# will just return the string value of e` That braced expressions evaluate much faster than unbraced ones, can be easily tested: `% proc unbraced x {expr  $x*$x}`\ `% proc braced x   {expr {$x*$x}}`\ `% time {unbraced 42} 1000`\ `197 microseconds per iteration`\ `% time {braced 42} 1000`\ `34 microseconds per iteration` The precision of the string representation of floating-point numbers is also controlled by the tcl_precision variable. The following example returns nonzero because the second term was clipped to 12 digits in making the string representation: `% expr 1./3-[expr 1./3]`\ `3.33288951992e-013` while this braced expression works more like expected: `% expr {1./3-[expr 1./3]}`\ `0.0` ### Operators Arithmetic, bitwise and logical operators are like in C, as is the conditional operator found in other languages (notably C): - c?a:b \-- if c is true, evaluate a, else b The conditional operator can be used for compact functional code (note that the following example requires Tcl 8.5 so that fac() can be called inside its own definition): `% proc tcl::mathfunc::fac x {expr {$x<2? 1 : $x*fac($x-1)}}`\ `% expr fac(5)`\ `120` #### Arithmetic operators The arithmetic operators are also like those found in C: - \+ addition - \- (binary: subtraction. unary: change sign) - \* multiplication - / (integer division if both operands are integer - \% (modulo, only on integers) - \*\* power (available from Tcl 8.5) #### Bitwise operators The following operators work on integers only: - & (AND) - \| (OR) - \^ (XOR) - \~ (NOT) - \<\< shift left - \>\> shift right #### Logical operators The following operators take integers (where 0 is considered false, everything else true) and return a truth value, 0 or 1: - && (and) - \|\| (or) - ! (not - unary) #### Comparison operators If operands on both side are numeric, these operators compare them as numbers. Otherwise, string comparison is done. They return a truth value, 0 (false) or 1 (true): - == equal - != not equal - \> greater than - \>= greater or equal than - \< less than - \<= less or equal than As truth values are integers, you can use them as such for further computing, as the sign function demonstrates: `proc sgn x {expr {($x>0) - ($x<0)}}`\ `% sgn 42`\ `1`\ `% sgn -42`\ `-1`\ `% sgn 0`\ `0` #### String operators The following operators work on the string representation of their operands: - eq string-equal - ne not string-equal Examples how \"equal\" and \"string equal\" differ: `% expr {1 == 1.0}`\ `1`\ `% expr {1 eq 1.0}`\ `0` #### List operators From Tcl 8.5, the following operators are also available: - a **in** b - 1 if a is a member of list b, else 0 - a **ni** b - 1 if a is not a member of list b, else 0 Before 8.5, it\'s easy to write an equivalent function `proc in {list el} {expr {[lsearch -exact $list $el]>=0}}` Usage example: `if [in $keys $key] ...` which you can rewrite, once 8.5 is available wherever your work is to run, with `if {$key in $keys} ...` ### Functions The following functions are built-in: - abs(x) - absolute value - acos(x) - arc cosine. acos(-1) = 3.14159265359 (Pi) - asin(x) - arc sine - atan(x) - arc tangent - atan2(y,x) - ceil(x) - next-highest integral value - cos(x) - cosine - cosh(x) - hyperbolic cosine - double(x) - convert to floating-point number - exp(x) - e to the x-th power. exp(1) = 2.71828182846 (Euler number, e) - floor(x) - next-lower integral value - fmod(x,y) - floating-point modulo - hypot(y,x) - hypotenuse (sqrt(\$y\*\$y+\$x\*\$x), but at higher precision) - int(x) - convert to integer (32-bit) - log(x) - logarithm to base e - log10(x) - logarithm to base 10 - pow(x,y) - x to the y-th power - rand() - random number \> 0.0 and \< 1.0 - round(x) - round a number to nearest integral value - sin(x) - sine - sinh(x) - hyperbolic sine - sqrt(x) - square root - srand(x) - initialize random number generation with seed x - tan(x) - tangent - tanh(x) - hyperbolic tangent - wide(x) - convert to wide (64-bit) integer Find out which functions are available with *info functions*: `% info functions`\ `round wide sqrt sin double log10 atan hypot rand abs acos atan2 srand`\ `sinh floor log int tanh tan asin ceil cos cosh exp pow fmod` ### Exporting expr functionalities If you don\'t want to write expr {\$x+5} every time you need a little calculation, you can easily export operators as Tcl commands: `foreach op {+ - * / %} {proc $op {a b} "expr {\$a $op \$b}"}` After that, you can call these operators like in LISP: `% + 6 7`\ `13`\ `% * 6 7`\ `42` Of course, one can refine this by allowing variable arguments at least for + and \*, or the single-argument case for -: `proc - {a {b ""}} {expr {$b eq ""? -$a: $a-$b}}` Similarly, expr functions can be exposed: `foreach f {sin cos tan sqrt} {proc $f x "expr {$f($x)}"}` In Tcl 8.5, the operators can be called as commands in the *::tcl::mathop* namespace: `% tcl::mathop::+ 6 7`\ `13` You can import them into the current namespace, for shorthand math commands: `% namespace import ::tcl::mathop::*`\ `% + 3 4 ;# way shorter than [expr {3 + 4}]`\ `7`\ `% * 6 7`\ `42` ### User-defined functions From Tcl 8.5, you can provide procs in the *::tcl::mathfunc* namespace, which can then be used inside *expr* expressions: `% proc tcl::mathfunc::fac x {expr {$x < 2? 1: $x * fac($x-1)}}`\ `% expr fac(100)`\ `93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000` This is especially useful for recursive functions, or functions whose arguments need some expr calculations: `% proc ::tcl::mathfunc::fib n {expr {$n<2? 1: fib($n-2)+fib($n-1)}} `\ `% expr fib(6)`\ `13`
# Tcl Programming/Internationalization \"Everything is a string\", the Tcl mantra goes. A string is a (finite-length) sequence of characters. Now, what is a character? A character is not the same as a glyph, the writing element that we see on screen or paper - that represents it, but the same glyph can stand for different characters, or the same character be represented with different glyphs (think e.g. of a font selector). Also, a character is not the same as a byte, or sequence of bytes, in memory. That again may represent a character, but not unequivocally, once we leave the safe haven of ASCII. Let\'s try the following working definition: \"A character is the abstract concept of a small writing unit\". This often amounts to a letter, digit, or punctuation sign - but a character can be more or less than that. More: Ligatures, groups of two or more letters, can at times be treated as one character (arranged even in more than one line, as seen in Japanese U+337F ㍿ or Arabic U+FDFA ﷺ). Less: little marks (diacritics) added to a character, like the two dots on ü in Nürnberg (U+00FC), can turn that into a new \"precomposed\" character, as in German; or they may be treated as a separate, \"composing character\" (U+0308 in the example) which in rendering is added to the preceding glyph (u, U+0075) without advancing the rendering position - a more sensible treatment of the function of these two dots, \"trema\", in Spanish, Dutch, or even (older) English orthography: consider the spelling \"coöperation\" in use before c. 1950. Such composition is the software equivalent of \"dead keys\" on a typewriter. Although an abstract concept, a character may of course have attributes, most importantly a name: a string, of course, which describes its function, usage, pronunciation etc. Various sets of names have been formalized in Postscript (/oumlaut) or HTML (&ouml;). Very important in technical applications is of course the assignment of a number (typically a non-negative integer) to identify a character - this is the essence of encodings, where the numbers are more formally called code points. Other attributes may be predicates like \"is upper\", \"is lower\", \"is digit\". The relations between the three domains are not too complicated: an encoding controls how a 1..n sequence of bytes is interpreted as a character, or vice versa; the act of rendering turns an abstract character into a glyph (typically by a pixel or vector pattern). Conversely, making sense of a set of pixels to correctly represent a sequence of characters, is the much more difficult art of OCR, which will not be covered here. ### Pre-Unicode encodings Work on encodings, mapping characters to numbers (code points), has a longer history than electronic computing. Francis Bacon (1561-1626) is reported to have used, around 1580, a five-bit encoding where bits were represented as \"a\" or \"b\", of the English/Latin alphabet (without the letters j and u!), long before Leibniz discussed binary arithmetics in 1679. An early encoding in practical use was the 5-bit Baudot/CCIT-2 teletype (punch tape) code standardized in 1932, which could represent digits and some punctuations by switching between two modes. I have worked on Univac machines that used six bits per \"Fieldata\" character, as hardware words were 36 bits long. While IBM used 8 bits in the EBCDIC code, the more famous American Standard Code for Information Interchange (ASCII) did basically the same job in 7 bits per character, which was sufficient for upper/lowercase basic Latin (English) as well as digits and a number of punctuations and other \"special\" characters - as hardware tended to 8-bit bytes as smallest memory unit, one was left for parity checks or other purposes. The most important purpose, outside the US, was of course to accommodate more letters required to represent the national writing system - Greek, Russian, or the mixed set of accented or \"umlauted\" characters used in virtually every country in Europe. Even England needed a code point for the Pound Sterling sign. The general solution was to use the 128 additional positions available when ASCII was implemented as 8-bit bytes, hex 80..FF. A whole flock of such encodings were defined and used: - ISO standard encodings iso8859-.. (1-15) - MS/DOS code pages cp\... - Macintosh code pages mac\... - Windows code pages cp1\... ### East Asian encodings The East Asian countries China, Japan, and Korea all use character sets numbering in the thousands, so the \"high ASCII\" approach was not feasible there. Instead, the ASCII concept was extended to a 2x7 bit pattern, where the 94 printing ASCII characters indicate row and column in a 94x94 matrix. This way, all character codes were in practice two bytes wide, and thousands of Hanzi/Kanji/Hangul could be accommodated, plus hundreds of others (ASCII, Greek, Russian alphabets, many graphic characters). These national multibyte encodings are: - JIS C-6226 (Japan, 1978; significantly revised 1983, 1990) - GB 2312-80 (Mainland China, 1980) - KS C-5601 (South Korea, 1987) If the 2x7 pattern was directly implemented, files in such encodings could not be told apart from ASCII files, except for unreadability. However, it does get some use in Japanese e-mails (in prevailing conventions developed prior to 8-bit-clean mail servers), with ANSI escape codes using the ESC control character being used to declare sections of text as ASCII or JIS C-6226, in what has become known as \"JIS encoding\" (or more properly as ISO-2022-JP). Elsewhere, in order to handle both types of strings transparently in a more practical manner, the \"high ASCII\" approach was extended so that a byte in 00..7F was taken at ASCII face value, while bytes with high bit set (80..FF) were interpreted as halves of multibyte codes. For instance, the first Chinese character in GB2312, row 16 col 1 (decimally 1601 for short), gives the two bytes `16 + 32 + 128 = 176 = 0xB0`\ ` 1 + 32 + 128 = 161 = 0xA1` This implementation became known as \"Extended UNIX Code\" (EUC) in the national flavors euc-cn (China), -jp (Japan), -kr (Korea). To add to the \"ideograph soup\" confusion, unlike euc-cn and euc-kr, euc-jp (Japan) was not widely adopted on the Windows or Macintosh platforms, which instead tend to use the incompatible ShiftJIS, which re-arranges the codes to make space for older single-byte codes for phonetic katakana characters. Also, Taiwan and Hong Kong use their own \"Big 5\" encoding, which doesn\'t use the 94×94 structure. Unlike EUC encodings, ASCII bytes can appear as the second byte of two-byte codes in these encodings, which is also true of common extensions to the EUC encodings (GBK extending euc-cn, Unified Hangul Code extending euc-kr). ### Unicode as pivot for all other encodings The Unicode standard is an attempt to unify all modern character encodings into one consistent 16-bit representation. Consider a page with a 16x16 table filled with EuroLatin-1 (ISO 8859-1), the lower half being the ASCII code points. Call that \"page 00\" and imagine a book of 256 or more such pages (with all kinds of other characters on them, in majority CJK), then you have a pretty clear concept of the Unicode standard, in which a character\'s code position is \"U+\" hex (page number\*256+cell number), for instance, U+20A4 is a version of the Pound Sterling sign. Initiated by the computer industry (www.unicode.org), the Unicode has grown together with ISO 10646, a parallel standard providing an up-to-31-bits encoding (one left for parity?) with the same scope. Software must allow Unicode strings to be fit for i18n. From Unicode version 3.1, the 16-bit limit was transcended for some rare writing systems, but also for the CJK Unified Ideographs Extension B - apparently, even 65536 code positions are not enough. The total count in Unicode 3.1 is 94,140 encoded characters, of which 70,207 are unified Han ideographs; the next biggest group are over 14000 Korean Hangul. And the number is growing. ### Unicode implementations: UTF-8, UCS-2/UTF-16 UTF-8 is made to cover 7-bit ASCII, Unicode, and ISO 10646. Characters are represented as sequences of 1..6 eight-bit bytes - termed octets in the character set business - (for ASCII: 1, for Unicode: 2..4) as follows: - ASCII 0x00..0x7F (Unicode page 0, left half): 0x00..0x7F. Nothing changed. - Unicode, pages 00..07: 2 bytes, `110aaabb 10bbbbbb`, where aaa are the rightmost bits of page#, bb.. are the bits of the second Unicode byte. These pages cover European/Extended Latin, Greek, Cyrillic, Armenian, Hebrew, Arabic. - Unicode, pages 08..FE: 3 bytes, `1110aaaa 10aaaabb 10bbbbbb`. These cover the rest of the Basic Multilingual Plane, including Hangul, Kanji, and what else. This means that East Asian texts are 50% longer in UTF-8 than in pure 16 bit Unicode. - Unicode, supplementary planes: 4 bytes, `11110ppp 10ppaaaa 10aaaabb 10bbbbbb`. These were not part of the original design of Unicode (only ISO 10646), but they were added to the Unicode standard when it became clear that one plane would not be sufficient for Unicode\'s goals. They mostly cover Emoji, ancient writing systems, niche writing systems, enormous numbers of obscure Kanji/Hanzi, and a few very new writing systems which postdate the original design of Unicode. - ISO 10646 codes beyond Unicode: 4..6 bytes. Since the current approval process keeps the standards in sync by preventing ISO 10646 being allocated beyond the 17 Unicode planes, these are guaranteed not to exist in the foreseeable future. The general principle of UTF-8 is that the first byte either is a single-byte character (if below 0x80), or indicates the length of a multi-byte code by the number of 1\'s before the first 0, and is then filled up with data bits. All other bytes start with bits 10 and are then filled up with 6 data bits. It follows from this that bytes in UTF-8 encoding fall in distinct ranges: `  00..7F - plain ASCII`\ `  80..BF - non-initial bytes of multibyte code`\ `  C2..FD - initial bytes of multibyte code (C0, C1 are not legal!)`\ `  FE, FF - never used, so can be used to detect a UTF-16 byte-order mark (and thus, a non-UTF-8 file).` The distinction between initial and non-initial helps in plausibility checks, or to re-synchronize with missing data. Besides, it\'s independent of byte order (as opposed to UCS-16, see below). Tcl however shields these UTF-8 details from us: characters are just characters, no matter whether 7 bit, 16 bit, or (in the future) more. The byte sequence EF BB BF is the UTF-8 equivalent of \\uFEFF, which is detected by Windows Notepad, which switches to the UTF-8 encoding when a file starts with these three bytes, and writes them when saving a file as UTF-8. This isn\'t always used elsewhere, but will generally override an otherwise declared character encoding if a file starts with it. The UCS-2 representation (in Tcl just called the \"unicode\" encoding) is much more easily explained: each character code is written as a 16-bit \"short\" unsigned integer. The practical complication is that the two memory bytes making up a \"short\" can be arranged in \"big-endian\" (Motorola, Sparc) or \"little-endian\" (Intel) byte order. Hence, the following rules were defined for Unicode: - Code point U+FEFF was defined as Byte Order Mark (BOM), later renamed to \"Zero-width non-breaking space\", although actually using it in its secondary whitespace role is now considered obsolete. - Code point U+FFFE (as well as FFFF) is a guaranteed non-character, and will never be a valid Unicode character. They are intended for use as sentinels, or for other internal use, as well as for detecting if the Byte Order Mark is being read incorrectly. This way, a Unicode-reading application (even Notepad/W2k) can easily detect that something\'s wrong when it encounters the byte sequence FFFE, and swap the following byte pairs - a minimal and elegant way of dealing with varying byte orders. While Unicode was originally intended to fit entirely within UCS-2, with the entirety of ISO 10646 requiring a 32-bit \"long\" (so-called UCS-4 or UTF-32), this distinction was later scrapped since one sixteen-bit plane was no longer considered sufficient to achieve Unicode\'s goal. Therefore, sixteen \"supplementary\" planes were added to Unicode, with the original 16-bit plane being kept as the \"Plane 0\" or \"Basic Multilingual Plane\". In order to use characters from supplementary planes in interfaces expecting a UCS-2 stream, the range U+D800--U+DFFF was guaranteed never to be used for Unicode characters. This allows characters in supplementary planes to be unambiguously represented in an otherwise UCS-2 stream, this is known as UTF-16. A supplementary character is represented in big-endian UTF-16 as follows, where `ssss` represents one less than the plane number. In little-endian, the first two bytes are swapped and the last two bytes are swapped, the entire sequence isn\'t reversed. This because it is treated like a sequence of two UCS-2 characters. `  110110ss ssaaaaaa 110111aa bbbbbbbb` For XML, an encoding self-identification is defined with the encoding attribute in the leading tag. This is only useful for documents which can be treated as ASCII up to that point though, so UTF-16/UCS-2 has to be detected beforehand or otherwise indicated. ### Tcl and encodings From Tcl 8.1, i18n support was brought to string processing, and it was wisely decided to - use Unicode as general character set - use UTF-8 as standard internal encoding - provide conversion support for the many other encodings in use. However, as unequal-length byte sequences make simple tasks as indexing into a string, or determining its length in characters more complex, the internal representation is converted to fixed-length 16-bit UCS-16 in such cases. (This brings new problems with recent Unicodes that cross the 16-bit barrier\... When practical use justifies it, this will have to change to UCS-32, or 4 bytes per character.) Not all i18n issues are therefore automatically solved for the user. One still has to analyze seemingly simple tasks like uppercase conversion (Turkish dotted/undotted I make an anomaly) or sorting (\"collation order\" is not necessarily the numeric order of the Unicodes, as lsort would apply by default), and write custom routines if a more correct behavior is required. Other locale-dependent i18n issues like number/currency formatting, date/time handling also belong to this group. I recommend to start from the defaults Tcl provides, and if necessary, customize the appearance as desired. International data exchange is severely hampered if localized numeric data are exchanged, one side using period, the other comma as decimal point\... Strictly spoken, the Tcl implementation \"violates the UTF-8 spec, which explicitly forbids non-canonical representation of characters and requires that malformed UTF-8 sequences in the input be errors. \... I think that to be an advantage. But the spec says \'MUST\' so we\'re at least technically non-compliant.\" (Kevin B. Kenny in the Tcl chat, 2003-05-13) If textual data are internal to your Tcl script, all you have to know is the \\uxxxx notation, which is substituted into the character with Unicode U+xxxx (hexadecimal). This notation can be used wherever Tcl substitution takes place, even in braced regexp\'s and string map pairlists; else you can force it by substing the string in question. To demonstrate that for instance scan works transparently, here\'s a one-liner to format any Unicode character as HTML hex entity: `proc c2html c {format "&#x%4.4x;" [scan $c %c]}` Conversely it takes a few lines more: `proc html2u string {`\ `   while {regexp {&#[xX;} $string matched hex]} {`\ `       regsub -all $matched $string [format %c 0x$hex] string`\ `   }`\ `   set string`\ `}`\ `% html2u "this is a &x20ac; sign"`\ `this is a € sign` For all other purposes, two commands basically provide all i18n support: `fconfigure $ch -encoding $e` enables conversion from/to encoding e for an open channel (file or socket) if different from system encoding; `encoding convertfrom/to $e $string` does what it says, the other encoding being always Unicode. For instance, I could easily decode the bytes EF BB BF from a hexdump with `format %x [encoding convertfrom utf-8 \xef\xbb\xbf]` in an interactive tclsh, and found that it stood for the famous byte-order mark FEFF. Internally to Tcl, (almost) everything is a Unicode string. All communications with the operating system is done in the \"system encoding\", which you can query (but best not change) with the \[encoding system\] command. Typical values are iso8859-1 or -15 on European Linuxes, and cp1252 on European Windowses. **Introspection**: Find out what encodings are available in your installation with `encoding names` You can add new encodings by producing an .enc file and copying that in the directory lib/tcl8.4/encoding (or similar) where the other .enc files are situated. For the format of encoding files (which are text files, consisting mostly of hex digits), see the man page <http://www.tcl.tk/man/tcl8.4/TclLib/Encoding.htm> . The basename of your .enc file (without the .enc extension) will be the name under which it can be addressed, e.g. for an encoding *iso4711* name the file *iso4711.enc*. ### Localization: message catalogs Finally, the msgcat package supports localization (\"l10n\") of apps by allowing message catalogs for translation of strings, typically for GUI display, from a base language (typically English) to a target language selected by the current locale. For example, an app to be localized for France might contain a file en_fr.msg with, for simplicity, only the line `msgcat::mcset fr File Fichier` In the app itself, all you need is `package require msgcat`\ `namespace import msgcat::mc`\ `msgcat::mclocale fr ;#(1)`\ `#...`\ `pack [button .b -text [mc File]]` to have the button display the localized text for \"File\", namely \"Fichier\", as obtained from the message catalog. For other locales, only a new message catalog has to be produced by translating from the base language. Instead of explicit setting as in (1), typically the locale information might come from an environment (LANG) or registry variable. ### Tk: text rendering, fonts Rendering international strings on displays or printers can pose the biggest problems. First, you need fonts that contain the characters in question. Fortunately, more and more fonts with international characters are available, a pioneer being Bitstream Cyberbit that contains roughly 40000 glyphs and was for some time offered for free download on the Web. Microsoft\'s Tahoma font also added support for most alphabet writings, including Arabic. Arial Unicode MS delivered with Windows 2000 contains just about all the characters in the Unicode, so even humble Notepad can get truly international with that. But having a good font is still not enough. While strings in memory are arranged in logical order, with addresses increasing from beginning to end of text, they may need to be rendered in other ways, with diacritics shifted to various positions of the preceding character, or most evident for the languages that are written from right to left (\"r2l\"): Arabic, Hebrew. (Tk still lacks automatic \"bidi\"rectional treatment, so r2l strings have to be directed \"wrongly\" in memory to appear right when rendered - see A simple Arabic renderer on the Wiki). Correct bidi treatment has consequences for cursor movement, line justification, and line wrapping as well. Vertical lines progressing from right to left are popular in Japan and Taiwan - and mandatory if you had to render Mongolian. Indian scripts like Devanagari are alphabets with about 40 characters, but the sequence of consonants and vowels is partially reversed in rendering, and consonant clusters must be rendered as ligatures of the two or more characters involved - the pure single letters would look very ugly to an Indian. An Indian font for one writing system already contains several hundred glyphs. Unfortunately, Indian ligatures are not contained in the Unicode (while Arabic ones are), so various vendor standards apply for coding such ligatures. #### A little i18n tester ![](I18ntester_ce.jpg "I18ntester_ce.jpg") Here\'s a little script that shows you what exotic characters your system has available. It creates a text window and tries to show some sample text for the specified languages (the screenshot is from a PocketPC in the Bitstream Cyberbit font): `pack [text .t -font {Helvetica 16}]`\ `.t insert end "`\ `Arabic \uFE94\uFEF4\uFE91\uFEAE\uFECC\uFEDF\uFE8D\uFE94\uFEE4\uFEE0\uFEDC\uFEDF\uFE8D`\ `Trad. Chinese      \u4E2D\u570B\u7684\u6F22\u5B57`\ `Simplified Chinese \u6C49\u8BED`\ `Greek   \u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AE\`\ `\u03B3\u03BB\u03CE\u03C3\u03C3\u03B1`\ `Hebrew  \u05DD\u05D9\u05DC\u05E9\u05D5\u05E8\u05D9\`\ `\u05DC\u05D9\u05D0\u05E8\u05E9\u05D9`\ `Japanese \u65E5\u672C\u8A9E\u306E\u3072\u3089\u304C\u306A,\`\ `\u6F22\u5B57\u3068\u30AB\u30BF\u30AB\u30CA`\ `Korean          \uB300\uD55C\uBBFC\uAD6D\uC758 \uD55C\uAE00 (\u3CA2\u3498)`\ `Russian         \u0420\u0443\u0441\u0441\u043A\u0438\u0439\`\ `\u044F\u0437\u044B\u043A`\ `"` No font or size are specified, so you see the pure defaults (and notice how Tk manages to find characters). You can then configure the text widget for the fonts you\'d like to see. #### Input methods in Tcl/Tk To get outlandish characters not seen on the keyboard into the machine, they may at lowest level be specified as escape sequences, e.g. \"\\u2345\". But most user input will come from keyboards, for which many layouts exist in different countries. In CJK countries, there is a separate coding level between keys and characters: keystrokes, which may stand for the pronunciation or geometric components of a character, are collected in a buffer and converted into the target code when enough context is available (often supported by on-screen menus to resolve ambiguities). Finally, a \"virtual keyboard\" on screen, where characters are selected by mouse click, is especially helpful for non-frequent use of rarer characters, since the physical keyboard gives no hints which key is mapped to which other code. This can be implemented by a set of buttons, or minimally with a canvas that holds the provided characters as text items, and bindings to \<1\>, so clicking on a character inserts its code into the widget which has keyboard focus. See iKey: a tiny multilingual keyboard. The term \"input methods\" is often used for operating-system-specific i18n support, but I have no experiences with this, doing i18n from a German Windows installation. So far I\'m totally content with hand-crafted pure Tcl/Tk solutions - see taiku on the Wiki. ### Transliterations: The Lish family The Lish family is a set of transliterations, all designed to convert strings in lowly 7-bit ASCII to appropriate Unicode strings in some major non-Latin writing systems. The name comes from the common suffix \"lish\" as in English, which is actually the neutral element of the family, faithfully returning its input ;-) Some rules of thumb: - One \*lish character should unambiguously map to one target character, wherever applicable - One target letter should be represented by one \*lish letter (A-Za-z), wherever applicable. Special characters and digits should be avoided for coding letters - Mappings should be intuitive and/or follow established practices ```{=html} <!-- --> ``` - In languages that distinguish case, the corresponding substitutes for upper- and lowercase letters should also correspond casewise in lower ASCII. The Tclers\' Wiki <http://mini.net/tcl/> has the members of the Lish family available for copy\'n\'paste. The ones I most frequently use are - Arblish, which does context glyph selection and right-to-left conversion; - Greeklish; - Hanglish for Korean Hangul, which computes Unicodes from initial-vowel-final letters; - Ruslish for Cyrillic. Calling examples, that return the Unicodes for the specified input: `  arblish   dby w Abw Zby`\ `  greeklish Aqh'nai`\ `  hanglish  se-qul`\ `  heblish   irwsliM`\ `  ruslish   Moskva i Leningrad` #### Greeklish It all began with Greeklish, which is not my invention, but used by Greeks on the Internet for writing Greek without Greek fonts or character set support. I just extended the practice I found with the convention of marking accented vowels with a trailing apostrophe (so it\'s not a strict 1:1 transliteration anymore). Special care was taken to convert \"s\" at word end to \"c\", so it produces the final-sigma. Here is the code: `proc greeklish str {`\ `  regsub -all {s([ \t\n.,:;])} $str {c\1} str`\ `  string map {`\ `   A' \u386 E' \u388 H' \u389 I' \u38a O' \u38c U' \u38e W' \u38f`\ `   a' \u3ac e' \u3ad h' \u3ae i' \u3af o' \u3cc u' \u3cd w' \u3ce`\ `   A \u391 B \u392 G \u393 D \u394 E \u395 Z \u396 H \u397 Q \u398`\ `   I \u399 K \u39a L \u39b M \u39c N \u39d J \u39e O \u39f P \u3a0`\ `   R \u3a1 S \u3a3 T \u3a4 U \u3a5 F \u3a6 X \u3a7 Y \u3a8 W \u3a9`\ `   a \u3b1 b \u3b2 g \u3b3 d \u3b4 e \u3b5 z \u3b6 h \u3b7 q \u3b8`\ `   i \u3b9 k \u3ba l \u3bb m \u3bc n \u3bd j \u3be o \u3bf p \u3c0`\ `   r \u3c1 c \u3c2 s \u3c3 t \u3c4 u \u3c5 f \u3c6 x \u3c7 y \u3c8 `\ `   w \u3c9 ";" \u387 ? ";"`\ `  } $str`\ `}` Testing: `% greeklish Aqh'nai`\ `Αθήναι`\ `% greeklish "eis thn po'lin"`\ `εις την πόλιν` #### Hanglish Even though the Korean Hangul writing has many thousands of syllable characters, it is possible to compute the Unicode from the spelling of a syllable and vice versa. Here\'s how: `proc hangul2hanglish s {`\ `   set lead {g gg n d dd r m b bb s ss "" j jj c k t p h}`\ `   set vowel {a ae ya yai e ei ye yei o oa oai oi yo u ue uei ui yu w wi i}`\ `   set tail {"" g gg gs n nj nh d l lg lm lb ls lt lp lh m b bs s ss ng j c k t p h}`\ `   set res ""`\ `   foreach c [split $s ""] {`\ `       scan $c %c cnum`\ `       if {$cnum>=0xAC00 && $cnum<0xD7A3} {`\ `           incr cnum -0xAC00`\ `           set l [expr {$cnum / (28*21)}]`\ `           set v [expr {($cnum/28) % 21}]`\ `           set t [expr {$cnum % 28}]`\ `           append res  [lindex $lead $l ]`\ `           append res  [lindex $vowel $v]`\ `           append res "[lindex $tail $t] "`\ `       } else {append res $c}`\ `   }`\ `   set res`\ `}`\ `proc hanglish2uc hanglish {`\ `   set L ""; set V "" ;# in case regexp doesn't hit`\ `   set hanglish [string map {`\ `       AE R SH S R L NG Q YE X YAI F AI R YA V YO Y YU Z VI F`\ `   } [string toupper $hanglish]]`\ `   regexp {^([GNDLMBSQJCKTPH]+)?([ARVFEIXOYUZW]+)([GNDLMBSQJCKTPH]*)$} \`\ `       $hanglish ->  L V T ;# lead cons.-vowel-trail cons.`\ `   if {$L==""} {set L Q}`\ `   if {$V==""} {return $hanglish}`\ `   set l [lsearch {G GG N D DD L M B BB S SS Q J JJ C K T P H} $L]`\ `   set v [lsearch {A R V F E EI X XI O OA OR OI Y U UE UEI UI Z W WI I} $V]`\ `   set t [lsearch {"" G GG GS N NJ NH D L LG LM LB LS LT LP LH  \`\ `       M B BS S SS Q J C K T P H} $T] ;# trailing consonants`\ `   if {[min $l $v $t] < 0} {return $hanglish}`\ `   format %c [expr {$l*21*28 + $v*28 + $t + 0xAC00}]`\ `}`\ `proc min args {lindex [lsort -real $args] 0}`\ `proc hanglish argl {`\ `   set res ""`\ `   foreach i $argl {`\ `       foreach j [split $i -] {append res [hanglish2uc $j]}`\ `   }`\ `   append res " "`\ `}` ### Collation Collation is \"the logical ordering of character or wide-character strings according to defined precedence rules. These rules identify a collation sequence between the collating elements, and such additional rules that can be used to order strings consisting of multiple collating elements.\" Tcl\'s **lsort** sorts according to numerical Unicode values, which may not be correct in some locales. For instance, in Portuguese, accented letters should sort as if they weren\'t, but in Unicode sequence come after \"z\". The following simple code takes a map in which collation differences can be listed as {from to from to\...}, sorts the mapped items, and retrieves only the original elements: `proc collatesort {list map} {`\ `   set l2 {}`\ `   foreach e $list {`\ `      lappend l2 [list $e [string map $map $e]]`\ `   }`\ `   set res {}`\ `   foreach e [lsort -index 1 $l2] {lappend res [lindex $e 0]}`\ `   set res`\ `}` Testing, Portuguese: `% collatesort {ab ãc ãd ae} {ã a}`\ `ab ãc ãd ae` Spanish (ll sorts after lz): `% collatesort {llano luxación leche} {ll lzz}`\ `leche luxación llano` German (umlauts sorted as if \"ä\" was \"ae\"): `% lsort {Bar Bär Bor}`\ `Bar Bor Bär`\ `% collatesort {Bar Bär Bor} {ä ae}`\ `Bär Bar Bor`
# Tcl Programming/regexp ### Overview Another language (I wouldn\'t want to call it \"little\") embedded inside Tcl is *regular expressions*. They may not look like this to you - but they follow (many) rules, indeed. The purpose is to describe a string pattern to match with - for searching, extracting, or replacing substrings. Regular expressions are used in the *regexp*, *regsub* commands, and optionally in *lsearch* and *switch*. Note that this language is very different from Tcl itself, so in most cases it is best to brace an RE, to prevent the Tcl parser from misunderstanding them. Before the gory details begin, let\'s start with some examples: `regexp {[0-9]+[a-z]} $input ` returns 1 if \$input contains one or more digits, followed by a lowercase letter. `set result [regsub -all {[A-Z]} $input ""]` deletes all uppercase letters from \$input, and saves that to the *result* variable. `lsearch -all -inline -regexp $input {^-}` returns all elements in the list \$input which start with a \"-\". ### Character classes Many characters just stand for themselves. E.g. `a` matches indeed the character \"a\". Any Unicode can be specified in the \\uXXXX format. In brackets (not the same as Tcl\'s), a set of alternatives (a \"class\") is defined: `[abc]` matches \"a\", \"b\", or \"c\". A dash (-) between two characters spans the range between them, e.g. `[0-9]` matches one decimal digit. To have literal \"-\" in a set of alternatives, put it first or last: `[0-9-]` matches a digit or a minus sign. A bracketed class can be negated by starting it with \^, e.g. `[^0-9]` matches any character that is not a decimal digit. The period \".\" represents one instance of any character. If a literal \".\" is intended (or in general, to escape any character that has a special meaning to the regexp syntax), put a backslash \"\\\" before it - and make sure the regular expression is braced, so the Tcl parser doesn\'t eat up the backslash early\...). ### Quantifiers To repeat a character (set) other than once, there are quantifiers put behind it, e.g. `a+     matches one or more "a"s,`\ `a?     matches zero or one "a",`\ `a*     matches zero or more "a"s.` There is also a way of numeric quantification, using braces (again, not the same as Tcl\'s): `a{2}   matches two "a"s - same as "aa"`\ `a{1,5} matches one to five "a"s`\ `a{1,}  one or more - like a+`\ `a{0,1} zero or one - like a?`\ `a{0,}  zero or more - like a*` The + and \* quantifiers act \"greedy\", i.e. they consume the longest possible substring. For non-greedy behavior, which provides the shortest possible match, add a \"?\" in behind. Examples: `% regexp -inline {<(.+)>} ``<foo>`{=html}`<bar>`{=html}`<grill>`{=html}\ `<foo>`{=html}`<bar>`{=html}`<grill>`{=html}` foo>``<bar>`{=html}`<grill` This matches until the last close-bracket `% regexp -inline {<(.+?)>} ``<foo>`{=html}`<bar>`{=html}`<grill>`{=html}\ `<foo>`{=html}` foo` This matches until the first close-bracket. ### Anchoring By default, a regular expression can match anywhere in a string. You can limit that to the beginning (\^) and/or end (\$): `regexp {^a.+z$} $input` succeeds if input begins with \"a\" and ends with \"z\", and has one or more characters between them. ### Grouping A part of a regular expression can be grouped by putting parentheses () around it. This can have several purposes: - *regexp* and *regsub* can extract or refer to such substrings - the operator precedence can be controlled The \"\|\" (or) operator has high precedence. So `foo|bar grill` matches the strings \"foo\" or \"bar grill\", while `(foo|bar) grill` matches \"foo grill\" or \"bar grill\". `(a|b|c) ;# is another way to write [abc]` For extracting substrings into separate variables, *regexp* allows additional arguments: `regexp ?options? re input fullmatch part1 part2...` Here, variable *fullmatch* will receive the substring of *input* that matched the regular expression *re*, while part1 etc. receive the parenthesized submatches. As *fullmatch* is often not needed, it has become an eye-candy idiom to use the variable name \"-\>\" in that position, e.g. `regexp {(..)(...)} $input -> first second` places the first two characters of *input* in the variable \'first*, and the next three in the variable*second*. If \$input was \"ab123\",*first*will hold \"ab\", and*second\'\' will contain \"123\". In **regsub** and **regexp**, you can refer to parenthesized submatches with \\1 for the first, \\2 for the second, etc. \\0 is the full match, as with *regexp* above. Example: `% regsub {(..)(...)} ab123 {\2\1=\0}`\ `123ab=ab123` Here \\1 contains \"ab\", \\2 contains \"123\", and \\0 is the full match \"ab123\". Another example, how to find four times the same lowercase letter in a row (the first occurrence, plus then three): `regexp {([a-z])\1{3}} $input` ### More examples Parse the contents in angle brackets (note that the result contains the full match and the submatch in paired sequence, so use *foreach* to extract only the submatches): `% regexp -all -inline {<([^>]+)>} x``<a>`{=html}`y<b>z``<c>`{=html}`d`\ `<a>`{=html}` a <b> b ``<c>`{=html}` c` Insert commas between groups of three digits into the integer part of a number: `% regsub -all {\d(?=(\d{3})+($|\.))} 1234567.89 {\0,}`\ `1,234,567.89` In other countries, you might use an apostrophe (\') as separator, or make groups of four digits (used in Japan). In the opposite direction, converting such formatted numbers back to the regular way for use in calculations, the task consists simply of removing all commas. This can be done with **regsub**: `% regsub -all , 1,234,567.89 ""`\ `1234567.89` but as the task involves only constant strings (comma and empty string), it is more efficient not to use regular expressions here, but use a **string map** command: `% string map {, ""} 1,234,567.89`\ `1234567.89`
# Tcl Programming/Debugging Tcl itself is quite a good teacher. Don\'t be afraid to do something wrong - it will most often deliver a helpful error message. When tclsh is called with no arguments, it starts in an interactive mode and displays a \"%\" prompt. The user types something in and sees what comes out: either the result or an error message. Trying isolated test cases interactively, and pasting the command into the editor when satisfied, can greatly reduce debugging time (there is no need to restart the application after every little change - just make sure it\'s the right one, before restarting.) ### A quick tour Here\'s a commented session transcript: `% hello`\ `invalid command name "hello"` OK, so we\'re supposed to type in a command. Although it doesn\'t look so, here\'s one: `% hi`\ `     1  hello`\ `    2  hi` Interactive tclsh tries to guess what we mean, and \"hi\" is the unambiguous prefix of the \"history\" command, whose results we see here. Another command worth remembering is \"info\": `% info`\ `wrong # args: should be "info option ?arg arg ...?"` The error message tells us there should be at least one option, and optionally more arguments. `% info option`\ `bad option "option": must be args, body, cmdcount, commands, complete, default,`\ `exists, functions, globals, hostname, level, library, loaded, locals, nameofexecutable,`\ `patchlevel, procs, script, sharedlibextension, tclversion, or vars` Another helpful error: \"option\" is not an option, but the valid ones are listed. To get information about commands, it makes sense to type the following: `% info commands`\ `tell socket subst lremove open eof tkcon_tcl_gets pwd glob list exec pid echo `\ `dir auto_load_index time unknown eval lrange tcl_unknown fblocked lsearch gets `\ `auto_import case lappend proc break dump variable llength tkcon auto_execok return`\ `pkg_mkIndex linsert error bgerror catch clock info split thread_load loadvfs array`\ `if idebug fconfigure concat join lreplace source fcopy global switch which auto_qualify`\ `update tclPkgUnknown close clear cd for auto_load file append format tkcon_puts alias `\ `what read package set unalias pkg_compareExtension binary namespace scan edit trace seek `\ `while flush after more vwait uplevel continue foreach lset rename tkcon_gets fileevent `\ `regexp tkcon_tcl_puts observe_var tclPkgSetup upvar unset encoding expr load regsub history`\ `exit interp puts incr lindex lsort tclLog observe ls less string` Oh my, quite many\... How many? `% llength [info commands]`\ `115` Now for a more practical task - let\'s let Tcl compute the value of Pi. `% expr acos(-1)`\ `3.14159265359` Hm.. can we have that with more precision? `% set tcl_precision 17`\ `17`\ `% expr acos(-1)`\ `3.1415926535897931` Back to the first try, where \"hello\" was an invalid command. Let\'s just create a valid one: `% proc hello {} {puts Hi!}` Silently acknowledged. Now testing: `% hello`\ `Hi!` ### Errors are exceptions What in Tcl is called **error** is in fact more like an *exception* in other languages - you can deliberately raise an error, and also **catch** errors. Examples: `if {$username eq ""} {error "please specify a user name"}` `if [catch {open $filename w} fp] {`\ `   error "$filename is not writable"`\ `}` One reason for errors can be an undefined command name. One can use this playfully, together with *catch*, as in the following example of a multi-loop *break*, that terminates the two nested loops when a matrix element is empty: `if [catch {`\ `   foreach row $matrix {`\ `      foreach col $row {`\ `          if {$col eq ""} throw`\ `      }`\ `   }`\ `}] {puts "empty matrix element found"}` The *throw* command does not exist in normal Tcl, so it throws an error, which is caught by the *catch* around the outer loop. #### The errorInfo variable This global variable provided by Tcl contains the last error message and the traceback of the last error. Silly example: `% proc foo {} {bar x}`\ `% proc bar {input} {grill$input}`\ `% foo`\ `invalid command name "grillx"` `% set errorInfo`\ `invalid command name "grillx"`\ `   while executing`\ `"grill$input"`\ `   (procedure "bar" line 1)`\ `   invoked from within`\ `"bar x"`\ `   (procedure "foo" line 1)`\ `   invoked from within`\ `"foo"` If no error has occurred yet, *errorInfo* will contain the empty string. #### The errorCode variable In addition, there is the *errorCode* variable that returns a list of up to three elements: - category (POSIX, ARITH, \...) - abbreviated code for the last error - human-readable error text Examples: `% open not_existing`\ `couldn't open "not_existing": no such file or directory`\ `% set errorCode`\ `POSIX ENOENT {no such file or directory}` `% expr 1/0`\ `divide by zero`\ `% set errorCode`\ `ARITH DIVZERO {divide by zero}` `% foo`\ `invalid command name "foo"`\ `% set errorCode`\ `NONE` ### Tracing procedure calls For a quick overview how some procedures are called, and when, and what do they return, and when, the *trace execution* is a valuable tool. Let\'s take the following factorial function as example: `proc fac x {expr {$x<2? 1 : $x * [fac [incr x -1]]}} ` We need to supply a handler that will be called with different numbers of arguments (two on enter, four on leave). Here\'s a very simple one: `proc tracer args {puts $args}` Now we instruct the interpreter to trace *enter* and *leave* of *fac*: `trace add execution fac {enter leave} tracer` Let\'s test it with the factorial of 7: `fac 7` which gives, on stdout: `{fac 7} enter`\ `{fac 6} enter`\ `{fac 5} enter`\ `{fac 4} enter`\ `{fac 3} enter`\ `{fac 2} enter`\ `{fac 1} enter`\ `{fac 1} 0 1 leave`\ `{fac 2} 0 2 leave`\ `{fac 3} 0 6 leave`\ `{fac 4} 0 24 leave`\ `{fac 5} 0 120 leave`\ `{fac 6} 0 720 leave`\ `{fac 7} 0 5040 leave` So we can see how recursion goes down to 1, then returns in backward order, stepwise building up the final result. The 0 that comes as second word in \"leave\" lines is the return status, 0 being TCL_OK. ### Stepping through a procedure To find out how exactly a proc works (and what goes wrong where), you can also register commands to be called before and after a command inside a procedure is called (going down transitively to all called procs). You can use the following *step* and *interact* procedures for this: `proc step {name {yesno 1}} {`\ `   set mode [expr {$yesno? "add" : "remove"}]`\ `   trace $mode execution $name {enterstep leavestep} interact`\ `}` `proc interact args {`\ `   if {[lindex $args end] eq "leavestep"} {`\ `       puts ==>[lindex $args 2]`\ `       return`\ `   }`\ `   puts -nonewline "$args --"`\ `   while 1 {`\ `       puts -nonewline "> "`\ `       flush stdout`\ `       gets stdin cmd`\ `       if {$cmd eq "c" || $cmd eq ""} break`\ `       catch {uplevel 1 $cmd} res`\ `       if {[string length $res]} {puts $res}`\ `   }`\ `}` `#----------------------------Test case, a simple string reverter:`\ `proc sreverse str {`\ `   set res ""`\ `   for {set i [string length $str]} {$i > 0} {} {`\ `       append res [string index $str [incr i -1]]`\ `   }`\ `   set res`\ `}` `#-- Turn on stepping for ``sreverse``:`\ `step sreverse`\ `sreverse hello` `#-- Turn off stepping (you can also type this command from inside interact):`\ `step sreverse 0`\ `puts [sreverse Goodbye]` The above code gives the following transcript when sourced into a tclsh: `{set res {}} enterstep -->`\ `==>`\ `{for {set i [string length $str]} {$i > 0} {} {`\ `       append res [string index $str [incr i -1]]`\ `   }} enterstep -->`\ `{string length hello} enterstep -->`\ `==>5`\ `{set i 5} enterstep -->`\ `==>5`\ `{incr i -1} enterstep -->`\ `==>4`\ `{string index hello 4} enterstep -->`\ `==>o`\ `{append res o} enterstep -->`\ `==>o`\ `{incr i -1} enterstep -->`\ `==>3`\ `{string index hello 3} enterstep -->`\ `==>l`\ `{append res l} enterstep -->`\ `==>ol`\ `{incr i -1} enterstep -->`\ `==>2`\ `{string index hello 2} enterstep -->`\ `==>l`\ `{append res l} enterstep -->`\ `==>oll`\ `{incr i -1} enterstep -->`\ `==>1`\ `{string index hello 1} enterstep -->`\ `==>e`\ `{append res e} enterstep -->`\ `==>olle`\ `{incr i -1} enterstep -->`\ `==>0`\ `{string index hello 0} enterstep -->`\ `==>h`\ `{append res h} enterstep -->`\ `==>olleh`\ `==>`\ `{set res} enterstep -->`\ `==>olleh`\ `eybdooG` ### Debugging The simplest way to inspect why something goes wrong is inserting a *puts* command before the place where it happens. Say if you want to see the values of variables x and y, just insert `puts x:$x,y:$y` (if the string argument contains no spaces, it needs not be quoted). The output will go to stdout - the console from where you started the script. On Windows or Mac, you might need to add the command `console show` to get the substitute console Tcl creates for you, when no real one is present. If at some time you want to see details of what your program does, and at others not, you can define and redefine a *dputs* command that either calls *puts* or does nothing: `proc d+ {} {proc dputs args {puts $args}}`\ `proc d- {} {proc dputs args {}}`\ `d+ ;# initially, tracing on... turn off with d-` For more debugging comfort, add the proc *interact* from above to your code, and put a call to *interact* before the place where the error happens. Some useful things to do at such a debugging prompt: `info level 0    ;# shows how the current proc was called`\ `info level      ;# shows how deep you are in the call stack`\ `uplevel 1 ...   ;# execute the ... command one level up, i.e. in the caller of the current proc`\ `set ::errorInfo ;# display the last error message in detail` ### Assertions Checking data for certain conditions is a frequent operation in coding. Absolutely intolerable conditions can just throw an error: `  if {$temperature > 100} {error "ouch... too hot!"}` Where the error occurred is evident from ::errorInfo, which will look a bit clearer (no mention of the error command) if you code `  if {$temperature > 100} {return -code error "ouch... too hot!"}` If you don\'t need hand-crafted error messages, you can factor such checks out to an assert command: `proc assert condition {`\ `   set s "{$condition}"`\ `   if {![uplevel 1 expr $s]} {`\ `       return -code error "assertion failed: $condition"`\ `   }`\ `}` Use cases look like this: `  assert {$temperature <= 100}` Note that the condition is reverted - as \"assert\" means roughly \"take for granted\", the positive case is specified, and the error is raised if it is not satisfied. Tests for internal conditions (that do not depend on external data) can be used during development, and when the coder is sure they are bullet-proof to always succeed, (s)he can turn them off centrally in one place by defining `proc assert args {}` This way, assertions are compiled to no bytecode at all, and can remain in the source code as a kind of documentation. If assertions are tested, it only happens at the position where they stand in the code. Using a trace, it is also possible to specify a condition once, and have it tested whenever a variable\'s value changes: `proc assertt {varName condition} {`\ `   uplevel 1 [list trace var $varName w "assert $condition ;#"]`\ `}` The \";#\" at the end of the trace causes the additional arguments name element op, that are appended to the command prefix when a trace fires, to be ignored as a comment. Testing: `% assertt list {[llength $list]<10}`\ `% set list {1 2 3 4 5 6 7 8}`\ `1 2 3 4 5 6 7 8`\ `% lappend list 9 10`\ `can't set "list": assertion failed: 10<10` The error message isn\'t as clear as could be, because the \[llength \$list\] is already substituted in it. But I couldn\'t find an easy solution to that quirk in this breakfast fun project - backslashing the \$condition in the assertt code sure didn\'t help. Better ideas welcome. To make the assertion condition more readable, we could quote the condition one more time,i.e ``` tcl % assertt list {{[llength $list]<10}} % set list {1 2 3 4 5 6 7 8} 1 2 3 4 5 6 7 8 % lappend list 9 10 can't set "list": assertion failed: [llength $list]<10 % ``` In this case,when trace trigger fires, the argument for assert is {\[llength \$list\]\<10}. In any case, these few lines of code give us a kind of bounds checking - the size of Tcl\'s data structures is in principle only bounded by the available virtual memory, but runaway loops may be harder to debug, compared to a few assertt calls for suspicious variables: `assertt aString {[string length $aString]<1024}` or `assertt anArray {[array size anArray] < 1024*1024}` Tcllib has a control::assert with more bells and whistles. ### A tiny testing framework Bugs happen. The earlier found, the easier for the coder, so the golden rule \"Test early. Test often\" should really be applied. One easy way is adding self-tests to a file of Tcl code. When the file is loaded as part of a library, just the proc definitions are executed. If however you feed this file directly to a tclsh, that fact is detected, and the \"e.g.\" calls are executed. If the result is not the one expected, this is reported on stdout; and in the end, you even get a little statistics. Here\'s a file that implements and demonstrates \"e.g.\": `# PROLOG -- self-test: if this file is sourced at top level:`\ `if {[info exists argv0]&&[file tail [info script]] eq [file tail $argv0]} {`\ `   set Ntest 0; set Nfail 0`\ `   proc e.g. {cmd -> expected} {`\ `       incr ::Ntest`\ `       catch {uplevel 1 $cmd} res`\ `       if {$res ne $expected} {`\ `           puts "$cmd -> $res, expected $expected"`\ `           incr ::Nfail`\ `       }`\ `   }`\ `} else {proc e.g. args {}} ;# does nothing, compiles to nothing` `##------------- Your code goes here, with e.g. tests following`\ `proc sum {a b} {expr {$a+$b}}`\ `e.g. {sum 3 4} -> 7` `proc mul {a b} {expr {$a*$b}}`\ `e.g. {mul 7 6} -> 42` `# testing a deliberate error (this way, it passes):`\ `e.g. {expr 1/0} -> "divide by zero"` `## EPILOG -- show statistics:`\ `e.g. {puts "[info script] : tested $::Ntest, failed $::Nfail"} -> ""` ### Guarded proc In more complex Tcl software, it may happen that a procedure is defined twice with different body and/or args, causing hard-to-track errors. The Tcl command *proc* itself doesn\'t complain if it is called with an existing name. Here is one way to add this functionality. Early in your code, you overload the proc command like this: ` rename proc _proc`\ ` _proc proc {name args body} {`\ `   set ns [uplevel namespace current]`\ `   if {[info commands $name]!="" || [info commands ${ns}::$name]!=""} {`\ `       puts stderr "warning: [info script] redefines $name in $ns"`\ `   }`\ `   uplevel [list _proc $name $args $body]`\ ` }` From the time that is sourced, any attempt to override a proc name will be reported to stderr (on Win-wish, it would show on the console in red). You may make it really strict by adding an \"exit\" after the \"puts stderr \...\", or throw an error. Known feature: proc names with wildcards will run into this trap, e.g. `  proc * args {expr [join $args *]*1}` will always lead to a complaint because \"\*\" fits any proc name. Fix (some regsub magic on \'name\') left as an exercise. ### Windows wish console While on Unixes, the standard channels *stdin*, *stdout*, and *stderr* are the same as the terminal you started wish from, a Windows *wish* doesn\'t typically have these standard channels (and is mostly started with double-click anyway). To help this, a console was added that takes over the standard channels (stderr even coming in red, stdin in blue). The console is normally hidden, but can be brought up with the command ` console show` You can also use the partially documented \"console\" command. \"console eval ```{=html} <script> ``` \" evals the given script in the Tcl interpreter that manages the console. The console\'s text area is actually a text widget created in this interpreter. For example: `       console eval {.console config -font Times}` will change the font of the console to \"Times\". Since the console is a Tk text widget, you can use all text widget commands and options on it (for example, changing colors, bindings\...). `console eval {winfo children .}` tells you more about the console widget: it is a toplevel with children .menu, .console (text), and .sb (scrollbar). You can resize the whole thing with `console eval {wm geometry . $Wx$H+$X+$Y}` where \$W and \$H are dimensions in character cells (default 80x24), but \$X and \$Y are in pixels. And more again: you can even add widgets to the console - try `console eval {pack [button .b -text hello -command {puts hello}]}` The button appears between the text widget and the scroll bar, and looks and does as expected. There is also a way back: the main interpreter is visible in the console interpreter under the name, consoleinterp. ### Remote debugging Here\'s a simple experiment on how to connect two Tcl processes so that one (call it \"debugger\") can inspect and control the other (\"debuggee\"). Both must have an event loop running (which is true when Tk runs, or when started with e.g. *vwait forever*). As this goes over a socket connection, the two processes could be on different hosts and operating systems (though I\'ve so far tested only the localhost variety). Use at your own risk, of course\... :\^) The \"debuggee\" contains in my experiments the following code, in addition to its own: `proc remo_server {{port 3456}} {`\ `   set sock [socket -server remo_accept $port]`\ `}`\ `proc remo_accept {socket adr port} {`\ `   fileevent $socket readable [list remo_go $socket]`\ `}`\ `proc remo_go {sock} {`\ `   gets $sock line`\ `   catch {uplevel \#0 $line} res`\ `   puts $sock $res`\ `   if [catch {flush $sock}] {close $sock}`\ `}`\ `remo_server` The \"debugger\" in this version (remo.tcl) runs only on Windows in a wish, as it needs a console, but you could modify it to avoid these restrictions: `#!/usr/bin/env wish`\ `console show`\ `wm withdraw .`\ `set remo [socket localhost 3456]`\ `fileevent $remo readable "puts `$$gets $remo$$`"`\ `proc r args {puts $::remo [join $args]; flush $::remo}`\ `puts "remote connection ready - use r to talk"` Now from *remo* you can call any Tcl command in the \"debuggee\", where it is executed in global scope, so in particular you can inspect (and modify) global variables. But you could also redefine procs on the fly, or whatever tickles your fancy\... Examples from a remo session, showing that the two have different pids, how errors are reported, and that quoting is different from normal (needs more work): `10 % pid`\ `600`\ `11 % r pid`\ `2556`\ `12 % r wm title . "Under remote control"`\ `wrong # args: should be "wm title window ?newTitle?"`\ `13 % r wm title . {"Under remote control"}`
# Tcl Programming/Working with files \_\_TOC\_\_ ### Files and channels In addition to the functionalities known from C\'s stdio, Tcl offers more commands that deal with files, similar to what shells provide, though often a bit more verbose. Here are some examples: `glob *.tcl` List all files in the current directory that match the pattern \*.tcl. `file copy /from/path/file.ext /to/path`\ `.`\ `file delete /from/path/file.ext`\ `.`\ `file rename before.txt after.txt`\ `.`\ `cd /an/other/directory`\ `.`\ `pwd` To let code temporarily execute in another directory, use this pattern: `set here [pwd]`\ `cd $someotherdir`\ `#... code here`\ `cd $here` More precisely, many \"file\" operations work in general on \"channels\", which can be - standard channels (stdin, stdout, stderr) - files as opened with **open \...** - pipes as opened with *\'open \|\...* - sockets (TCP) ### File names Files are often addressed with *path names*, which indicate their position in the directory tree. Like Unix, Tcl uses \"/\" as path separator, while on Windows \"\\\" is the native way - which brings trouble not only to Tcl, but even to C, because \"\\\" is the escape character on both, so that e.g. \\t is parsed as horizontal tab, \\n as newline, etc. Fortunately Windows accepts natively \"/\" as well, so you can use forward slash in both Tcl and C programs as path separator without worries. However, you still have to take care of escape sequences. One stopgap measure is - to escape the escape character, i.e. write \\\\ for \\, or - brace backslashed names, e.g. {\\foo\\bar\\grill.txt} But Tcl allows to use the \"normal\" separator / in almost all situations, so you\'re safer off with that. Unfortunately, things are sad for Mac users, since MacOS (before X) accepts only \":\" as file separator. If you need to, here\'s ways to convert between the two forms: `% file normalize \\foo\\bar\\grill.txt`\ `C:/foo/bar/grill.txt`\ `% file nativename /foo/bar/grill.txt`\ `\foo\bar\grill.txt` You can even use file join command: *file join arg1 arg2 \... argN* Tcl will then take care of all platform dependent details to create platform independent path. For example: *set somepath \[file join foo bar grill.txt\]* will result in following path (on windows machine): foo/bar/grill.txt ### Input and output Tcl\'s input/output commands are pretty closely based on those from C\'s stdio (just strip off the leading *f*): - set handle \[**open** *filename ?mode?*\] - set data \[**read** *\$handle ?int?*\] - **tell** *\$handle* - **seek** *\$handle offset ?from?* - **puts** *?-nonewline? ?\$handle? content* - **gets** *\$handle ?varname?* - **close** *\$handle* C\'s *printf* functionality is split in two steps: - format the data into a string with **format** (which is very much like *sprintf*) - output the resulting string with **puts**. For example, `puts $handle [format "%05d %s" $number $text]` To process a text file line by line, you have two choices. If the file is smaller than several megabytes, you can read it just in one go: `set f [open $filename]`\ `foreach line [split [read $f] \n] {`\ `    # work with $line here ...`\ `}`\ `close $f` For files of any big size, you can read the lines one by one (though this is slightly slower than the above approach): `set f [open $filename]`\ `while {[gets $f line] >= 0} {`\ `    # work with $line here ...`\ `}`\ `close $f`\ Finally, if you can format your file so that it is executable Tcl code, the following reading method is fastest: `source $filename` To \"touch a file\", i.e. create it if not exists, and in any case update its modification time, you can use this: `proc touch name {close [open $name a]}` ### \"Binary\" files All files are made of bytes, which are made of bits, which are binary. The term \"binary\" with files relates mostly to the fact that they can contain bytes of any value, and line-ends (Carriage Return+Newline in the DOS/Windows world) are not to be translated. Tcl can handle \"binary\" files without a problem \-- just configure the channel as binary after opening: `set fp [open tmp.jpg]`\ `fconfigure $fp -translation binary`\ `set content [read $fp]`\ `close $fp` Now the variable *content* holds the file\'s contents, byte for byte. To test whether a file is \"binary\", in the sense that it contains NUL bytes: `proc binary? filename {`\ `   set f [open $filename]`\ `   set data [read $f 1024]`\ `   close $f`\ `   expr {[string first \x00 $data]>=0}`\ `}` ### The file command Many useful operations with files are collected in the **file** command. The first argument tells which operation to do: - file atime name ?time? - file attributes name - file attributes name ?option? - file attributes name ?option value option value\...? - file channels ?pattern? - returns the handles of currently open files - file copy ?-force? ?- -? source target - file copy ?-force? ?- -? source ?source \...? targetDir - file delete ?-force? ?- -? pathname ?pathname \... ? - file dirname name - e.g. \[file dirname /foo/bar/grill.txt\] -\> /foo/bar - file executable name - file exists name - file extension name - e.g. \[file extension /foo/bar/grill.txt\] -\> .txt - file isdirectory name - file isfile name - file join name ?name \...? - file link ?-linktype? linkName ?target? - file lstat name varName - file mkdir dir ?dir \...? - creates one or more directories (folders) - file mtime name ?time? - file nativename name - file normalize name - file owned name - file pathtype name - file readable name - file readlink name - file rename ?-force? ?- -? source target - file rename ?-force? ?- -? source ?source \...? targetDir - file rootname name - e.g. \[file rootname /foo/bar/grill.txt\] -\> /foo/bar/grill - file separator ?name? - file size name - file split name - e.g \[file split /foo/bar/grill.txt\] -\> {foo bar grill.txt} - file stat name varName - file system name - file tail name - e.g. \[file tail /foo/bar/grill.txt\] -\> grill.txt - file type name - file volumes - Windows: returns your \"drive letters\", e.g {A:/ C:/} - file writable name
# Tcl Programming/Examples Most of these example scripts first appeared in the Tclers\' Wiki <http://wiki.tcl.tk> . The author (Richard Suchenwirth) declares them to be fully in the public domain. The following scripts are plain Tcl, they don\'t use the Tk GUI toolkit (there\'s a separate chapter for those). ### Sets as lists Tcl\'s lists are well suited to represent sets. Here\'s typical set operations. If you use the tiny testing framework explained earlier, the *e.g.* lines make the self-test; otherwise they just illustrate how the operations should work. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc set'contains {set el} {expr {[lsearch -exact $set $el]>=0}} e.g. {set'contains {A B C} A} -> 1 e.g. {set'contains {A B C} D} -> 0 proc set'add {_set args} { upvar 1 $_set set foreach el $args { if {![set'contains $set $el]} {lappend set $el} } set set } set example {1 2 3} e.g. {set'add example 4} -> {1 2 3 4} e.g. {set'add example 4} -> {1 2 3 4} proc set'remove {_set args} { upvar 1 $_set set foreach el $args { set pos [lsearch -exact $set $el] set set [lreplace $set $pos $pos] } set set } e.g. {set'remove example 3} -> {1 2 4} proc set'intersection {a b} { foreach el $a {set arr($el) ""} set res {} foreach el $b {if {[info exists arr($el)]} {lappend res $el}} set res e.g. {set'intersection {1 2 3 4} {2 4 6 8}} -> {2 4} proc set'union {a b} { foreach el $a {set arr($el) ""} foreach el $b {set arr($el) ""} lsort [array names arr] } e.g. {set'union {1 3 5 7} {2 4 6 8}} -> {1 2 3 4 5 6 7 8} proc set'difference {a b} { eval set'remove a $b } e.g. {set'difference {1 2 3 4 5} {2 4 6}} -> {1 3 5} ``` ```{=html} </div> ``` ### Hex-dumping a file The following example code opens a file, configures it to binary translation (i.e. line-ends `\r\n` are not standardized to `\n` as usual in C), and prints as many lines as needed which each contain 16 bytes in hexadecimal notation, plus, where possible, the ASCII character. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc file'hexdump filename { set fp [open $filename] fconfigure $fp -translation binary set n 0 while {![eof $fp]} { set bytes [read $fp 16] regsub -all {[^\x20-\xfe]} $bytes . ascii puts [format "%04X %-48s %-16s" $n [hexdump $bytes] $ascii] incr n 16 } close $fp } proc hexdump string { binary scan $string H* hex regexp -all -inline .. $hex } ``` ```{=html} </div> ``` The \"main routine\" is a single line that dumps all files given on the command line: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl foreach file $argv {file'hexdump $file} ``` ```{=html} </div> ``` Sample output, the script applied to itself: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text ...> tclsh hexdump.tcl hexdump.tcl 0000 0d 0a 20 70 72 6f 63 20 66 69 6c 65 27 68 65 78 .. proc file'hex 0010 64 75 6d 70 20 66 69 6c 65 6e 61 6d 65 20 7b 0d dump filename {. 0020 0a 20 20 20 20 73 65 74 20 66 70 20 5b 6f 70 65 . set fp [ope 0030 6e 20 24 66 69 6c 65 6e 61 6d 65 5d 0d 0a 20 20 n $filename].. ... ``` ```{=html} </div> ``` ### Roman numerals Roman numerals are an additive (and partially subtractive) system with the following letter values: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text I=1 V=5 X=10 L=50 C=100 D=500 M=1000; MCMXCIX = 1999 ``` ```{=html} </div> ``` Here\'s some Tcl routines for dealing with Roman numerals. **Sorting roman numerals:** I,V,X already come in the right order; for the others we have to introduce temporary collation transformations, which we\'ll undo right after sorting: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc roman:sort list { set map {IX VIIII L Y XC YXXXX C Z D {\^} ZM {\^ZZZZ} M _} foreach {from to} $map { regsub -all $from $list $to list } set list [lsort $list] foreach {from to} [lrevert $map] { regsub -all $from $list $to list } set list } ``` ```{=html} </div> ``` **Roman numerals from integer:** ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc roman:numeral {i} { set res "" foreach {value roman} { 1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 9 IX 5 V 4 IV 1 I} { while {$i>=$value} { append res $roman incr i -$value } } set res } ``` ```{=html} </div> ``` **Roman numerals parsed into integer:** ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc roman:get {s} { array set r_v {M 1000 D 500 C 100 L 50 X 10 V 5 I 1} set last 99999; set res 0 foreach i [split [string toupper $s] ""] { if [catch {set val $r_v($i)}] { error "un-Roman digit $i in $s" } incr res $val if {$val>$last} {incr res [expr -2*$last]} set last $val } set res } ``` ```{=html} </div> ``` ### Custom control structures As \"control structures\" are really nothing special in Tcl, just a set of commands, it is easier than in most other languages to create one\'s own. For instance, if you would like to simplify the **for** loop ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl for {set i 0} {$i < $max} {incr i} {...} ``` ```{=html} </div> ``` for the typical simple cases so you can write instead ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl loop i 0 $max {...} ``` ```{=html} </div> ``` here is an implementation that even returns a list of the results of each iteration: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc loop {_var from to body} { upvar 1 $_var var set res {} for {set var $from} {$var < $to} {incr var} {lappend res [uplevel 1 $body]} return $res } ``` ```{=html} </div> ``` using this, a *string reverse* function can be had as a one-liner: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc sreverse {str} { join [loop i 0 [string length $str] {string index $str end-$i}] "" } ``` ```{=html} </div> ``` #### Range-aware switch Another example is the following **range-aware switch** variation. A range (numeric or strings) can be given as from..to, and the associated scriptlet gets executed if the tested value lies inside that range. Like in switch, fall-through collapsing of several cases is indicated by \"-\", and \"default\" as final condition fires if none else did. Different from switch, numbers are compared by numeric value, no matter whether given as decimal, octal or hex. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc rswitch {value body} { set go 0 foreach {cond script} $body { if {[regexp {(.+)\.\.(.+)} $cond -> from to]} { if {$value >= $from && $value <= $to} {incr go} } else { if {$value == $cond} {incr go} } if {$go && $script ne "-"} { #(2) uplevel 1 $script break } } if {$cond eq "default" && !$go} {uplevel 1 $script} ;#(1) } ``` ```{=html} </div> ``` Testing: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % foreach i {A K c z 0 7} { puts $i rswitch $i { A..Z {puts upper} a..z {puts lower} 0..9 {puts digit} } } A upper K upper c lower z lower 0 digit 7 digit % rswitch 0x2A {42 {puts magic} default {puts df}} magic ``` ```{=html} </div> ``` #### The K combinator A very simple control structure (one might also call it a result dispatcher) is the **K combinator**, which is almost terribly simple: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc K {a b} {return $a} ``` ```{=html} </div> ``` It can be used in all situations where you want to deliver a result that is not the last. For instance, reading a file in one go: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc readfile filename { set f [open $filename] set data [read $f] close $f return $data } ``` ```{=html} </div> ``` can be simplified, without need for the *data* variable, to: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc readfile filename { K [read [set f [open $filename]]] [close $f] } ``` ```{=html} </div> ``` Another example, popping a stack: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc pop _stack { upvar 1 $_stack stack K [lindex $stack end] [set stack [lrange $stack 0 end-1]] } ``` ```{=html} </div> ``` This is in some ways similar to LISP\'s PROG1 construct: evaluate the contained expressions, and return the result of the first one. ### Rational numbers Rational numbers, a.k.a. fractions, can be thought of as pairs of integers {numerator denominator}, such that their \"real\" numerical value is numerator/denominator (and not in integer nor \"double\" division!). They can be more precise than any \"float\" or \"double\" numbers on computers, as those can\'t exactly represent any fractions whose denominator isn\'t a power of 2 --- consider which can not at any precision be exactly represented as floating-point number to base 2, nor as decimal fraction (base 10), even if bignum. An obvious string representation of a rational is of course \"n/d\". The following \"constructor\" does that, plus it normalizes the signs, reduces to lowest terms, and returns just the integer n if d==1: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc rat {n d} { if {!$d} {error "denominator can't be 0"} if {$d<0} {set n [- $n]; set d [- $d]} set g [gcd $n $d] set n [/ $n $g] set d [/ $d $g] expr {$d==1? $n: "$n/$d" } } ``` ```{=html} </div> ``` Conversely, this \"deconstructor\" splits zero or more rational or integer strings into num and den variables, such that \[ratsplit 1/3 a b\] assigns 1 to a and 3 to b: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc ratsplit args { foreach {r _n _d} $args { upvar 1 $_n n $_d d foreach {n d} [split $r /] break if {$d eq ""} {set d 1} } } #-- Four-species math on "rats": proc rat+ {r s} { ratsplit $r a b $s c d rat [+ [* $a $d] [* $c $b]] [* $b $d] } proc rat- {r s} { ratsplit $r a b $s c d rat [- [* $a $d] [* $c $b]] [* $b $d] } proc rat* {r s} { ratsplit $r a b $s c d rat [* $a $c] [* $b $d] } proc rat/ {r s} { ratsplit $r a b $s c d rat [* $a $d] [* $b $c] } ``` ```{=html} </div> ``` Arithmetical helper functions can be wrapped with func if they only consist of one call of *expr*: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc func {name argl body} {proc $name $argl [list expr $body]} #-- Greatest common denominator: func gcd {u v} {$u? [gcd [% $v $u] $u]: abs($v)} #-- Binary expr operators exported: foreach op {+ * / %} {func $op {a b} \$a$op\$b} #-- "-" can have 1 or 2 operands: func - {a {b ""}} {$b eq ""? -$a: $a-$b} #-- a little tester reports the unexpected: proc ? {cmd expected} { catch {uplevel 1 $cmd} res if {$res ne $expected} {puts "$cmd -> $res, expected $expected"} } #-- The test suite should silently pass when this file is sourced: ? {rat 42 6} 7 ? {rat 1 -2} -1/2 ? {rat -1 -2} 1/2 ? {rat 1 0} "denominator can't be 0" ? {rat+ 1/3 1/3} 2/3 ? {rat+ 1/2 1/2} 1 ? {rat+ 1/2 1/3} 5/6 ? {rat+ 1 1/2} 3/2 ? {rat- 1/2 1/8} 3/8 ? {rat- 1/2 1/-8} 5/8 ? {rat- 1/7 1/7} 0 ? {rat* 1/2 1/2} 1/4 ? {rat/ 1/4 1/4} 1 ? {rat/ 4 -6} -2/3 ``` ```{=html} </div> ``` ### Docstrings Languages like Lisp and Python have the docstring feature, where a string in the beginning of a function can be retrieved for on-line (or printed) documentation. Tcl doesn\'t have this mechanism built-in (and it would be hard to do it exactly the same way, because everything is a string), but a similar mechanism can easily be adopted, and it doesn\'t look bad in comparison: - Common Lisp: (documentation \'foo \'function) - Python: foo.\_\_doc\_\_ - Tcl: docstring foo If the docstring is written in comments at the top of a proc body, it is easy to parse it out. In addition, for all procs, even without docstring, you get the \"signature\" (proc name and arguments with defaults). The code below also serves as usage example: } ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc docstring procname { # reports a proc's args and leading comments. # Multiple documentation lines are allowed. set res "{usage: $procname [uplevel 1 [list info args $procname]]}" # This comment should not appear in the docstring foreach line [split [uplevel 1 [list info body $procname]] \n] { if {[string trim $line] eq ""} continue if ![regexp {\s*#(.+)} $line -> line] break lappend res [string trim $line] } join $res \n } proc args procname { # Signature of a proc: arguments with defaults set res "" foreach a [info args $procname] { if [info default $procname $a default] { lappend a $default } lappend res $a } set res } ``` ```{=html} </div> ``` Testing: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % docstring docstring usage: docstring procname reports a proc's args and leading comments. Multiple documentation lines are allowed. % docstring args usage: args procname Signature of a proc: arguments with defaults ``` ```{=html} </div> ``` ### Factorial Factorial (n!) is a popular function with super-exponential growth. Mathematically put, ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl 0! = 1 n! = n (n-1)! if n >0, else undefined ``` ```{=html} </div> ``` In Tcl, we can have it pretty similarly: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc fact n {expr {$n<2? 1: $n * [fact [incr n -1]]}} ``` ```{=html} </div> ``` But this very soon crosses the limits of integers, giving wrong results. A math book showed me the Stirling approximation to `n!` for large `n` (at Tcl\'s precisions, \"large\" is \> 20 \...), so I built that in: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc fact n {expr { $n<2? 1: $n>20? pow($n,$n)*exp(-$n)*sqrt(2*acos(-1)*$n): wide($n)*[fact [incr n -1]]} } ``` ```{=html} </div> ``` Just in case somebody needs approximated large factorials\... But for `n>143` we reach the domain limit of floating point numbers. In fact, the float limit is at `n>170`, so an intermediate result in the Stirling formula must have busted at 144. For such few values it is most efficient to just look them up in a pre-built table, as Tcllib\'s `math::factorial` does. ### How big is A4? Letter and Legal paper formats are popular in the US and other places. In Europe and elsewhere, the most widely used paper format is called A4. To find out how big a paper format is, one can measure an instance with a ruler, or look up appropriate documentation. The A formats can also be deduced from the following axioms: - A0 has an area of one square meter - `A(n)` has half the area of `A(n-1)` - The ratio between the longer and the shorter side of an A format is constant How much this ratio is, can easily be computed if we consider that `A(n)` is produced from `A(n-1)` by halving it parallel to the shorter side, so ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl 2a : b = b : a, 2 a2 = b2, b=sqrt(2) a, hence b : a = sqrt(2) : 1 ``` ```{=html} </div> ``` So here is my Tcl implementation, which returns a list of height and width in centimeters (10000 cm^2^ = 1 m^2^) with two fractional digits, which delivers a sufficient precision of 1/10 mm: } ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc paperA n { set w [expr {sqrt(10000/(pow(2,$n) * sqrt(2)))}] set h [expr {$w * sqrt(2)}] format "%.2f %.2f" $h $w } % paperA 4 29.73 21.02 ``` ```{=html} </div> ``` ### Bit vectors Here is a routine for querying or setting single bits in vectors, where bits are addressed by non-negative integers. Implementation is as a \"little-endian\" list of integers, where bits 0..31 are in the first list element, 32..63 in the second, etc. Usage: **bit** *varName position ?bitval?* If bitval is given, sets the bit at numeric position position to 1 if bitval `!=` 0, else to 0; in any case returns the bit value at specified position. If variable varName does not exist in caller\'s scope, it will be created; if it is not long enough, it will be extended to hold at least `$position+1` bits, e.g. bit foo 32 will turn foo into a list of two integers, if it was only one before. All bits are initialized to 0. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc bit {varName pos {bitval {}}} { upvar 1 $varName var if {![info exist var]} {set var 0} set element [expr {$pos/32}] while {$element >= [llength $var]} {lappend var 0} set bitpos [expr {1 << $pos%32}] set word [lindex $var $element] if {$bitval != ""} { if {$bitval} { set word [expr {$word | $bitpos}] } else { set word [expr {$word & ~$bitpos}] } lset var $element $word } expr {($word & $bitpos) != 0} } #---------------------- now testing... if {[file tail [info script]] == [file tail $argv0]} { foreach {test expected} { {bit foo 5 1} 1 {set foo} 32 {bit foo 32 1} {32 1} } { catch {eval $test} res puts $test:$res/$expected } } ``` ```{=html} </div> ``` This may be used for Boolean properties of numerically indexed sets of items. Example: An existence map of ZIP codes between 00000 and 99999 can be kept in a list of 3125 integers (where each element requires about 15 bytes overall), while implementing the map as an array would take 100000 \* 42 bytes in worst case, but still more than a bit vector if the population isn\'t extremely sparse --- in that case, a list of 1-bit positions, retrieved with `lsearch`, might be more efficient in memory usage. Runtime of bit vector accesses is constant, except when a vector has to be extended to much larger length. Bit vectors can also be used to indicate set membership (set operations would run faster if processing 32 bits on one go with bitwise operators (`&`, `|`, `~`, `^`)) --- or pixels in a binary imary image, where each row could be implemented by a bitvector. Here\'s a routine that returns the numeric indices of all set bits in a bit vector: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc bits bitvec { set res {} set pos 0 foreach word $bitvec { for {set i 0} {$i<32} {incr i} { if {$word & 1<<$i} {lappend res $pos} incr pos } } set res } % bit foo 47 1 1 % bit foo 11 1 1 % set foo 2048 32768 % bits $foo 11 47 ``` ```{=html} </div> ``` **Sieve of Erastothenes**: The following procedure exercises the bit vector functions by letting bits represent integers, and unsetting all that are divisible. The numbers of the bits finally still set are supposed to be primes, and returned: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc sieve max { set maxroot [expr {sqrt($max)}] set primes [string repeat " 0xFFFFFFFF" [expr {($max+31)/32}]] bit primes 0 0; bit primes 1 0 for {set i [expr $max+1]} {$i<=(($max+31)/32)*32} {incr i} { bit primes $i 0 ;# mask out excess bits } for {set i 2} {$i<=$maxroot} {incr i} { if {[bit primes $i]} { for {set j [expr $i<<1]} {$j<=$max} {incr j $i} { bit primes $j 0 } } } bits $primes } % time {set res [sieve 10000]} 797000 microseconds per iteration ``` ```{=html} </div> ``` Here\'s code to count the number of 1-bits in a bit vector, represented as an integer list. It does so by adding the values of the hex digits: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc bitcount intlist { array set bits { 0 0 1 1 2 1 3 2 4 1 5 2 6 2 7 3 8 1 9 2 a 2 b 3 c 2 d 3 e 3 f 4 } set sum 0 foreach int $intlist { foreach nybble [split [format %x $int] ""] { incr sum $bits($nybble) } } set sum } ``` ```{=html} </div> ``` ### Stacks and queues Stacks and queues are containers for data objects with typical access methods: - push: add one object to the container - pop: retrieve and remove one object from the container In Tcl it is easiest to implement stacks and queues with lists, and the push method is most naturally *lappend*, so we only have to code a single generic line for all stacks and queues: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl interp alias {} push {} lappend ``` ```{=html} </div> ``` It is pop operations in which stacks, queues, and priority queues differ: - in a stack, the most recently pushed object is retrieved and removed (last in first out, LIFO) - in a (normal) queue, it is the least recently pushed object (first in first out, FIFO) - in a priority queue, the object with the highest priority comes first. Priority (a number) has to be assigned at pushing time --- by pushing a list of two elements, the item itself and the priority, e.g.. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl push toDo [list "go shopping" 2] push toDo {"answer mail" 3} push toDo {"Tcl coding" 1} ;# most important thing to do ``` ```{=html} </div> ``` In a frequent parlage, priority 1 is the \"highest\", and the number increases for \"lower\" priorities --- but you could push in an item with 0 for \"ultrahigh\" ;-) Popping a stack can be done like this: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc pop name { upvar 1 $name stack set res [lindex $stack end] set stack [lrange $stack 0 end-1] set res } ``` ```{=html} </div> ``` Popping a queue is similarly structured, but with so different details that I found no convenient way to factor out things: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc qpop name { upvar 1 $name queue set res [lindex $queue 0] set queue [lrange $queue 1 end] set res } ``` ```{=html} </div> ``` Popping a priority queue requires sorting out which item has highest priority. Sorting can be done when pushing, or when popping, and since our push is so nicely generic I prefer the second choice (as the number of pushs and pops should be about equal, it does not really matter). Tcl\'s lsort is stable, so items with equal priority will remain in the order in which they were queued: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc pqpop name { upvar 1 $name queue set queue [lsort -real -index 1 $queue] qpop queue ;# fall back to standard queue, now that it's sorted } ``` ```{=html} </div> ``` A practical application is e.g. in state space searching, where the kind of container of the to-do list determines the strategy: - stack is depth-first - (normal) queue is breadth-first - priority queue is any of the more clever ways: A\*, Greedy, \... **Recent-use lists:** A variation that can be used both in a stack or queue fashion is a list of values in order of their last use (which may come handy in an editor to display the last edited files, for instance). Here, pushing has to be done by dedicated code because a previous instance would have to be removed: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc rupush {listName value} { upvar 1 $listName list if {![info exist list]} {set list {}} set pos [lsearch $list $value] set list [lreplace $list $pos $pos] lappend list $value } % rupush tmp hello hello % rupush tmp world hello world % rupush tmp again hello world again % rupush tmp world hello again world ``` ```{=html} </div> ``` The first element is the least recently, the last the most recently used. Elements are not removed by the popping, but (if necessary) when re-pushing. (One might truncate the list at front if it gets too long). ### Functions Functions in Tcl are typically written with the *proc* command. But I notice more and more that, on my way to functional programming, my *proc* bodies are a single call to *expr* which does all the rest (often with the powerful `x?y:z` operator). So what about a thin abstraction (wrapper) around this recurring pattern? ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc func {name argl body} {proc $name $argl [list expr $body]} ``` ```{=html} </div> ``` (I might have called it fun as well\... it sure is.) That\'s all. A collateral advantage is that all expressions are braced, without me having to care. But to not make the page look so empty, here\'s some examples for func uses: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl func fac n {$n<2? 1: $n*[fac [incr n -1]]} func gcd {u v} {$u? [gcd [expr $v%$u] $u]: $v} func min {a b} {$a<$b? $a: $b} func sgn x {($x>0)-($x<0)} ;# courtesy rmax ``` ```{=html} </div> ``` Pity we have to make *expr* explicit again, in nested calls like in *gcd* \... But *func* isn\'t limited to math functions (which, especially when recursive, come out nice), but for *expr* uses in testing predicates as well: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl func atomar list {[lindex $list 0] eq $list} func empty list {[llength $list] == 0} func in {list element} {[lsearch -exact $list $element] >= 0} func limit {x min max} {$x<$min? $min: $x>$max? $max: $x} func ladd {list e} {[in $list $e]? $list: [lappend list $e]} ``` ```{=html} </div> ``` Exposing *expr* binary arithmetic operators as Tcl commands goes quite easy too: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl foreach op {+ * / %} {func $op {a b} "\$a $op \$b"} ``` ```{=html} </div> ``` For \"-\", we distinguish unary and binary form: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl func - {a {b ""}} {$b eq ""? -$a: $a-$b} ``` ```{=html} </div> ``` Having the modulo operator exposed, *gcd* now looks nicer: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl func gcd {u v} {$u? [gcd [% $v $u] $u]: abs($v)} ``` ```{=html} </div> ``` For unary not I prefer that name to \"!\", as it might also stand for factorial --- and see the shortest function body I ever wrote :\^) : ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl func not x {!$x} ``` ```{=html} </div> ``` Without big mention, functions implemented by recursion have a pattern for which func is well suited (see *fac* and *gcd* above). Another example is this integer range generator (starts from 1, and is inclusive, so `[iota1 5] == {1 2 3 4 5}`): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl func iota1 n {$n == 1? 1: [concat [iota1 [- $n 1]] $n]} ``` ```{=html} </div> ``` ### Experiments with Boolean functions \"NAND is not AND.\" Here are some Tcl codelets to demonstrate how all Boolean operations can be expressed in terms of the single NAND operator, which returns true if not both his two inputs are true (NOR would have done equally well). We have Boolean operators in *expr*, so here goes: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc nand {A B} {expr {!($A && $B)}} ``` ```{=html} </div> ``` The only unary operator NOT can be written in terms of nand: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc not {A} {nand $A $A} ``` ```{=html} </div> ``` .. and everything else can be built from them too: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc and {A B} {not [nand $A $B]} proc or {A B} {nand [not $A] [not $B]} proc nor {A B} {not [or $A $B]} proc eq {A B} {or [and $A $B] [nor $A $B]} proc ne {A B} {nor [and $A $B] [nor $A $B]} ``` ```{=html} </div> ``` Here\'s some testing tools --- to see whether an implementation is correct, look at its truth table, here done as the four results for A,B combinations 0,0 0,1 1,0 1,1 --- side note: observe how easily functions can be passed in as arguments: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc truthtable f { set res {} foreach A {0 1} { foreach B {0 1} { lappend res [$f $A $B] } } set res } % truthtable and 0 0 0 1 % truthtable nand 1 1 1 0 % truthtable or 0 1 1 1 % truthtable nor 1 0 0 0 % truthtable eq 1 0 0 1 ``` ```{=html} </div> ``` To see how efficient the implementation is (in terms of NAND units used), try this, which relies on the fact that Boolean functions contain no lowercase letters apart from the operator names: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc nandcount f { regsub -all {[^a-z]} [info body $f] " " list set nums [string map {nand 1 not 1 and 2 nor 4 or 3 eq 6} $list] expr [join $nums +] } ``` ```{=html} </div> ``` As a very different idea, having nothing to do with NAND as elementary function, the following generic code \"implements\" Boolean functions very intuitively, by just giving their truth table for look-up at runtime: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc booleanFunction {truthtable a b} { lindex $truthtable [expr {!!$a+!!$a+!!$b}] } interp alias {} and {} booleanFunction {0 0 0 1} interp alias {} or {} booleanFunction {0 1 1 1} interp alias {} nand {} booleanFunction {1 1 1 0} ``` ```{=html} </div> ``` ### Solving cryptarithms Cryptarithms are puzzles where digits are represented by letters, and the task is to find out which. The following \"General Problem Solver\" (for small values of General) uses heavy metaprogramming: it - builds up a nest of foreachs suiting the problem, - quick kills (with continue) to force unique values for the variables, and - returns the first solution found, or else an empty string: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc solve {problem {domain0 {0 1 2 3 4 5 6 7 8 9}}} { set vars [lsort -u [split [regsub -all {[^A-Z]} $problem ""] ""]] set map {= ==} set outers {} set initials regexp -all -inline {[^A-Z} /$problem] set pos [lsearch $domain0 0] set domain1 [lreplace $domain0 $pos $pos] foreach var $vars { append body "foreach $var \$domain[expr [lsearch $initials $var]>=0] \{\n" lappend map $var $$var foreach outer $outers { append body "if {$$var eq $$outer} continue\n" } lappend outers $var append epilog \} } set test [string map $map $problem] append body "if {\[expr $test\]} {return \[subst $test\]}" $epilog if 1 $body } ``` ```{=html} </div> ``` This works fine on some well-known cryptarithms: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % solve SEND+MORE=MONEY 9567+1085==10652 % solve SAVE+MORE=MONEY 9386+1076==10462 % solve YELLOW+YELLOW+RED=ORANGE 143329+143329+846==287504 ``` ```{=html} </div> ``` ### Database experiments #### A simple array-based database There are lots of complex databases around. Here I want to explore how a database can be implemented in the Tcl spirit of simplicity, and how far that approach takes us. Consider the following model: - A database is a set of records - A record is a nonempty set of fields with a unique ID - A field is a pair of tag and nonempty value, both being strings Fields may well be implemented as array entries, so we could have an array per record, or better one array for the whole database, where the key is composed of ID and tag. Unique IDs can be had by just counting up (incrementing the highest ID so far). The process of creating a simple database consists only of setting an initial value for the ID: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set db(lastid) 0 ``` ```{=html} </div> ``` Let\'s consider a library application for an example. Adding a book to the database can be simply done by ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set id [incr db(lastid)] set db($id,author) "Shakespeare, William" set db($id,title) "The Tempest" set db($id,printed) 1962 set db($id,label) S321-001 ``` ```{=html} </div> ``` Note that, as we never specified what fields a record shall contain, we can add whatever we see fit. For easier handling, it\'s a good idea to classify records somehow (we\'ll want to store more than books), so we add ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set db($id,isa) book ``` ```{=html} </div> ``` Retrieving a record is as easy as this (though the fields come in undefined order): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl array get db $id,* ``` ```{=html} </div> ``` and deleting a record is only slightly more convolved: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl foreach i [array names db $id,*] {unset db($i)} ``` ```{=html} </div> ``` or, even easier and faster from Tcl 8.3 on: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl array unset db $id,* ``` ```{=html} </div> ``` Here\'s how to get a \"column\", all fields of a given tag: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl array get db *,title ``` ```{=html} </div> ``` But real columns may have empty fields, which we don\'t want to store. Retrieving fields that may not physically exist needs a tolerant access function: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc db'get {_db id field} { upvar $_db db if {[array names db $id,$field]=="$id,$field"} { return $db($id,$field) } else {return ""} } ``` ```{=html} </div> ``` In a classical database we have to define tables: which fields of what type and of which width. Here we can do what we want, even retrieve which fields we have used so far (using a temporary array to keep track of field names): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc db'fields {_db} { upvar $_db db foreach i [array names db *,*] { set tmp([lindex [split $i ,] 1]) "" } lsort [array names tmp] } ``` ```{=html} </div> ``` Searching for records that meet a certain condition can be done sequentially. For instance, we want all books printed before 1980: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl foreach i [array names *,printed] { if {$db($i)<1980} { set id [lindex [split $i ,] 0] puts "[db'get db $id author]: [db'get db $id title] $db($i)" } } ``` ```{=html} </div> ``` We might also store our patrons in the same database (here in a different style): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set i [incr $db(lastid)] array set db [list $i,name "John F. Smith" $i,tel (123)456-7890 $i,isa patron} ``` ```{=html} </div> ``` Without a concept of \"tables\", we can now introduce structures like in relational databases. Assume John Smith borrows \"The Tempest\". We have the patron\'s and book\'s ID in variables and do double bookkeeping: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl lappend db($patron,borrowed) $book ;# might have borrowed other books set db($book,borrower) $patron set db($book,dueback) 2001-06-12 ``` ```{=html} </div> ``` When he returns the book, the process is reversed: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set pos [lsearch $db($patron,borrowed) $book] set db($patron,borrowed) [lreplace $db($patron,borrowed) $pos $pos] unset db($book,borrower) ;# we're not interested in empty fields unset db($book,dueback) ``` ```{=html} </div> ``` The dueback field (`%Y-%M-%d` format is good for sorting and comparing) is useful for checking whether books have not been returned in time: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set today [clock format [clock seconds] -format %Y-%M-%d]] foreach i [array names db *,dueback] { if {$db($i)<$today} { set book [lindex [split $i ,] 0] ;# or: set book [idof $i] - see below set patron $db($book,borrower) #write a letter puts "Dear $db($patron,name), " puts "please return $db($book,title) which was due on\ $db($book,dueback)" } } ``` ```{=html} </div> ``` Likewise, parts of the accounting (e.g. orders to, and bills from, booksellers) can be added with little effort, and cross-related also to external files (just set the value to the filename). *Indexes:* As shown, we can retrieve all data by sequential searching over array names. But if the database grows in size, it\'s a good idea to create indexes which cross-reference tags and values to IDs. For instance, here\'s how to make an authors\' index in four lines: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl foreach i [array names db *,author] { set book [lindex [split $i ,] 0] lappend db(author=[string toupper $db($i)]) $book } # and then.. foreach i [lsort [array names db author=SHAK*]] { puts "[lindex [split $i =] 1]:" ;# could be wrapped as 'valueof' foreach id $db($i) { puts "[db'get db $id title] - [db'get db $id label]" } } ``` ```{=html} </div> ``` gives us a books list of all authors matching the given glob pattern (we reuse Tcl\'s functionality, instead of reinventing it\...). Indexes are useful for repeated information that is likely to be searched. Especially, indexing the isa field allows iterating over \"tables\" (which we still don\'t explicitly have!;-): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl regsub -all isa= [array names db isa=*] "" tables foreach patron $db(isa=patron) {...} ``` ```{=html} </div> ``` And beyond industry-standard SQL, we can search multiple indices in one query: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl array names db *=*MARK* ``` ```{=html} </div> ``` gives you all (case-independent) occurrences of MARK, be it in patron\'s names, book\'s authors or titles. As versatile as good old grep\... **Persistence:** Databases are supposed to exist between sessions, so here\'s how to save a database to a file: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set fp [open Library.db w] puts $fp [list array set db [array get db]] close $fp ``` ```{=html} </div> ``` and loading a database is even easier (on re-loading, better unset the array before): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl source Library.db ``` ```{=html} </div> ``` If you use characters outside your system encoding (no problem to write Japanese book titles in Kanji), you\'ll have to fconfigure (e.g -encoding utf-8) on saving and loading, but that\'s just a few more LOC. Saving also goes a good way to what is ceremonially called \"committing\" (you\'ll need write-locking for multi-user systems), while loading (without saving before) might be called a \"one-level rollback\", where you want to discard your latest changes. Notice that so far we have only defined one short proc, all other operations were done with built-in Tcl commands only. For clearer code, it is advisable to factor out frequent operations into procs, e.g. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc idof {index} {lindex [split $index ,] 0} proc db'add {_db data} { upvar $_db db set id [incr db(lastid)] foreach {tag value} $data {set db($id,$tag) $value} # might also update indexes here } proc db'tablerow {_db id tags} { upvar $_db db set res {} foreach tag $tags {lappend res [db'get db $id $tag]} set res } ``` ```{=html} </div> ``` Of course, with growing databases we may reach memory limits: arrays need some extra storage for administration. On the other hand, the present approach is pretty economic, since it does not use field widths (all strings are \"shrink-wrapped\"), and omits empty fields, while at the same time allowing to add whatever fields you wish. A further optimization could be to tally value strings, and replace the frequent ones with \"`@$id`\", where `db(@$id)` holds the value once, and only db\'get has to be adapted to redirect the query. Also, memory limits on modern computers are somewhere up high\... so only at some time in the future you might have (but maybe not want) to change to a complex database ;-) **On the limits:** Tcl arrays may get quite large (one app was reported to store 800000 keys in Greek characters), and at some point enumerating all keys with array names db (which produces one long list) may exceed your available memory, causing the process to swap. In that situation, you can fall back to the (otherwise slower, and uglier) use of a dedicated iterator: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set search [array startsearch db] while {[array anymore db $search]} { set key [array nextelement db $search] # now do something with db($key) - but see below! } array donesearch db $search ``` ```{=html} </div> ``` But neither can you filter the keys you will get with a glob pattern, nor may you add or delete array elements in the loop --- the search will be immediately terminated. #### Tables as lists of lists Tables are understood here as rectangular (matrix) arrangements of data in rows (one row per \"item\"/\"record\") and columns (one column per \"field\"/\"element\"). They are for instance the building blocks of relational databases and spreadsheets. In Tcl, a sensible implementation for compact data storage would be as a list of lists. This way, they are \"pure values\" and can be passed e.g. through functions that take a table and return a table. No con-/destructors are needed, in contrast to the heavierweight matrix in Tcllib. I know there are many table implementations in Tcl, but like so often I wanted to build one \"with my bare hands\" and as simple as possible. As you see below, many functionalities can be \"implemented\" by just using Tcl\'s list functions. A nice table also has a header line, that specifies the field names. So to create such a table with a defined field structure, but no contents yet, one just assigns the header list: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set tbl { {firstname lastname phone}} ``` ```{=html} </div> ``` Note the double bracing, which makes sure tbl is a 1-element list. Adding \"records\" to the table is as easy as ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl lappend tbl {John Smith (123)456-7890} ``` ```{=html} </div> ``` Make sure the fields (cells) match those in the header. Here single bracing is correct. If a field content contains spaces, it must be quoted or braced too: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl lappend tbl {{George W} Bush 234-5678} ``` ```{=html} </div> ``` Sorting a table can be done with lsort -index, taking care that the header line stays on top: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc tsort args { set table [lindex $args end] set header [lindex $table 0] set res [eval lsort [lrange $args 0 end-1] [list [lrange $table 1 end]]] linsert $res 0 $header } ``` ```{=html} </div> ``` Removing a row (or contiguous sequence of rows) by numeric index is a job for lreplace: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set tbl [lreplace $tbl $from $to] ``` ```{=html} </div> ``` Simple printing of such a table, a row per line, is easy with ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl puts [join $tbl \n] ``` ```{=html} </div> ``` Accessing fields in a table is more fun with the field names than the numeric indexes, which is made easy by the fact that the field names are in the first row: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc t@ {tbl field} {lsearch [lindex $tbl 0] $field} % t@ $tbl phone 2 ``` ```{=html} </div> ``` You can then access cells: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl puts [lindex $tbl $rownumber [t@ $tbl lastname]] ``` ```{=html} </div> ``` and replace cell contents like this: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl lset tbl $rownumber [t@ $tbl phone] (222)333-4567 ``` ```{=html} </div> ``` Here is how to filter a table by giving pairs of field name and glob-style expression --- in addition to the header line, all rows that satisfy at least one of those come through (you can force AND behavior by just nesting such calls): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc trows {tbl args} { set conditions {} foreach {field condition} $args { lappend conditions [t@ $tbl $field] $condition } set res [list [lindex $tbl 0]] foreach row [lrange $tbl 1 end] { foreach {index condition} $conditions { if [string match $condition [lindex $row $index]] { lappend res $row break; # one hit is sufficient } } } set res } % trows $tbl lastname Sm* {firstname lastname} phone {John Smith (123)456-7890} ``` ```{=html} </div> ``` This filters (and, if wanted, rearranges) columns, sort of what is called a \"view\": ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc tcols {tbl args} { set indices {} foreach field $args {lappend indices [t@ $tbl $field]} set res {} foreach row $tbl { set newrow {} foreach index $indices {lappend newrow [lindex $row $index]} lappend res $newrow } set res } ``` ```{=html} </div> ``` ### Programming Languages Laboratory In the following few chapters you\'ll see how easy it is to emulate or explore other programming languages with Tcl. #### GOTO: a little state machine The GOTO \"jumping\" instruction is considered harmful in programming for many years now, but still it might be interesting to experiment with. Tcl has no *goto* command, but it can easily be created. The following code was created in the Tcl chatroom, instigated by the quote: \"A computer is a state machine. Threads are for people who can\'t program state machines.\" So here is one model of a state machine in ten lines of code. The \"machine\" itself takes a list of alternating labels and state code; if a state code does not end in a goto or break, the same state will be repeated as long as not left, with goto or break (implicit endless loop). The goto command is defined \"locally\", and deleted after leaving the state machine --- it is not meaningfully used outside of it. Execution starts at the first of the states. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc statemachine states { array set S $states proc goto label { uplevel 1 set this $label return -code continue } set this [lindex $states 0] while 1 {eval $S($this)} rename goto {} } ``` ```{=html} </div> ``` Testing: a tiny state machine that greets you as often as you wish, and ends if you only hit on the \"how often?\" question: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl statemachine { 1 { puts "how often?" gets stdin nmax if {$nmax eq ""} {goto 3} set n 0 goto 2 } 2 { if {[incr n] > $nmax} {goto 1} puts "hello" } 3 {puts "Thank you!"; break} } ``` ```{=html} </div> ``` #### Playing Assembler In this weekend fun project to emulate machine language, I picked those parts of Intel 8080A/8085 Assembler (because I had a detailed reference handy) that are easily implemented and still somehow educational (or nostalgic ;-). Of course this is no real assembler. The memory model is constant-size instructions (strings in array elements), which are implemented as Tcl procs. So an \"assembler\" program in this plaything will run even slower than in pure Tcl, and consume more memory --- while normally you associate speed and conciseness with \"real\" assembler code. But it looks halfway like the real thing: you get sort of an assembly listing with symbol table, and can run it --- I\'d hardly start writing an assembler in C, but in Tcl it\'s fun for a sunny Sunday afternoon\... } ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl namespace eval asm { proc asm body { variable mem catch {unset mem} ;# good for repeated sourcing foreach line [split $body \n] { foreach i {label op args} {set $i ""} regexp {([^;]*);} $line -> line ;# strip off comments regexp {^ *(([A-Z0-9]+):)? *([A-Z]*) +(.*)} [string toupper $line]\ -> - label op args puts label=$label,op=$op,args=$args if {$label!=""} {set sym($label) $PC} if {$op==""} continue if {$op=="DB"} {set mem($PC) [convertHex $args]; incr PC; continue} if {$op=="EQU"} {set sym($label) [convertHex $args]; continue} if {$op=="ORG"} {set PC [convertHex $args]; continue} regsub -all ", *" $args " " args ;# normalize commas set mem($PC) "$op $args" incr PC } substituteSymbols sym dump sym } proc convertHex s { if [regexp {^([0-9A-F]+)H$} [string trim $s] -> s] {set s [expr 0x$s]} set s } proc substituteSymbols {_sym} { variable mem upvar $_sym sym foreach i [array names mem] { set tmp [lindex $mem($i) 0] foreach j [lrange $mem($i) 1 end] { if {[array names sym $j] eq $j} {set j $sym($j)} lappend tmp $j } set mem($i) $tmp } } proc dump {_sym} { variable mem upvar $_sym sym foreach i [lsort -integer [array names mem]] { puts [format "%04d %s" $i $mem($i)] } foreach i [lsort [array names sym]] { puts [format "%-10s: %04x" $i $sym($i)] } } proc run { {pc 255}} { variable mem foreach i {A B C D E Z} {set ::$i 0} while {$pc>=0} { incr pc #puts "$mem($pc)\tA:$::A B:$::B C:$::C D:$::D E:$::E Z:$::Z" eval $mem($pc) } } #----------------- "machine opcodes" implemented as procs proc ADD {reg reg2} {set ::Z [incr ::$reg [set ::$reg2]]} proc ADI {reg value} {set ::Z [incr ::$reg $value]} proc CALL {name} {[string tolower $name] $::A} proc DCR {reg} {set ::Z [incr ::$reg -1]} proc INR {reg} {set ::Z [incr ::$reg]} proc JMP where {uplevel 1 set pc [expr $where-1]} proc JNZ where {if $::Z {uplevel 1 JMP $where}} proc JZ where {if !$::Z {uplevel 1 JMP $where}} proc MOV {reg adr} {variable mem; set ::$reg $mem($adr)} proc MVI {reg value} {set ::$reg $value} } ``` ```{=html} </div> ``` Now testing: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` asm asm::asm { org 100 ; the canonical start address in CP/M jmp START ; idiomatic: get over the initial variable(s) DONE: equ 0 ; warm start in CP/M ;-) MAX: equ 5 INCR: db 2 ; a variable (though we won't vary it) ;; here we go... START: mvi c,MAX ; set count limit mvi a,0 ; initial value mov b,INCR LOOP: call puts ; for now, fall back to Tcl for I/O inr a add a,b ; just to make adding 1 more complicated dcr c ; counting down.. jnz LOOP ; jump on non-zero to LOOP jmp DONE ; end of program end } ``` ```{=html} </div> ``` The `mov b,INCR` part is an oversimplification. For a real 8080, one would have to say ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` asm LXI H,INCR ; load double registers H+L with the address INCR MOV B,M ; load byte to register B from the address pointed to in HL ``` ```{=html} </div> ``` Since the pseudo-register M can also be used for writing back, it cannot be implemented by simply copying the value. Rather, one could use read and write traces on variable M, causing it to load from, or store to, mem(\$HL). Maybe another weekend\... #### Functional programming (Backus 1977) John Backus turned 80 these days. For creating FORTRAN and the BNF style of language description, he received the ACM Turing Award in 1977. In his Turing Award lecture, *Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs. (Comm. ACM 21.8, Aug. 1978, 613-641)* he developed an amazing framework for functional programming, from theoretical foundations to implementation hints, e.g. for installation, user privileges, and system self-protection. In a nutshell, his FP system comprises - a set O of objects (atoms or sequences) - a set F of functions that map objects into objects (`f : O |-> O`} - an operation, application (very roughly, eval) - a set FF of functional forms, used to combine functions or objects to form new functions in F - a set D of definitions that map names to functions in F I\'m far from having digested it all, but like so often, interesting reading prompts me to do Tcl experiments, especially on weekends. I started with Backus\' first Functional Program example, ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl Def Innerproduct = (Insert +) o (ApplyToAll x) o Transpose ``` ```{=html} </div> ``` and wanted to bring it to life --- slightly adapted to Tcl style, especially by replacing the infix operator \"o\" with a Polish prefix style: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl Def Innerproduct = {o {Insert +} {ApplyToAll *} Transpose} ``` ```{=html} </div> ``` Unlike procs or lambdas, more like APL or RPN, this definition needs no variables --- it declares (from right to left) what to do with the input; the result of each step is the input for the next step (to the left of it). In an RPN language, the example might look like this: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl /Innerproduct {Transpose * swap ApplyToAll + swap Insert} def ``` ```{=html} </div> ``` which has the advantage that execution goes from left to right, but requires some stack awareness (and some swaps to set the stack right ;\^) Implementing Def, I took an easy route by just creating a proc that adds an argument and leaves it to the \"functional\" to do the right thing (with some quoting heaven :-) } ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc Def {name = functional} { proc $name x "\[$functional\] \$x" } ``` ```{=html} </div> ``` For functional composition, where, say for two functions f and g, ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl [{o f g} $x] == [f [g $x]] ``` ```{=html} </div> ``` again a proc is created that does the bracket nesting: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc o args { set body return foreach f $args {append body " \[$f"} set name [info level 0] proc $name x "$body \$x [string repeat \] [llength $args]]" set name } ``` ```{=html} </div> ``` Why Backus used Transpose on the input, wasn\'t first clear to me, but as he (like we Tclers) represents a matrix as a list of rows, which are again lists (also known as vectors), it later made much sense to me. This code for transposing a matrix uses the fact that variable names can be any string, including those that look like integers, so the column contents are collected into variables named 0 1 2 \... and finally turned into the result list: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc Transpose matrix { set cols [iota [llength [lindex $matrix 0]]] foreach row $matrix { foreach element $row col $cols { lappend $col $element } } set res {} foreach col $cols {lappend res [set $col]} set res } ``` ```{=html} </div> ``` An integer range generator produces the variable names, e.g `iota 3 => {0 1 2}` ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc iota n { set res {} for {set i 0} {$i<$n} {incr i} {lappend res $i} set res } #-- This "functional form" is mostly called map in more recent FP: proc ApplyToAll {f list} { set res {} foreach element $list {lappend res [$f $element]} set res } ``` ```{=html} </div> ``` \...and Insert is better known as fold, I suppose. My oversimple implementation assumes that the operator is one that expr understands: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc Insert {op arguments} {expr [join $arguments $op]} #-- Prefix multiplication comes as a special case of this: interp alias {} * {} Insert * #-- Now to try out the whole thing: Def Innerproduct = {o {Insert +} {ApplyToAll *} Transpose} puts [Innerproduct {{1 2 3} {6 5 4}}] ``` ```{=html} </div> ``` which returns 28 just as Dr. Backus ordered (= 1\*6 + 2\*5 + 3\*4). Ah, the joys of weekend Tcl\'ing\... --- and belatedly, Happy Birthday, John! :) Another example, cooked up by myself this time, computes the average of a list. For this we need to implement the construction operator, which is sort of inverse mapping --- while mapping a function over a sequence of inputs produces a sequence of outputs of that function applied to each input, Backus\' construction maps a sequence of functions over one input to produce a sequence of results of each function to that input, e.g. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl f,g == <f(x),g(x)> ``` ```{=html} </div> ``` Of course I can\'t use circumfix brackets as operator name, so let\'s call it constr: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc constr args { set functions [lrange $args 0 end-1] set x [lindex $args end] set res {} foreach f $functions {lappend res [eval $f [list $x]]} set res } #-- Testing: Def mean = {o {Insert /} {constr {Insert +} llength}} puts [mean {1 2 3 4 5}] ``` ```{=html} </div> ``` which returns correctly 3. However, as integer division takes place, it would be better to make that ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc double x {expr {double($x)}} Def mean = {o {Insert /} {constr {Insert +} dlength}} Def dlength = {o double llength} puts [mean {1 2 3 4}] ``` ```{=html} </div> ``` giving the correct result 2.5. However, the auxiliary definition for dlength cannot be inlined into the definition of mean --- so this needs more work\... But this version, that maps double first, works: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl Def mean = {o {Insert /} {constr {Insert +} llength} {ApplyToAll double}} ``` ```{=html} </div> ``` One more experiment, just to get the feel: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl Def hypot = {o sqrt {Insert +} {ApplyToAll square}} Def square = {o {Insert *} {constr id id}} proc sqrt x {expr {sqrt($x)}} proc id x {set x} puts [hypot {3 4}] ``` ```{=html} </div> ``` which gives 5.0. Compared to an RPN language, hypot would be ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl /hypot {dup * swap dup * + sqrt} def ``` ```{=html} </div> ``` which is shorter and simpler, but meddles more directly with the stack. An important functional form is the conditional, which at Backus looks like ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text p1 -> f; p2 -> g; h ``` ```{=html} </div> ``` meaning, translated to Tcl, ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl if {[p1 $x]} then {f $x} elseif {[p2 $x]} then {g $x} else {h $x} ``` ```{=html} </div> ``` Let\'s try that, rewritten Polish-ly to: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl cond p1 f p2 g h proc cond args { set body "" foreach {condition function} [lrange $args 0 end-1] { append body "if {\[$condition \$x\]} {$function \$x} else" } append body " {[lindex $args end] \$x}" set name [info level 0] proc $name x $body set name } #-- Testing, with K in another role as Konstant function :) Def abs = {cond {> 0} -- id} proc > {a b} {expr {$a>$b}} proc < {a b} {expr {$a<$b}} proc -- x {expr -$x} puts [abs -42],[abs 0],[abs 42] Def sgn = {cond {< 0} {K 1} {> 0} {K -1} {K 0}} proc K {a b} {set a} puts [sgn 42]/[sgn 0]/[sgn -42] #--Another famous toy example, reading a file's contents: Def readfile = {o 1 {constr read close} open} #--where Backus' selector (named just as integer) is here: proc 1 x {lindex $x 0} ``` ```{=html} </div> ``` #### Reusable functional components Say you want to make a multiplication table for an elementary school kid near you. Easily done in a few lines of Tcl code: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc multable {rows cols} { set res "" for {set i 1} {$i <= $rows} {incr i} { for {set j 1} {$j <= $cols} {incr j} { append res [format %4d [expr {$i*$j}]] } append res \n } set res } ``` ```{=html} </div> ``` The code does not directly puts its results, but returns them as a string --- you might want to do other things with it, e.g. save it to a file for printing. Testing: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % multable 3 10 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 ``` ```{=html} </div> ``` Or print the result directly from wish: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl catch {console show} puts "[multable 3 10]" ``` ```{=html} </div> ``` Here\'s a different way to do it à la functional programming: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc multable2 {rows cols} { formatMatrix %4d [outProd * [iota 1 $rows] [iota 1 $cols]] } ``` ```{=html} </div> ``` The body is nice and short, but consists of all unfamiliar commands. They are however better reusable than the *multable* proc above. The first formats a matrix (a list of lists to Tcl) with newlines and aligned columns for better display: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc formatMatrix {fm matrix} { join [lmap row $matrix {join [lmap i $row {format $fm $i}] ""}] \n } ``` ```{=html} </div> ``` Short again, and slightly cryptic, as is the \"outer product\" routine, which takes a function f and two vectors, and produces a matrix where f was applied to every pair of a x b --- in APL they had special compound operators for this job, in this case \"°.x\": ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc outProd {f a b} { lmap i $a {lmap j $b {$f $i $j}} } ``` ```{=html} </div> ``` Again, lmap (the collecting foreach) figures prominently, so here it is in all its simplicity: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc lmap {_var list body} { upvar 1 $_var var set res {} foreach var $list {lappend res [uplevel 1 $body]} set res } #-- We need multiplication from expr exposed as a function: proc * {a b} {expr {$a * $b}} #-- And finally, iota is an integer range generator: proc iota {from to} { set res {} while {$from <= $to} {lappend res $from; incr from} set res } ``` ```{=html} </div> ``` With these parts in place, we can see that *multable2* works as we want: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % multable2 3 10 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 ``` ```{=html} </div> ``` So why write six procedures, where one did the job already? A matter of style and taste, in a way --- *multable* is 10 LOC and depends on nothing but Tcl, which is good; *multable2* describes quite concisely what it does, and builds on a few other procs that are highly reusable. Should you need a unit matrix (where the main diagonal is 1, and the rest is 0), just call outProd with a different function (equality, ==): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % outProd == [iota 1 5] [iota 1 5] {1 0 0 0 0} {0 1 0 0 0} {0 0 1 0 0} {0 0 0 1 0} {0 0 0 0 1} ``` ```{=html} </div> ``` which just requires expr\'s equality to be exposed too: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc == {a b} {expr {$a == $b}} ``` ```{=html} </div> ``` One of the fascinations of functional programming is that one can do the job in a simple and clear way (typically a one-liner), while using a collection of reusable building-blocks like lmap and iota. And *formatMatrix* and *outProd* are so general that one might include them in some library, while the task of producing a multiplication table may not come up any more for a long time\... #### Modelling an RPN language Tcl follows strictly the Polish notation, where an operator or function always precedes its arguments. It is however easy to build an interpreter for a language in Reverse Polish Notation (RPN) like Forth, Postscript, or Joy, and experiment with it. The \"runtime engine\" is just called \"r\" (not to be confused with the R language), and it boils down to a three-way switch done for each word, in eleven lines of code: - \"tcl\" evaluates the top of stack as a Tcl script - known words in the `::C` array are recursively evaluated in \"r\" - other words are just pushed Joy\'s rich quoting for types (\[list\], {set}, \"string\", \'char) conflict with the Tcl parser, so lists in \"r\" are {braced} if their length isn\'t 1, and (parenthesized) if it is --- but the word shall not be evaluated now. This looks better to me than /slashing as in Postscript. As everything is a string, and to Tcl \"a\" is {a} is a , Joy\'s polymorphy has to be made explicit. I added converters between characters and integers, and between strings and lists (see the dictionary below). For Joy\'s sets I haven\'t bothered yet --- they are restricted to the domain 0..31, probably implemented with bits in a 32-bit word. Far as this is from Joy, it was mostly triggered by the examples in Manfred von Thun\'s papers, so I tongue-in-cheek still call it \"Pocket Joy\" --- it was for me, at last, on the iPaq\... The test suite at end should give many examples of what one can do in \"r\". } ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc r args { foreach a $args { dputs [info level]:$::S//$a if {$a eq "tcl"} { eval [pop] } elseif [info exists ::C($a)] { eval r $::C($a) } else {push [string trim $a ()]} } set ::S } ``` ```{=html} </div> ``` \# That\'s it. Stack (list) and Command array are global variables: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set S {}; unset C ``` ```{=html} </div> ``` #\-- A tiny switchable debugger: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc d+ {} {proc dputs s {puts $s}} proc d- {} {proc dputs args {}} d- ;#-- initially, debug mode off ``` ```{=html} </div> ``` Definitions are in Forth style --- \":\" as initial word, as they look much more compact than Joy\'s *DEFINE n == args;* ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc : {n args} {set ::C($n) $args} ``` ```{=html} </div> ``` *expr* functionality is exposed for binary operators and one-arg functions: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc 2op op { set t [pop] push [expr {[pop]} $op {$t}] } foreach op {+ - * / > >= != <= <} {: $op [list 2op $op] tcl} : = {2op ==} tcl proc 1f f {push [expr $f\([pop])]} foreach f {abs double exp int sqrt sin cos acos tan} {: $f [list 1f $f] tcl} interp alias {} pn {} puts -nonewline #----- The dictionary has all one-liners: : . {pn "[pop] "} tcl : .s {puts $::S} tcl : ' {push [scan [pop] %c]} tcl ;# char -> int : ` {push [format %c [pop]]} tcl ;# int -> char : and {2op &&} tcl : at 1 - swap {push [lindex [pop] [pop]]} tcl : c {set ::S {}} tcl ;# clear stack : choice {choice [pop] [pop] [pop]} tcl : cleave {cleave [pop] [pop] [pop]} tcl : cons {push [linsert [pop] 0 [pop]]} tcl : dup {push [set x [pop]] $x} tcl : dupd {push [lindex $::S end-1]} tcl : emit {pn [format %c [pop]]} tcl : even odd not : explode {push [split [pop] ""]} tcl ;# string -> char list : fact 1 (*) primrec : filter split swap pop : first {push [lindex [pop] 0]} tcl : fold {rfold [pop] [pop] [pop]} tcl : gcd swap {0 >} {swap dupd rem swap gcd} (pop) ifte : has swap in : i {eval r [pop]} tcl : ifte {rifte [pop] [pop] [pop]} tcl : implode {push [join [pop] ""]} tcl ;# char list -> string : in {push [lsearch [pop] [pop]]} tcl 0 >= : map {rmap [pop] [pop]} tcl : max {push [max [pop] [pop]]} tcl : min {push [min [pop] [pop]]} tcl : newstack c : not {1f !} tcl : odd 2 rem : of swap at : or {2op ||} tcl : pop (pop) tcl : pred 1 - : primrec {primrec [pop] [pop] [pop]} tcl : product 1 (*) fold : qsort (lsort) tcl : qsort1 {lsort -index 0} tcl : rem {2op %} tcl : rest {push [lrange [pop] 1 end]} tcl : reverse {} swap (swons) step : set {set ::[pop] [pop]} tcl : $ {push [set ::[pop]]} tcl : sign {0 >} {0 <} cleave - : size {push [llength [pop]]} tcl : split {rsplit [pop] [pop]} tcl : step {step [pop] [pop]} tcl : succ 1 + : sum 0 (+) fold : swap {push [pop] [pop]} tcl : swons swap cons : xor != ``` ```{=html} </div> ``` Helper functions written in Tcl: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc rifte {else then cond} { eval r dup $cond eval r [expr {[pop]? $then: $else}] } proc choice {z y x} { push [expr {$x? $y: $z}] } proc cleave { g f x} { eval [list r $x] $f [list $x] $g } proc max {x y} {expr {$x>$y?$x:$y}} proc min {x y} {expr {$x<$y? $x:$y}} proc rmap {f list} { set res {} foreach e $list { eval [list r $e] $f lappend res [pop] } push $res } proc step {f list} { foreach e $list {eval [list r ($e)] $f} } proc rsplit {f list} { foreach i {0 1} {set $i {}} foreach e $list { eval [list r $e] $f lappend [expr {!![pop]}] $e } push $0 $1 } proc primrec {f init n} { if {$n>0} { push $n while {$n>1} { eval [list r [incr n -1]] $f } } else {push $init} } proc rfold {f init list} { push $init foreach e $list {eval [list r $e] $f} } #------------------ Stack routines proc push args { foreach a $args {lappend ::S $a} } proc pop {} { if [llength $::S] { K [lindex $::S end] \ [set ::S [lrange $::S 0 end-1]] } else {error "stack underflow"} } proc K {a b} {set a} #------------------------ The test suite: proc ? {cmd expected} { catch {uplevel 1 $cmd} res if {$res ne $expected} {puts "$cmd->$res, not $expected"} } ? {r 2 3 +} 5 ? {r 2 *} 10 ? {r c 5 dup *} 25 : sqr dup * : hypot sqr swap sqr + sqrt ? {r c 3 4 hypot} 5.0 ? {r c {1 2 3} {dup *} map} { {1 4 9}} ? {r size} 3 ? {r c {2 5 3} 0 (+) fold} 10 ? {r c {3 4 5} product} 60 ? {r c {2 5 3} 0 {dup * +} fold} 38 ? {r c {1 2 3 4} dup sum swap size double /} 2.5 ? {r c {1 2 3 4} (sum) {size double} cleave /} 2.5 : if0 {1000 >} {2 /} {3 *} ifte ? {r c 1200 if0} 600 ? {r c 600 if0} 1800 ? {r c 42 sign} 1 ? {r c 0 sign} 0 ? {r c -42 sign} -1 ? {r c 5 fact} 120 ? {r c 1 0 and} 0 ? {r c 1 0 or} 1 ? {r c 1 0 and not} 1 ? {r c 3 {2 1} cons} { {3 2 1}} ? {r c {2 1} 3 swons} { {3 2 1}} ? {r c {1 2 3} first} 1 ? {r c {1 2 3} rest} { {2 3}} ? {r c {6 1 5 2 4 3} {3 >} filter} { {6 5 4}} ? {r c 1 2 {+ 20 * 10 4 -} i} {60 6} ? {r c 42 succ} 43 ? {r c 42 pred} 41 ? {r c {a b c d} 2 at} b ? {r c 2 {a b c d} of} b ? {r c 1 2 pop} 1 ? {r c A ' 32 + succ succ `} c ? {r c {a b c d} reverse} { {d c b a}} ? {r c 1 2 dupd} {1 2 1} ? {r c 6 9 gcd} 3 ? {r c true yes no choice} yes ? {r c false yes no choice} no ? {r c {1 2 3 4} (odd) split} { {2 4} {1 3}} ? {r c a {a b c} in} 1 ? {r c d {a b c} in} 0 ? {r c {a b c} b has} 1 ? {r c {a b c} e has} 0 ? {r c 3 4 max} 4 ? {r c 3 4 min} 3 ? {r c hello explode reverse implode} olleh : palindrome dup explode reverse implode = ? {r c hello palindrome} 0 ? {r c otto palindrome} 1 #-- reading (varname $) and setting (varname set) global Tcl vars set tv 42 ? {r c (tv) $ 1 + dup (tv) set} 43 ? {expr $tv==43} 1 ``` ```{=html} </div> ``` #### Tacit programming The J programming language is the \"blessed successor\" to APL, where \"every function is an infix or prefix operator\", `x?y` (dyadic) or `?y` (monadic), for `?` being any pre- or user-defined function). \"Tacit programming\" (*tacit*: implied; indicated by necessary connotation though not expressed directly) is one of the styles possible in J, and means coding by combining functions, without reference to argument names. This idea may have been first brought up in Functional programming (Backus 1977), if not in Forth and Joy, and it\'s an interesting simplification compared to the lambda calculus. For instance, here\'s a breathtakingly short J program to compute the mean of a list of numbers: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text mean=.+/%# ``` ```{=html} </div> ``` Let\'s chew this, byte by byte :) ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text =. is assignment to a local variable ("mean") which can be called +/%# is the "function body" + (dyadic) is addition / folds the operator on its left over the list on its right +/ hence being the sum of a list % (dyadic) is division, going double on integer arguments when needed # (monadic) is tally, like Tcl's [llength] resp. [string length] ``` ```{=html} </div> ``` Only implicitly present is a powerful function combinator called \"fork\". When J parses three operators in a row, gfh, where f is dyadic and g and h are monadic, they are combined like the following Tcl version does: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc fork {f g h x} {$f [$g $x] [$h $x]} ``` ```{=html} </div> ``` In other words, f is applied to the results of applying g and h to the single argument. Note that `+/` is considered one operator, which applies the \"adverb\" folding to the \"verb\" addition (one might well call it \"sum\"). When two operands occur together, the \"hook\" pattern is implied, which might in Tcl be written as: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc hook {f g x} {$f $x [$g $x]} ``` ```{=html} </div> ``` As KBK pointed out in the Tcl chatroom, the \"hook\" pattern corresponds to Schönfinkel/Curry\'s S combinator (see Hot Curry and Combinator Engine), while \"fork\" is called S\' there. Unlike in earlier years when I was playing APL, this time my aim was not to parse and emulate J in Tcl --- I expected hard work for a dubitable gain, and this is a weekend fun project after all. I rather wanted to explore some of these concepts and how to use them in Tcl, so that in slightly more verbose words I could code (and call) ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl Def mean = fork /. sum llength ``` ```{=html} </div> ``` following Backus\' FP language with the \"Def\" command. So let\'s get the pieces together. My \"Def\" creates an interp alias, which is a good and simple Tcl way to compose partial scripts (the definition, here) with one or more arguments, also known as \"currying\": ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc Def {name = args} {eval [list interp alias {} $name {}] $args} ``` ```{=html} </div> ``` The second parameter, \"=\", is for better looks only and evidently never used. Testing early and often is a virtue, as is documentation --- to make the following code snippets clearer, I tuned my little tester for better looks, so that the test cases in the source code also serve as well readable examples --- they look like comments but are code! The cute name \"e.g.\" was instigated by the fact that in J, \"NB.\" is used as comment indicator, both being well known Latin abbreviations: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc e.g. {cmd -> expected} { catch {uplevel 1 $cmd} res if {$res != $expected} {puts "$cmd -> $res, not $expected"} } ``` ```{=html} </div> ``` Again, the \"`->`\" argument is for eye-candy only --- but it feels better to me at least. See the examples soon to come. For recursive functions and other arithmetics, func makes better reading, by accepting expr language in the body: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc func {name argl body} {proc $name $argl [list expr $body]} ``` ```{=html} </div> ``` We\'ll use this to turn expr\'s infix operators into dyadic functions, plus the \"slashdot\" operator that makes division always return a real number, hence the dot : ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl foreach op {+ &mdash; * /} {func $op {a b} "\$a $op \$b"} e.g. {+ 1 2} -> 3 e.g. {/ 1 2} -> 0 ;# integer division func /. {a b} {double($a)/$b} e.g. {/. 1 2} -> 0.5 ;# "real" division #-- Two abbreviations for frequently used list operations: proc head list {lindex $list 0} e.g. {head {a b c}} -> a proc tail list {lrange $list 1 end} e.g. {tail {a b c}} -> {b c} ``` ```{=html} </div> ``` For \"fold\", this time I devised a recursive version: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl func fold {neutral op list} { $list eq [] ? $neutral : [$op [head $list] [fold $neutral $op [tail $list]]] } e.g. {fold 0 + {1 2 3 4}} -> 10 #-- A "Def" alias does the same job: Def sum = fold 0 + e.g. {sum {1 2 3 4}} -> 10 #-- So let's try to implement "mean" in tacit Tcl! Def mean = fork /. sum llength e.g. {mean {1 2 3 40}} -> 11.5 ``` ```{=html} </div> ``` Tacit enough (one might have picked fancier names like +/ for \"sum\" and \# as alias for llength), but in principle it is equivalent to the J version, and doesn\'t name a single argument. Also, the use of llength demonstrates that any good old Tcl command can go in here, not just the artificial Tacit world that I\'m just creating\... In the next step, I want to reimplement the \"median\" function, which for a sorted list returns the central element if its length is odd, or the mean of the two elements adjacent to the (virtual) center for even length. In J, it looks like this: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text median=.(mean@:\{~medind@#)@sortu medind=.((<.,>.)@half) ` half @.(2&|) half=.-:@<: NB. halve one less than rt. argument sortu=.\{~/: NB. sort upwards ``` ```{=html} </div> ``` which may better explain why I wouldn\'t want to code in J :\^) J has ASCIIfied the zoo of APL strange character operators, at the cost of using braces and brackets as operators too, without regard for balancing, and extending them with dots and colons, so e.g. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text - monadic: negate; dyadic: minus -. monadic: not -: monadic: halve ``` ```{=html} </div> ``` J code sometimes really looks like an accident in a keyboard factory\... I won\'t go into all details of the above code, just some: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text @ ("atop") is strong linkage, sort of functional composition <. (monadic) is floor() >. (monadic) is ceil() ``` ```{=html} </div> ``` (\<.,\>.) is building a list of the floor and the ceiling of its single argument, the comma being the concatenation operator here, comparable to Backus\' \"construction\" or Joy\'s cleave. The pattern ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text a ` b @. c ``` ```{=html} </div> ``` is a kind of conditional in J, which could in Tcl be written ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl if {[$c $x]} {$a $x} else {$b $x} ``` ```{=html} </div> ``` but my variant of the median algorithm doesn\'t need a conditional --- for lists of odd length it just uses the central index twice, which is idempotent for \"mean\", even if a tad slower. J\'s \"from\" operator `{` takes zero or more elements from a list, possibly repeatedly. For porting this, lmap is a good helper, even though not strictly functional: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc lmap {_v list body} { upvar 1 $_v v set res {} foreach v $list {lappend res [uplevel 1 $body]} set res } e.g. {lmap i {1 2 3 4} {* $i $i}} -> {1 4 9 16} #-- So here's my 'from': proc from {indices list} {lmap i $indices {lindex $list $i}} e.g. {from {1 0 0 2} {a b c}} -> {b a a c} ``` ```{=html} </div> ``` We furtheron borrow some more content from expr: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl func ceil x {int(ceil($x))} func floor x {int(floor($x))} e.g. {ceil 1.5} -> 2 e.g. {floor 1.5} -> 1 e.g. {fork list floor ceil 1.5} -> {1 2} ``` ```{=html} </div> ``` We\'ll need functional composition, and here\'s a recursive de-luxe version that takes zero or more functions, hence the name `o*`: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl func o* {functions x} { $functions eq []? $x : [[head $functions] [o* [tail $functions] $x]] } e.g. {o* {} hello,world} -> hello,world ``` ```{=html} </div> ``` Evidently, identity as could be written ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc I x {set x} ``` ```{=html} </div> ``` is the neutral element of variadic functional composition, when called with no functions at all. If composite functions like \'fork\' are arguments to o\*, we\'d better let unknown know that we want auto-expansion of first word: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc know what {proc unknown args $what\n[info body unknown]} know { set cmd [head $args] if {[llength $cmd]>1} {return [eval $cmd [tail $args]]} } ``` ```{=html} </div> ``` Also, we need a numeric sort that\'s good for integers as well as reals (\"Def\" serves for all kinds of aliases, not just combinations of functions): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl Def sort = lsort -real e.g. {sort {2.718 10 1}} -> {1 2.718 10} e.g. {lsort {2.718 10 1}} -> {1 10 2.718} ;# lexicographic #-- And now for the median test: Def median = o* {mean {fork from center sort}} Def center = o* {{fork list floor ceil} {* 0.5} -1 llength} func -1 x {$x &mdash; 1} e.g. {-1 5} -> 4 ;# predecessor function, when for integers #-- Trying the whole thing out: e.g. {median {1 2 3 4 5}} -> 3 e.g. {median {1 2 3 4}} -> 2.5 ``` ```{=html} </div> ``` As this file gets tacitly sourced, I am pretty confident that I\'ve reached my goal for this weekend --- even though my median doesn\'t remotely look like the J version: it is as \"wordy\" as Tcl usually is. But the admittedly still very trivial challenge was met in truly function-level style, concerning the definitions of median, center and mean --- no variable left behind. And that is one, and not the worst, Tcl way of Tacit programming\... ### Vector arithmetics APL and J (see Tacit programming) have the feature that arithmetics can be done with vectors and arrays as well as scalar numbers, in the varieties (for any operator @): - scalar @ scalar → scalar (like expr does) - vector @ scalar → vector - scalar @ vector → vector - vector @ vector → vector (all of same dimensions, element-wise) Here\'s experiments how to do this in Tcl. First lmap is a collecting foreach --- it maps the specified body over a list: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc lmap {_var list body} { upvar 1 $_var var set res {} foreach var $list {lappend res [uplevel 1 $body]} set res } #-- We need basic scalar operators from expr factored out: foreach op {+ - * / % ==} {proc $op {a b} "expr {\$a $op \$b}"} ``` ```{=html} </div> ``` The following generic wrapper takes one binary operator (could be any suitable function) and two arguments, which may be scalars, vectors, or even matrices (lists of lists), as it recurses as often as needed. Note that as my lmap above only takes one list, the two-list case had to be made explicit with foreach. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc vec {op a b} { if {[llength $a] == 1 && [llength $b] == 1} { $op $a $b } elseif {[llength $a]==1} { lmap i $b {vec $op $a $i} } elseif {[llength $b]==1} { lmap i $a {vec $op $i $b} } elseif {[llength $a] == [llength $b]} { set res {} foreach i $a j $b {lappend res [vec $op $i $j]} set res } else {error "length mismatch [llength $a] != [llength $b]"} } ``` ```{=html} </div> ``` Tests are done with this minimal \"framework\": ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc e.g. {cmd -> expected} { catch $cmd res if {$res ne $expected} {puts "$cmd -> $res, not $expected"} } ``` ```{=html} </div> ``` Scalar + Scalar ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl e.g. {vec + 1 2} -> 3 ``` ```{=html} </div> ``` Scalar + Vector ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl e.g. {vec + 1 {1 2 3 4}} -> {2 3 4 5} ``` ```{=html} </div> ``` Vector / Scalar ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl e.g. {vec / {1 2 3 4} 2.} -> {0.5 1.0 1.5 2.0} ``` ```{=html} </div> ``` Vector + Vector ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl e.g. {vec + {1 2 3} {4 5 6}} -> {5 7 9} ``` ```{=html} </div> ``` Matrix \* Scalar ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl e.g. {vec * {{1 2 3} {4 5 6}} 2} -> {{2 4 6} {8 10 12}} ``` ```{=html} </div> ``` Multiplying a 3x3 matrix with another: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl e.g. {vec * {{1 2 3} {4 5 6} {7 8 9}} {{1 0 0} {0 1 0} {0 0 1}}} -> \ {{1 0 0} {0 5 0} {0 0 9}} ``` ```{=html} </div> ``` The dot product of two vectors is a scalar. That\'s easily had too, given a sum function: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc sum list {expr [join $list +]+0} sum [vec * {1 2} {3 4}] ``` ```{=html} </div> ``` should result in 11 (= (1\*3)+(2\*4)). Here\'s a little application for this: a vector factorizer, that produces the list of divisors for a given integer. For this we again need a 1-based integer range generator: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc iota1 x { set res {} for {set i 1} {$i<=$x} {incr i} {lappend res $i} set res } e.g. {iota1 7} -> {1 2 3 4 5 6 7} #-- We can compute the modulo of a number by its index vector: e.g. {vec % 7 [iota1 7]} -> {0 1 1 3 2 1 0} #-- and turn all elements where the remainder is 0 to 1, else 0: e.g. {vec == 0 [vec % 7 [iota1 7]]} -> {1 0 0 0 0 0 1} ``` ```{=html} </div> ``` At this point, a number is prime if the sum of the latest vector is 2. But we can also multiply out the 1s with the divisors from the i ndex vector: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl e.g. {vec * [iota1 7] [vec == 0 [vec % 7 [iota1 7]]]} -> {1 0 0 0 0 0 7} #-- Hence, 7 is only divisible by 1 and itself, hence it is a prime. e.g. {vec * [iota1 6] [vec == 0 [vec % 6 [iota1 6]]]} -> {1 2 3 0 0 6} ``` ```{=html} </div> ``` So 6 is divisible by 2 and 3; non-zero elements in (lrange \$divisors 1 end-1) gives the \"proper\" divisors. And three nested calls to vec are sufficient to produce the divisors list :) Just for comparison, here\'s how it looks in J: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl iota1=.>:@i. iota1 7 1 2 3 4 5 6 7 f3=.iota1*(0&=@|~iota1) f3 7 1 0 0 0 0 0 7 f3 6 1 2 3 0 0 6 ``` ```{=html} </div> ``` ### Integers as Boolean functions Boolean functions, in which arguments and result are in the domain {true, false}, or {1, 0} as expr has it, and operators are e.g. {AND, OR, NOT} resp. {&&, \|\|, !}, can be represented by their truth table, which for example for {\$a && \$b} looks like: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl a b a&&b 0 0 0 1 0 0 0 1 0 1 1 1 ``` ```{=html} </div> ``` As all but the last column just enumerate all possible combinations of the arguments, first column least-significant, the full representation of a&&b is the last column, a sequence of 0s and 1s which can be seen as binary integer, reading from bottom up: `1 0 0 0 == 8`. So 8 is the associated integer of `a&&b`, but not only of this --- we get the same integer for `!(!a || !b)`, but then again, these functions are equivalent. To try this in Tcl, here\'s a truth table generator that I borrowed from a little proving engine, but without the lsort used there --- the order of cases delivered makes best sense when the first bit is least significant: } ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc truthtable n { # make a list of 2**n lists, each with n truth values 0|1 set res {} for {set i 0} {$i < (1<<$n)} {incr i} { set case {} for {set j 0} {$j <$n} {incr j } { lappend case [expr {($i & (1<<$j)) != 0}] } lappend res $case } set res } ``` ```{=html} </div> ``` Now we can write n(f), which, given a Boolean function of one or more arguments, returns its characteristic number, by iterating over all cases in the truth table, and setting a bit where appropriate: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc n(f) expression { set vars [lsort -unique [regsub -all {[^a-zA-Z]} $expression " "]] set res 0 set bit 1 foreach case [truthtable [llength $vars]] { foreach $vars $case break set res [expr $res | ((($expression)!=0)*$bit)] incr bit $bit ;#-- <<1, or *2 } set res } ``` ```{=html} </div> ``` Experimenting: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % n(f) {$a && !$a} ;#-- contradiction is always false 0 % n(f) {$a || !$a} ;#-- tautology is always true 3 % n(f) {$a} ;#-- identity is boring 2 % n(f) {!$a} ;#-- NOT 1 % n(f) {$a && $b} ;#-- AND 8 % n(f) {$a || $b} ;#-- OR 14 % n(f) {!($a && $b)} ;#-- de Morgan's laws: 7 % n(f) {!$a || !$b} ;#-- same value = equivalent 7 ``` ```{=html} </div> ``` So the characteristic integer is not the same as the Goedel number of a function, which would encode the structure of operators used there. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % n(f) {!($a || $b)} ;#-- interesting: same as unary NOT 1 % n(f) {!$a && !$b} 1 ``` ```{=html} </div> ``` Getting more daring, let\'s try a distributive law: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % n(f) {$p && ($q || $r)} 168 % n(f) {($p && $q) || ($p && $r)} 168 ``` ```{=html} </div> ``` Daring more: what if we postulate the equivalence? ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % n(f) {(($p && $q) || ($p && $r)) == ($p && ($q || $r))} 255 ``` ```{=html} </div> ``` Without proof, I just claim that every function of n arguments whose characteristic integer is `2^(2^n)` --- 1 is a tautology (or a true statement --- all bits are 1). Conversely, postulating non-equivalence turns out to be false in all cases, hence a contradiction: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % n(f) {(($p && $q) || ($p && $r)) != ($p && ($q || $r))} 0 ``` ```{=html} </div> ``` So again, we have a little proving engine, and simpler than last time. In the opposite direction, we can call a Boolean function by its number and provide one or more arguments --- if we give more than the function can make sense of, non-false excess arguments lead to constant falsity, as the integer can be considered zero-extended: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc f(n) {n args} { set row 0 set bit 1 foreach arg $args { set row [expr {$row | ($arg != 0)*$bit}] incr bit $bit } expr !!($n &(1<<$row)) } ``` ```{=html} </div> ``` Trying again, starting at OR (14): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % f(n) 14 0 0 0 % f(n) 14 0 1 1 % f(n) 14 1 0 1 % f(n) 14 1 1 1 ``` ```{=html} </div> ``` So f(n) 14 indeed behaves like the OR function --- little surprise, as its truth table (the results of the four calls), read bottom-up, 1110, is decimal 14 (8 + 4 + 2). Another test, inequality: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % n(f) {$a != $b} 6 % f(n) 6 0 0 0 % f(n) 6 0 1 1 % f(n) 6 1 0 1 % f(n) 6 1 1 0 ``` ```{=html} </div> ``` Trying to call 14 (OR) with more than two args: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % f(n) 14 0 0 1 0 % f(n) 14 0 1 1 0 53 % f(n) 14 1 1 1 0 ``` ```{=html} </div> ``` The constant 0 result is a subtle indication that we did something wrong :) Implication (if a then b, `a -> b`) can in expr be expressed as `$a <= $b` --- just note that the \"arrow\" seems to point the wrong way. Let\'s try to prove \"Modus Barbara\" --- \"if a implies b and b implies c, then a implies c\": ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % n(f) {(($a <= $b) && ($b <= $c)) <= ($a <= $c)} 255 ``` ```{=html} </div> ``` With less abstract variable names, one might as well write ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % n(f) {(($Socrates <= $human) && ($human <= $mortal)) <= ($Socrates <= $mortal)} 255 ``` ```{=html} </div> ``` But this has been verified long ago, by Socrates\' death :\^) ### Let unknown know To extend Tcl, i.e. to make it understand and do things that before raised an error, the easiest way is to write a proc. Any proc must however be called in compliance with Tcl\'s fundamental syntax: first word is the command name, then the arguments separated by whitespace. Deeper changes are possible with the unknown command, which is called if a command name is, well, unknown, and in the standard version tries to call executables, to auto-load scripts, or do other helpful things (see the file `init.tcl`). One could edit that file (not recommended), or rename unknown to something else and provide one\'s own unknown handler, that falls through to the original proc if unsuccessful, as shown in Radical language modification. Here is a simpler way that allows to extend unknown \"in place\" and incrementally: We let unknown \"know\" what action it shall take under what conditions. The know command is called with a condition that should result in an integer when given to expr, and a body that will be executed if cond results in nonzero, returning the last result if not terminated with an explicit return. In both cond and body you may use the variable args that holds the problem command unknown was invoked with. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc know what { if ![info complete $what] {error "incomplete command(s) $what"} proc unknown args $what\n[info body unknown] } ;# RS ``` ```{=html} </div> ``` The extending code *what* is prepended to the previous unknown body. This means that subsequent calls to know stack up, last condition being tried first, so if you have several conditions that fire on the same input, let them be \"known\" from generic to specific. Here\'s a little debugging helper, to find out why \"know\" conditions don\'t fire: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc know? {} {puts [string range [info body unknown] 0 511]} ``` ```{=html} </div> ``` Now testing what new magic this handful of code allows us to do. This simple example invokes expr if the \"command\" is digestible for it: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % know {if {![catch {expr $args} res]} {return $res}} % 3+4 7 ``` ```{=html} </div> ``` ### If we had no if Imagine the makers of Tcl had failed to provide the if command. All the rest would be there. Doing more steps towards functional programming, I came upon this interesting problem, and will shortly demonstrate that it can easily be solved in pure-Tcl. We still have the canonical truth values 0 and 1 as returned from expr with a comparison operator. The idea in the paper I read is to use them as names of very simple functions: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc 0 {then else} {uplevel 1 $else} proc 1 {then else} {uplevel 1 $then} ;# the famous K combinator ``` ```{=html} </div> ``` Glory be to the 11 rules of man Tcl that this is already a crude though sufficient reimplementation: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set x 42 [expr $x<100] {puts Yes} {puts No} ``` ```{=html} </div> ``` The bracketed expr command is evaluated first, returning 0 or 1 as result of the comparison. This result (0 or 1) is substituted for the first word of this command. The other words (arguments) are not substituted because they\'re curly-braced, so either 0 or 1 is invoked, and does its simple job. (I used uplevel instead of eval to keep all side effects in caller\'s scope). Formally, what happened to the bracketed call is that it went through \"applicative order\" evaluation (i.e., do it now), while the braced commands wait for \"normal order\" evaluation (i.e., do when needed, maybe never --- the need is expressed through eval/upvar or similar commands). Though slick at first sight, we actually have to type more. As a second step, we create the If command that wraps the expr invocation: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc If {cond then else} { [uplevel 1 [list expr ($cond)!=0]] {uplevel 1 $then} {uplevel 1 $else} } If {$x>40} {puts Indeed} {puts "Not at all"} ``` ```{=html} </div> ``` This again passes impromptu tests, and adds the feature that any non-zero value counts as true and returns 1 --- if we neglect the other syntactic options of if, especially the elseif chaining. However, this is no fundamental problem --- consider that ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl if A then B elseif C then D else E ``` ```{=html} </div> ``` can be rewritten as ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl if A then B else {if C then D else E} ``` ```{=html} </div> ``` so the two-way If is about as mighty as the real thing, give or take a few braces and redundant keywords (then, else). Luckily we have an if in Tcl (and it certainly fares better in byte-code compilation), but on leisurely evenings it\'s not the microseconds that count (for me at least) --- it\'s rather reading on the most surprising (or fundamental) ideas, and demonstrating how easily Tcl can bring them to life\... ### Brute force meets Goedel Never afraid of anything (as long as everything is a string), a discussion in the Tcl chatroom brought me to try the following: let the computer write (\"discover\") its own software, only given specifications of input and output. In truly brute force, up to half a million programs are automatically written and (a suitable subset of them) tested to find the one that passes the tests. To make things easier, this flavor of \"software\" is in a very simple RPN language similar to, but much smaller than, the one presented in Playing bytecode: stack-oriented like Forth, each operation being one byte (ASCII char) wide, so we don\'t even need whitespace in between. Arguments are pushed on the stack, and the result of the \"software\", the stack at end, is returned. For example, in ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl ebc ++ 1 2 3 ``` ```{=html} </div> ``` execution of the script \"++\" should sum its three arguments (1+(2+3)), and return 6. Here\'s the \"bytecode engine\" (ebc: execute byte code), which retrieves the implementations of bytecodes from the global array cmd: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc ebc {code argl} { set ::S $argl foreach opcode [split $code ""] { eval $::cmd($opcode) } set ::S } ``` ```{=html} </div> ``` Let\'s now populate the bytecode collection. The set of all defined bytecodes will be the alphabet of this little RPN language. It may be interesting to note that this language has truly minimal syntax --- the only rule is: each script (\"word\") composed of any number of bytecodes is well-formed. It just remains to check whether it does what we want. Binary expr operators can be treated generically: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl foreach op {+ - * /} { set cmd($op) [string map "@ $op" {swap; push [expr {[pop] @ [pop]}]}] } #-- And here's some more hand-crafted bytecode implementations set cmd(d) {push [lindex $::S end]} ;# dup set cmd(q) {push [expr {sqrt([pop])}]} set cmd(^) {push [swap; expr {pow([pop],[pop])}]} set cmd(s) swap #-- The stack routines imply a global stack ::S, for simplicity interp alias {} push {} lappend ::S proc pop {} {K [lindex $::S end] [set ::S [lrange $::S 0 end-1]]} proc K {a b} {set a} proc swap {} {push [pop] [pop]} ``` ```{=html} </div> ``` Instead of enumerating all possible bytecode combinations beforehand (which grows exponentially by alphabet and word length), I use this code from Mapping words to integers to step over their sequence, uniquely indexed by an increasing integer. This is something like the Goedel number of the corresponding code. Note that with this mapping, all valid programs (bytecode sequences) correspond to one unique non-negative integer, and longer programs have higher integers associated: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc int2word {int alphabet} { set word "" set la [llength $alphabet] while {$int > 0} { incr int -1 set word [lindex $alphabet [expr {$int % $la}]]$word set int [expr {$int/$la}] } set word } ``` ```{=html} </div> ``` Now out for discovery! The toplevel proc takes a paired list of inputs and expected output. It tries in brute force all programs up to the specified maximum Goedel number and returns the first one that complies with all tests: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc discover0 args { set alphabet [lsort [array names ::cmd]] for {set i 1} {$i<10000} {incr i} { set code [int2word $i $alphabet] set failed 0 foreach {inputs output} $args { catch {ebc $code $inputs} res if {$res != $output} {incr failed; break} } if {!$failed} {return $code} } } ``` ```{=html} </div> ``` But iterating over many words is still pretty slow, at least on my 200 MHz box, and many useless \"programs\" are tried. For instance, if the test has two inputs and wants one output, the stack balance is -1 (one less out than in). This is provided e.g. by one the binary operators +-\*/. But the program \"dd\" (which just duplicates the top of stack twice) has a stack balance of +2, and hence can never pass the example test. So, on a morning dogwalk, I thought out this strategy: - measure the stack balance for each bytecode - iterate once over very many possible programs, computing their stack balance - partition them (put into distinct subsets) by stack balance - perform each \'discovery\' call only on programs of matching stack balance Here\'s this version. Single bytecodes are executed, only to measure their effect on the stack. The balance of longer programs can be computed by just adding the balances of their individual bytecodes: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc bc'stack'balance bc { set stack {1 2} ;# a bytecode will consume at most two elements expr {[llength [ebc $bc $stack]]-[llength $stack]} } proc stack'balance code { set res 0 foreach bc [split $code ""] {incr res $::balance($bc)} set res } ``` ```{=html} </div> ``` The partitioning will run for some seconds (depending on nmax --- I tried with several ten thousand), but it\'s needed only once. The size of partitions is further reduced by excluding programs which contain redundant code, that will have no effect, like swapping the stack twice, or swapping before an addition or multiplication. A program without such extravaganzas is shorter and yet does the same job, so it will have been tested earlier anyway. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc partition'programs nmax { global cmd partitions balance #-- make a table of bytecode stack balances set alphabet [array names cmd] foreach bc $alphabet { set balance($bc) [bc'stack'balance $bc] } array unset partitions ;# for repeated sourcing for {set i 1} {$i<=$nmax} {incr i} { set program [int2word $i $alphabet] #-- "peephole optimizer" - suppress code with redundancies set ok 1 foreach sequence {ss s+ s*} { if {[string first $sequence $program]>=0} {set ok 0} } if {$ok} { lappend partitions([stack'balance $program]) $program } } set program ;# see how far we got } ``` ```{=html} </div> ``` The discoverer, Second Edition, determines the stack balance of the first text, and tests only those programs of the same partition: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc discover args { global partitions foreach {in out} $args break set balance [expr {[llength $out]-[llength $in]}] foreach code $partitions($balance) { set failed 0 foreach {input output} $args { catch {ebc $code $input} res if {$res != $output} {incr failed; break} } if {!$failed} {return $code} } } ``` ```{=html} </div> ``` But now for the trying. The partitioning helps very much in reducing the number of candidates. For the 1000 programs with Goedel numbers 1..1000, it retains only a fraction for each stack balance: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl -2: 75 -1: 155 (this and 0 will be the most frequently used) 0: 241 1: 274 2: 155 3: 100 ``` ```{=html} </div> ``` Simple starter --- discover the successor function (add one): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % discover 5 6 7 8 dd/+ ``` ```{=html} </div> ``` Not bad: duplicate the number twice, divide by itself to get the constant 1, and add that to the original number. However, it fails to work if we add the successor of 0 as another test case: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % discover 5 6 7 8 0 1 ``` ```{=html} </div> ``` Nothing coming --- because zero division made the last test fail. If we give only this test, another solution is found: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % discover 0 1 d^ ``` ```{=html} </div> ``` \"Take x to the x-th\" power\" --- `pow(0,0)` gives indeed 1, but that\'s not the generic successor function. More experiments to discover the hypot() function: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % discover {4 3} 5 d/+ ``` ```{=html} </div> ``` Hm --- the 3 is duplicated, divided by itself (=1), which is added to 4. Try to swap the inputs: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % discover {3 4} 5 q+ ``` ```{=html} </div> ``` Another dirty trick: get square root of 4, add to 3 --- presto, 5. The correct `hypot()` function would be ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl d*sd*+q ``` ```{=html} </div> ``` but my program set (nmax=30000) ends at 5-byte codes, so even by giving another test to force discovery of the real thing, it would never reach a 7-byte code. OK, I bite the bullet, set nmax to 500000, wait 5 minutes for the partitioning, and then: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % discover {3 4} 5 {11 60} 61 sd/+ ``` ```{=html} </div> ``` Hm.. cheap trick again --- it was discovered that the solution is just the successor of the second argument. Like in real life, test cases have to be carefully chosen. So I tried with another a\^2+b\^2=c\^2 set, and HEUREKA! (after 286 seconds): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % discover {3 4} 5 {8 15} 17 d*sd*+q ``` ```{=html} </div> ``` After partitioning, 54005 programs had the -1 stack balance, and the correct result was on position 48393 in that list\... And finally, with the half-million set of programs, here\'s a solution for the successor function too: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % discover 0 1 4711 4712 ddd-^+ ``` ```{=html} </div> ``` \"d-\" subtracts top of stack from itself, pushing 0; the second duplicate to the 0-th power gives 1, which is added to the original argument. After some head-scratching, I find it plausible, and possibly it is even the simplest possible solution, given the poorness of this RPN language. Lessons learned: - Brute force is simple, but may demand very much patience (or faster hardware) - The sky, not the skull is the limit what all we can do with Tcl :) ### Object orientation OO (Object Orientation) is a style in programming languages popular since Smalltalk, and especially C++, Java, etc. For Tcl, there have been several OO extensions/frameworks (*incr Tcl*, *XOTcl*, *stooop*, *Snit* to name a few) in different flavors, but none can be considered as standard followed by a majority of users. However, most of these share the features - classes can be defined, with variables and methods - objects are created as instances of a class - objects are called with messages to perform a method Of course, there are some who say: \"Advocating object-orientated programming is like advocating pants-oriented clothing: it covers your behind, but often doesn\'t fit best\" \... #### Bare-bones OO Quite a bunch of what is called OO can be done in pure Tcl without a \"framework\", only that the code might look clumsy and distracting. Just choose how to implement instance variables: - in global variables or namespaces - or just as parts of a transparent value, with TOOT The task of frameworks, be they written in Tcl or C, is just to hide away gorey details of the implementation --- in other words, sugar it :) On the other hand, one understands a clockwork best when it\'s outside the clock, and all parts are visible --- so to get a good understanding of OO, it might be most instructive to look at a simple implementation. As an example, here\'s a Stack class with *push* and *pop* methods, and an instance variable *s* --- a list that holds the stack\'s contents: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl namespace eval Stack {set n 0} proc Stack::Stack {} { #-- constructor variable n set instance [namespace current]::[incr n] namespace eval $instance {variable s {}} interp alias {} $instance {} ::Stack::do $instance } ``` ```{=html} </div> ``` The *interp alias* makes sure that calling the object\'s name, like ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl ::Stack::1 push hello ``` ```{=html} </div> ``` is understood and rerouted as a call to the dispatcher below: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl ::Stack::do ::Stack::1 push hello ``` ```{=html} </div> ``` The dispatcher imports the object\'s variables (only *s* here) into local scope, and then switches on the method name: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc Stack::do {self method args} { #-- Dispatcher with methods upvar #0 ${self}::s s switch -- $method { push {eval lappend s $args} pop { if ![llength $s] {error "stack underflow"} K [lindex $s end] [set s [lrange $s 0 end-1]] } default {error "unknown method $method"} } } proc K {a b} {set a} ``` ```{=html} </div> ``` A framework would just have to make sure that the above code is functionally equivalent to, e.g. (in a fantasy OO style): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl class Stack { variable s {} method push args {eval lappend s $args} method pop {} { if ![llength $s] {error "stack underflow"} K [lindex $s end] [set s [lrange $s 0 end-1]] } } ``` ```{=html} </div> ``` which, I admit, reads definitely better. But bare-bones has its advantages too: in order to see how a clockwork works, you\'d better have all parts visible :) Now testing in an interactive tclsh: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % set s [Stack::Stack] ;#-- constructor ::Stack::1 ;#-- returns the generated instance name % $s push hello hello % $s push world hello world % $s pop world % $s pop hello % $s pop stack underflow ;#-- clear enough error message % namespace delete $s ;#-- "destructor" ``` ```{=html} </div> ``` #### TOOT: transparent OO for Tcl Transparent OO for Tcl, or TOOT for short, is a very amazing combination of Tcl\'s concept of transparent values, and the power of OO concepts. In TOOT, the values of objects are represented as a list of length 3: the class name (so much for \"runtime type information\" :-), a \"\|\" as separator and indicator, and the values of the object, e.g. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl {class | {values of the object}} ``` ```{=html} </div> ``` Here\'s my little take on toot in a nutshell. Classes in C++ started out as structs, so I take a minimal struct as example, with generic get and set methods. We will export the *get* and *set* methods: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl namespace eval toot {namespace export get set} proc toot::struct {name members} { namespace eval $name {namespace import -force ::toot::*} #-- membership information is kept in an alias: interp alias {} ${name}::@ {} lsearch $members } ``` ```{=html} </div> ``` The two generic accessor functions will be inherited by \"struct\"s ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc toot::get {class value member} { lindex $value [${class}::@ $member] } ``` ```{=html} </div> ``` The set method does not change the instance (it couldn\'t, as it sees it only \"by value\") --- it just returns the new composite toot object, for the caller to do with it what he wants: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc toot::set {class value member newval} { ::set pos [${class}::@ $member] list $class | [lreplace $value $pos $pos $newval] } ``` ```{=html} </div> ``` For the whole thing to work, here\'s a simple overloading of unknown --- see \"Let unknown know\". It augments the current unknown code, at the top, with a handler for ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl {class | values} method args ``` ```{=html} </div> ``` patterns, which converts it to the form ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl ::toot::(class)::(method) (class) (values) (args) ``` ```{=html} </div> ``` and returns the result of calling that form: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc know what {proc unknown args $what\n[info body unknown]} ``` ```{=html} </div> ``` Now to use it (I admit the code is no easy reading): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl know { set first [lindex $args 0] if {[llength $first]==3 && [lindex $first 1] eq "|"} { set class [lindex $first 0] return [eval ::toot::${class}::[lindex $args 1] \ $class [list [lindex $first 2]] [lrange $args 2 end]] } } ``` ```{=html} </div> ``` Testing: we define a \"struct\" named foo, with two obvious members: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl toot::struct foo {bar grill} ``` ```{=html} </div> ``` Create an instance as pure string value: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set x {foo | {hello world}} puts [$x get bar] ;# -> hello (value of the "bar" member) ``` ```{=html} </div> ``` Modify part of the foo, and assign it to another variale: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set y [$x set grill again] puts $y ;# -> foo | {hello again} ``` ```{=html} </div> ``` Struct-specific methods can be just procs in the right namespace. The first and second arguments are the class (disregarded here, as the dash shows) and the value, the rest is up to the coder. This silly example demonstrates member access and some string manipulation: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc toot::foo::upcase {- values which string} { string toupper [lindex $values [@ $which]]$string } puts [$y upcase grill !] ;# -> AGAIN! ``` ```{=html} </div> ``` ### A little deterministic Turing machine At university, I never learned much about Turing machines. Only decades later, a hint in the Tcl chatroom pointed me to <http://csc.smsu.edu/~shade/333/project.txt> , an assignment to implement a Deterministic Turing Machine (i.e. one with at most one rule per state and input character), which gives clear instructions and two test cases for input and output, so I decided to try my hand in Tcl. Rules in this little challenge are of the form a bcD e, where - a is the state in which they can be applied - b is the character that must be read from tape if this rule is to apply - c is the character to write to the tape - D is the direction to move the tape after writing (R(ight) or L(eft)) - e is the state to transition to after the rule was applied Here\'s my naive implementation, which takes the tape just as the string it initially is. I only had to take care that when moving beyond its ends, I had to attach a space (written as \_) on that end, and adjust the position pointer when at the beginning. Rules are also taken as strings, whose parts can easily be extracted with string index --- as it\'s used so often here, I alias it to @. } ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc dtm {rules tape} { set state 1 set pos 0 while 1 { set char [@ $tape $pos] foreach rule $rules { if {[@ $rule 0] eq $state && [@ $rule 2] eq $char} { #puts rule:$rule,tape:$tape,pos:$pos,char:$char #-- Rewrite tape at head position. set tape [string replace $tape $pos $pos [@ $rule 3]] #-- Move tape Left or Right as specified in rule. incr pos [expr {[@ $rule 4] eq "L"? -1: 1}] if {$pos == -1} { set pos 0 set tape _$tape } elseif {$pos == [string length $tape]} { append tape _ } set state [@ $rule 6] break } } if {$state == 0} break } #-- Highlight the head position on the tape. string trim [string replace $tape $pos $pos \[[@ $tape $pos]\]] _ } interp alias {} @ {} string index ``` ```{=html} </div> ``` Test data from <http://csc.smsu.edu/~shade/333/project.txt> ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl set rules { {1 00R 1} {2 01L 0} {1 __L 2} {2 10L 2} {2 _1L 0} {1 11R 1} } set tapes { 0 10011 1111 } set rules2 { {3 _1L 2} {1 _1R 2} {1 11L 3} {2 11R 2} {3 11R 0} {2 _1L 1} } set tapes2 _ ``` ```{=html} </div> ``` Testing: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl foreach tape $tapes {puts [dtm $rules $tape]} puts * puts [dtm $rules2 $tapes2] ``` ```{=html} </div> ``` reports the results as wanted in the paper, on stdout: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl >tclsh turing.tcl [_]1 1[0]100 [_]10000 * 1111[1]1 ``` ```{=html} </div> ``` ### Streams Streams are a powerful concept in (not only functional) programming. In SICP chapter 3.5, streams are introduced as data structures characterized as \"delayed lists\", whose elements are produced and returned only on demand (deferred evaluation). This way, a stream can promise to be a potentially endless source of data, while taking only finite time to process and deliver what\'s really wanted. Other streams may provide a finite but very large number of elements, which would be impractical to process in one go. In Tcl, the two ways of reading a file are a good example: - read `$fp` returns the whole contents, which then can be processed; - while `{[gets $fp line]>-1} {...}` reads line by line, interleaved with processing The second construct may be less efficient, but is robust for gigabyte-sized files. A simpler example is pipes in Unix/DOS (use TYPE for cat there): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` bash cat foo.bar | more ``` ```{=html} </div> ``` where the \"cat\" delivers lines of the file as long as \"more\" will take them, and waits otherwise (after all, stdin and stdout are just streams\...). Such process chains can be emulated in Tcl with the following rules: A stream is modelled here as a procedure that returns one stream item on each call. The special item \"\" (the empty string) indicates that the stream is exhausted. Streams are interesting if they don\'t deliver the same result on every call, which requires them to maintain state between calls e.g. in static variables (here implemented with the fancy remember proc) --- examples are intgen that delivers ever increasing integers, or gets `$fp` where the file pointer advances at each call, so potentially all lines of the file are returned over time. A filter takes one or more streams, and possibly other arguments, and reacts like a stream too. Hence, streams can be (and typically are) nested for processing purposes. If a filter meets end-of-stream, it should return that too. Filters may be characterized as \"selectors\" (who may return only part of their input, like \"grep\") and/or \"appliers\" who call a command on their input and return the result. Note that on infinite streams, selectors may never return, e.g. if you want the second even prime\... Streams in general should not be written in brackets (then the Tcl parser would eagerly evaluate them before evaluating the command), but braced, and stream consumers eval the stream at their discretion. Before we start, a word of warning: maintaining state of a procedure is done with default arguments that may be rewritten. To prevent bugs from procedures whose defaults have changed, I\'ve come up with the following simple architecture --- procs with static variables are registered as \"sproc\"s, which remembers the initial defaults, and with a reset command you can restore the initial values for one or all sprocs: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc sproc {name head body} { set ::sproc($name) $head proc $name $head $body } proc reset { {what *}} { foreach name [array names ::sproc $what] { proc $name $::sproc($name) [info body $name] } } ``` ```{=html} </div> ``` Now let\'s start with a simple stream source, \"cat\", which as a wrapper for gets returns the lines of a file one by one until exhausted (EOF), in which case an empty string is returned (this requires that empty lines in the files, which would look similarly, are represented as a single blank): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl sproc cat {filename {fp {}} } { if {$fp==""} { remember fp [set fp [open $filename]] } if {[gets $fp res]<0} { remember fp [close $fp] ;# which returns an empty string ;-) } elseif {$res==""} {set res " "} ;# not end of stream! set res } proc remember {argn value} { # - rewrite a proc's default arg with given value set procn [lindex [info level -1] 0] ;# caller's name set argl {} foreach arg [info args $procn] { if [info default $procn $arg default] { if {$arg==$argn} {set default $value} lappend argl [list $arg $default] } else { lappend argl $arg } } proc $procn $argl [info body $procn] set value } # This simple but infinite stream source produces all positive integers: sproc intgen { {seed -1}} {remember seed [incr seed]} # This produces all (well, very many) powers of 2: sproc powers-of-2 { {x 0.5}} {remember x [expr $x*2]} # A filter that reads and displays a stream until user stops it: proc more {stream} { while 1 { set res [eval $stream] if {$res==""} break ;# encountered end of stream puts -nonewline $res; flush stdout if {[gets stdin]=="q"} break } } ``` ```{=html} </div> ``` Usage example: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl more {cat streams.tcl} ``` ```{=html} </div> ``` which crudely emulates the Unix/DOS pipe mentioned above (you\'ll have to hit after every line, and to quit..). more is the most important \"end-user\" of streams, especially if they are infinite. Note however that you need stdin for this implementation, which excludes wishes on Windows (one might easily write a UI-more that reacts on mouse clicks, though). A more generic filter takes a condition and a stream, and on each call returns an element of the input stream where the condition holds --- if ever one comes along: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc filter {cond stream} { while 1 { set res [eval $stream] if {$res=="" || [$cond $res]} break } set res } # Here is a sample usage with famous name: proc grep {re stream} { filter [lambda [list x [list re $re]] {regexp $re $x}] $stream } #.... which uses the (less) famous function maker: proc lambda {args body} { set name [info level 0] proc $name $args $body set name } # Usage example: more {grep this {cat streams.tcl}} ``` ```{=html} </div> ``` Friends of syntactic sugar might prefer shell style: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` bash $ cat streams.tcl | grep this | more ``` ```{=html} </div> ``` and guess what, we can have that in Tcl too (and not in Scheme !-), by writing a proc, that also resets all sprocs, with the fancy name \"\$\" (in Unix, this could be the shell prompt that you don\'t type, but for Tcl we always have to have the command name as first word): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc $ args { reset set cmd {} foreach arg $args { if {$arg != "|"} { lappend tmp $arg } else { set cmd [expr {$cmd==""? $tmp: [lappend tmp $cmd]}] set tmp {} } } uplevel 1 [lappend tmp $cmd] } ``` ```{=html} </div> ``` To prove that we haven\'t cheated by using exec, let\'s introduce a line counter filter: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl sproc -n {stream {n 0}} { set res [eval $stream] if {$res!=""} {set res [remember n [incr n]]:$res} } ``` ```{=html} </div> ``` This can be added to filter chains, to count lines in the original file, or only the results from grep: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl $ cat streams.tcl | -n | grep this | more $ cat streams.tcl | grep this | -n | more ``` ```{=html} </div> ``` We further observe that more has a similar structure to filter, so we could also rewrite it in terms of that: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc more2 stream { filter [lambda x { puts -nonewline $x; flush stdout expr {[gets stdin]=="q"} }] $stream } # Here is another stream producer that returns elements from a list: sproc streamlist {list {todo {}} {firstTime 1} } { if $firstTime {set todo $list; remember firstTime 0} remember todo [lrange $todo 1 end] lindex $todo 0 } # This one repeats its list endlessly, so better use it with 'more': sproc infinite-streamlist {list {todo {}} } { initially todo $list remember todo [lrange $todo 1 end] lindex $todo 0 } # This is sugar for first-time assignment of static variables: proc initially {varName value} { upvar 1 $varName var if {$var==""} {set var $value} } # But for a simple constant stream source, just use [subst]: # more {subst 1} ;# will produce as many ones as you wish # This filter collects its input (should be finite ;-) into a list: proc collect stream { set res {} while 1 { set element [eval $stream] if {$element==""} break lappend res $element } set res } ``` ```{=html} </div> ``` The sort filter is unusual in that it consumes its whole (finite!) input, sorts it, and acts as a stream source on the output: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl sproc sort {stream {todo {}} {firstTime 1}} { if $firstTime { set todo [lsort [collect $stream]] remember firstTime 0 } remember todo [lrange $todo 1 end] lindex $todo 0 } # $ streamlist {foo bar grill a} | sort | collect => a bar foo grill proc apply {f stream} {$f [eval $stream]} #... This can be plugged into a filter chain to see what's going on: proc observe stream {apply [lambda y {puts $y; set y}] $stream} # ... or, to get a stream of even numbers, starting from 0: more {apply [lambda x {expr $x*2}] intgen} ``` ```{=html} </div> ``` Now for the example in SICP: find the second prime in the interval between 10000 and 1000000. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl sproc interval {from to {current {}} } { initially current $from if {$current<=$to} { remember current [expr $current+1] } } proc prime? x { if {$x<2} {return 0} set max [expr sqrt($x)] set try 2 while {$try<=$max} { if {$x%$try == 0} {return 0} incr try [expr {2-($try==2)}] } return 1 } proc stream-index {stream index} { for {set i 0} {$i<=$index} {incr i} { set res [eval $stream] } set res } sproc stream-range {stream from to {pos 0}} { while {$pos<$from} { set res [eval $stream] ;# ignore elements before 'from' if {$res==""} return ;# might be end-of-stream incr pos } if {$to!="end" && $pos > $to} return remember pos [incr pos] eval $stream } stream-index {filter prime? {interval 10000 1000000}} 1 ==> 10009 ``` ```{=html} </div> ``` Another idea from SICP is a \"smoothing\" function, that averages each pair of values from the input stream. For this we need to introduce a short-term memory also in the filter: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl sproc average {stream {previous {}} } { if {$previous==""} {set previous [eval $stream]} remember previous [set current [eval $stream]] if {$current!=""} {expr {($previous+$current)/2.}} } ``` ```{=html} </div> ``` which, tested on a n-element stream, returns n-1 averages: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl collect {average {streamlist {1 2 3 4 5}}} ==> 1.5 2.5 3.5 4.5 ``` ```{=html} </div> ``` Yet another challenge was to produce an infinite stream of pairs `{i j}` of positive integers, `i <= j`, ordered by their sum, so that more pairs produces consecutively ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl {1 1} {1 2} {1 3} {2 2} {1 4} {2 3} {1 5} {2 4} {3 3} {1 6} ... ``` ```{=html} </div> ``` Here\'s my solution which does that: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl sproc pairs { {last {}} } { if {$last==""} { set last [list 1 1] ;# start of iteration } else { foreach {a b} $last break if {$a >= $b-1} { set last [list 1 [expr {$a+$b}]] ;# next sum level } else { set last [list [incr a] [incr b -1]] } } remember last $last } ``` ```{=html} </div> ``` **Ramanujan numbers**: The pairs generator can be used to find Ramanujan numbers, which can be represented as the sum of two integer cubes in more than one way. Here I use a global array for recording results: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl sproc Ramanujan {stream {firstTime 1}} { if $firstTime {unset ::A; remember firstTime 0} while 1 { set pair [eval $stream] foreach {a b} $pair break set n [expr {$a*$a*$a + $b*$b*$b}] if [info exists ::A($n)] { lappend ::A($n) $pair break } else {set ::A($n) [list $pair]} } list $n $::A($n) } more {Ramanujan pairs} ;# or: $ pairs | Ramanujan | more ``` ```{=html} </div> ``` delivers in hardly noticeable time the R. numbers 1729, 4104, 13832\... Or, how\'s this infinite Fibonacchi number generator, which on more fibo produces all the F.numbers (0,1,1,2,3,5,8,13,21\...) you might want? ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl sproc fibo { {a ""} {b ""}} { if {$a==""} { remember a 0 } elseif {$b==""} { remember b 1 } else { if {$b > 1<<30} {set b [expr double($b)]} remember a $b remember b [expr $a+$b] } } ``` ```{=html} </div> ``` **Discussion**: With the above code, it was possible to reproduce quite some behavior of streams as documented in SICP, not as data structures but with Tcl procs (though procs are data too, in some sense\...). What\'s missing is the capability to randomly address parts of a stream, as is possible in Scheme (and of course their claim to do without assignment, or mutable data\...) Tcl lists just don\'t follow LISP\'s CAR/CDR model (though KBK demonstrated in Tcl and LISP that this structure can be emulated, also with procs), but rather C\'s flat `*TclObject[]` style. The absence of lexical scoping also led to constructs like sproc/reset, which stop a gap but aren\'t exactly elegant --- but Tcl\'s clear line between either local or global variables allows something like closures only by rewriting default arguments like done in remember (or like in Python). Don\'t take this as a fundamental critique of Tcl, though --- its underlying model is far more simple and elegant than LISP\'s (what with \"special forms\", \"reader macros\"\...), and yet powerful enough to do just about everything possible\... ### Playing with Laws of Form After many years, I re-read ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl G. Spencer-Brown, "Laws of Form". New York: E.P. Dutton 1979 ``` ```{=html} </div> ``` which is sort of a mathematical thriller, if you will. Bertrand Russell commented that the author \"has revealed a new calculus, of great power and simplicity\" (somehow sounds like Tcl ;\^). In a very radical simplification, a whole world is built up by two operators, juxtaposition without visible symbol (which could be likened to or) and a overbar-hook (with the meaning of not) that I can\'t type here --- it\'s a horizontal stroke over zero or more operands, continued at right by a vertical stroke going down to the baseline. In these Tcl experiments, I use \"\" for \"\" and angle-brackets \<\> for the overbar-hook (with zero or more operands in between). One point that was new for me is that the distinction between operators and operands is not cast in stone. Especially constants (like \"true\" and \"false\" in Boolean algebras) can be equally well expressed as neutral elements of operators, if these are considered variadic, and having zero arguments. This makes sense, even in Tcl, where one might implement them as ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc and args { foreach arg $args {if {![uplevel 1 expr $arg]} {return 0}} return 1 } proc or args { foreach arg $args {if {[uplevel 1 expr $arg]} {return 1}} return 0 } ``` ```{=html} </div> ``` which, when called with no arguments, return 1 or 0, respectively. So \[or\] == 0 and \[and\] == 1. In Spencer-Brown\'s terms, \[\] (which is \"\", the empty string with no arguments) is false (\"nil\" in LISP), and \[\<\>\] is the negation of \"\", i.e. true. His two axioms are: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl <><> == <> "to recall is to call -- (1 || 1) == 1" <<>> == "to recross is not to cross -- !!0 == 0" ``` ```{=html} </div> ``` and these can be implemented by a string map that is repeated as long as it makes any difference (sort of a trampoline) to simplify any expression consisting only of operators and constants (which are operators with zero arguments): ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc lf'simplify expression { while 1 { set res [string map {<><> <> <<>> ""} $expression] if {$res eq $expression} {return $res} set expression $res } } ``` ```{=html} </div> ``` Testing: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % lf'simplify <<><>><> <> ``` ```{=html} </div> ``` which maps \<\>\<\> to \<\>, \<\<\>\> to \"\", and returns \<\> for \"true\". ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % lf'simplify <a>a <a>a ``` ```{=html} </div> ``` In the algebra introduced here, with a variable \"a\", no further simplification was so far possible. Let\'s change that --- \"a\" can have only two values, `""` or `<>`, so we might try to solve the expression by assuming all possible values for a, and see if they differ. If they don\'t, we have found a fact that isn\'t dependent on the variable\'s value, and the resulting constant is returned, otherwise the unsolved expression: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc lf'solve {expression var} { set results {} foreach value {"" <>} { set res [lf'simplify [string map [list $var $value] $expression]] if {![in $results $res]} {lappend results $res} if {[llength $results] > 1} {return $expression} } set results } ``` ```{=html} </div> ``` with a helper function in that reports containment of an element in a list: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc in {list element} {expr {[lsearch -exact $list $element] >= 0}} ``` ```{=html} </div> ``` Testing: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % lf'solve <a>a a <> ``` ```{=html} </div> ``` which means, in expr terms, {(!\$a \|\| \$a) == 1}, for all values of a. In other words, a tautology. All of Boole\'s algebra can be expressed in this calculus: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl * (1) not a == !$a == <a> * (2) a or b == $a || $b == ab * (3) a and b == $a && $b == <<a>&lt;b&gt;> * (4) a implies b == $a <= $b == <a>b ``` ```{=html} </div> ``` We can test it with the classic \"ex contradictione quodlibet\" (ECQ) example --- \"if p and not p, then q\" for any q: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl % lf'solve <&lt;p><&lt;p>>>q p q ``` ```{=html} </div> ``` So formally, q is true, whatever it is :) If this sounds overly theoretic, here\'s a tricky practical example in puzzle solving, Lewis Carroll\'s last sorites (pp. 123f.). The task is to conclude something from the following premises: - The only animals in this house are cats - Every animal is suitable for a pet, that loves to gaze at the moon - When I detest an animal, I avoid it - No animals are carnivorous, unless they prowl at night - No cat fail to kill mice - No animals ever take to me, except what are in this house - Kangaroos are not suitable for pets - None but carnivora kill mice - I detest animals that do not take to me - Animals that prowl at night always love to gaze at the moon These are encoded to the following one-letter predicates: a: avoided by me\ c: cat\ d: detested by me\ h: house, in this\ k: kill mice\ m: moon, love to gaze at\ n: night, prowl at\ p: pet, suitable for\ r: (kanga)roo\ t: take to me\ v: (carni)vorous So the problem set can be restated, in Spencer-Brown\'s terms, as <h>c <m>p <d>a <v>n <c>k <t>h <r><p> <k>v td <n>m I first don\'t understand why all premises can be just written in a row, which amounts to implicit \"or\", but it seems to work out well. As we\'ve seen that `<x>`{=html}`x` is true for any `x`, we can cancel out such tautologies. For this, we reformat the expression to a list of values of type `x` or `!x`, that is in turn dumped into a local array for existence checking. And when both `x` and `!x` exist, they are removed from the expression: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl proc lf'cancel expression { set e2 [string map {"< " ! "> " ""} [split $expression ""]] foreach term $e2 {if {$term ne ""} {set a($term) ""}} foreach var [array names a ?] { if [info exists a(!$var)] { set expression [string map [list <$var> "" $var ""] $expression] } } set expression } puts [lf'cancel {<h>c <m>p <d>a <v>n <c>k <t>h <r>&lt;p> <k>v td <n>m}] ``` ```{=html} </div> ``` which results in: - a `<r>`{=html} translated back: \"I avoid it, or it\'s not a kangaroo\", or, reordered, \"`<r>`{=html} a\" which by (4) means, \"All kangaroos are avoided by me\". ### A little IRC chat bot Here is a simple example of a \"chat bot\" --- a program that listens on an IRC chatroom, and sometimes also says something, according to its programming. The following script - connects to channel #tcl on IRC - listens to what is said - if someone mentions its name (minibot), tries to parse the message and answer. ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` tcl #!/usr/bin/env tclsh set ::server irc.freenode.org set ::chan #tcl set ::me minibot proc recv {} { gets $::fd line puts $line # handle PING messages from server if {[lindex [split $line] 0] eq "PING"} { send "PONG [info hostname] [lindex [split $line] 1]"; return } if {[regexp {:([^!]*)![^ ].* +PRIVMSG ([^ :]+) +(.*[Mm]inibot)(.+)} $line -> \ nick target msg cmd]} { if {$nick eq "ijchain"} {regexp {<([^>]+)>(.+)} $msg -> nick msg} set hit 0 foreach pattern [array names ::patterns] { if [string match "*$pattern*" $cmd] { set cmd [string trim $cmd {.,:? }] if [catch {mini eval $::patterns($pattern) $cmd} res] { set res $::errorInfo } foreach line [split $res \n] { send "PRIVMSG $::chan :$line" } incr hit break } } if !$hit {send "PRIVMSG $::chan :Sorry, no idea."} } } #----------- Patterns for response: set patterns(time) {clock format [clock sec] ;#} set patterns(expr) safeexpr proc safeexpr args {expr [string map {\[ ( \] ) expr ""} $args]} set patterns(eggdrop) {set _ "Please check http://wiki.tcl.tk/6601" ;#} set patterns(toupper) string set patterns(Windows) {set _ "I'd prefer not to discuss Windows..." ;#} set {patterns(translate "good" to Russian)} {set _ \u0425\u043E\u0440\u043E\u0448\u043E ;#} set patterns(Beijing) {set _ \u5317\u4EAC ;#} set patterns(Tokyo) {set _ \u4E1C\u4EAC ;#} set {patterns(your Wiki page)} {set _ http://wiki.tcl.tk/20205 ;#} set patterns(zzz) {set _ "zzz well!" ;#} set patterns(man) safeman proc safeman args {return http://www.tcl.tk/man/tcl8.4/TclCmd/[lindex $args 1].htm} set {patterns(where can I read about)} gotowiki proc gotowiki args {return "Try http://wiki.tcl.tk/[lindex $args end]"} set patterns(thank) {set _ "You're welcome." ;#} set patterns(worry) worry proc worry args { return "Why do [string map {I you my your your my you me} $args]?" } #-- let the show begin... :^) interp create -safe mini foreach i {safeexpr safeman gotowiki worry} { interp alias mini $i {} $i } proc in {list element} {expr {[lsearch -exact $list $element]>=0}} proc send str {puts $::fd $str;flush $::fd} set ::fd [socket $::server 6667] fconfigure $fd -encoding utf-8 send "NICK minibot" send "USER $::me 0 * :PicoIRC user" send "JOIN $::chan" fileevent $::fd readable recv vwait forever ``` ```{=html} </div> ``` Examples from the chat: ```{=html} <div style="margin:0;padding-top:0.5em;padding-bottom:0.5em"> ``` ``` text suchenwi minibot, which is your Wiki page? <minibot> http://wiki.tcl.tk/20205 suchenwi ah, thanks suchenwi minibot expr 6*7 <minibot> 42 suchenwi minibot, what's your local time? <minibot> Sun Oct 21 01:26:59 (MEZ) - Mitteleurop. Sommerzeit 2007 ``` ```{=html} </div> ```
# Tcl Programming/Tk ### Introduction The Tk (Tool Kit) is the most popular Tcl extension for designing graphical user interfaces (GUI) on Macintosh, Unix/Linux, or Windows operating systems. With little effort, it allows to put together useful - windows (forms, as some call them) consisting of - *widgets*, which are managed by - *geometry managers*. Also, you can easily define - bindings of mouse or keyboard events to trigger the actions you want. #### Example: calculator Here is a very simple, complete Tcl/Tk script that implements a calculator: `package require Tk`\ `pack [entry .e -textvar e -width 50]`\ `bind .e ``<Return>`{=html}` {`\ `   set e  [regsub { *=.*} $e ""] ;# remove evaluation (Chris)`\ `   catch {expr [string map {/ *1./} $e]} res`\ `   append e " = $res"`\ `} ` It creates an *entry* widget named *.e*, into which you can type from the keyboard, with an associated variable *e* (which will mirror the entry\'s content), and manages it with *pack*. One binding is defined: if with keyboard focus on .e, the `<Return>`{=html} key is hit, then - all division operators (/) in the variable *e* are mapped to \"\*1./\" (this forces floating point division), - the resulting string is fed to *expr* to evaluate it as an arithmetic/logic expression - as there may be errors in the user input, the *expr* call is wrapped into a *catch* which assigns either the result of *expr*, or the error message if one occurred, into the variable *res* - the result of the last evaluation is cleared by deleting everything after *=* - finally, an equal sign and the value of the *res* variable are *append*ed to *e*, making input and result immediately visible in the entry. #### Example: a tiny IRC client As before in the Tcl section, here\'s a working little script again: a client for IRC (Internet Relay Chat) in 38 lines of code, that features a **text** and an **entry** widget: ![](Picoirc.gif "Picoirc.gif") `package require Tk`\ `set ::server irc.freenode.org`\ `set ::chan   #tcl`\ `set ::me     $tcl_platform(user)`\ `text .t -height 30 -wrap word -font {Arial 9}`\ `.t tag config bold   -font [linsert [.t cget -font] end bold]`\ `.t tag config italic -font [linsert [.t cget -font] end italic]`\ `.t tag config blue   -foreground blue`\ `entry .cmd`\ `pack .cmd -side bottom -fill x`\ `pack .t -fill both -expand 1`\ `bind .cmd ``<Return>`{=html}` post`\ `proc recv {} {`\ `    gets $::fd line`\ `    if {[regexp {:([^!]*)![^ ].* +PRIVMSG ([^ :]+) +:(.*)} $line -> \`\ `        nick target msg]} {`\ `        set tag ""`\ `        if [regexp {\001ACTION(.+)\001} $msg -> msg] {set tag italic}`\ `        if [in {azbridge ijchain} $nick] {regexp {<([^>]+)>(.+)} $msg -> nick msg}`\ `       .t insert end $nick\t bold $msg\n $tag`\ `    } else {.t insert end $line\n italic}`\ `    .t yview end`\ `}`\ `proc in {list element} {expr {[lsearch -exact $list $element]>=0}}`\ `proc post {} {`\ `    set msg [.cmd get]`\ `    if [regexp {^/me (.+)} $msg -> action] {set msg "\001ACTION $action\001"}`\ `    foreach line [split $msg \n] {send "PRIVMSG $::chan :$line"}`\ `    .cmd delete 0 end`\ `    set tag ""`\ `    if [regexp {\001ACTION(.+)\001} $msg -> msg] {set tag italic}`\ `    .t insert end $::me\t {bold blue} $msg\n [list blue $tag]`\ `    .t yview end`\ `}`\ `proc send str {puts $::fd $str; flush $::fd}`\ `set ::fd [socket $::server 6667]`\ `send "NICK $::me"`\ `send "USER $::me 0 * :PicoIRC user"`\ `send "JOIN $::chan"`\ `fileevent $::fd readable recv`\ `bind . ``<Escape>`{=html}` {exec wish $argv0 &; exit}` The last line is a quick debugging helper: if you modified the script in the editor, save to disk, then hit `<Escape>`{=html} in the app to start it anew. ### Widgets Widgets are GUI objects that, when mapped by a geometry manager, correspond to a rectangular area on the screen, with different properties and capabilities. Widgets are named with *path* names, somehow resembling file system path names, except that the separator for widgets is a period \".\". For example, *.foo.bar* is a child of *foo* which is a child of \".\" Parent-child relation occurs typically with containers, e.g. *toplevel, frame, canvas, text*. The name parts (i.e. between the dots) can be almost any string that does not contain \".\" of course, or starts with a Capital Letter (this is because widget class names with capital initial have a special meaning, they denote class-wide options). If you have a proc that takes a parent widget *w* and adds children, it may be important to distinguish whether *w* is \".\" or another - because you can\'t concatenate a child widget name directly to \".\" - \$w.kid will make an invalid name if \$w == \".\". Here\'s how to avoid this: `set w2 [expr {$w eq "."? "": $w}]`\ `button $w2.$kid ...` Widgets are created by a command named after their class, which then takes the path name (requiring that parent widgets have to exist by that time) and any number of *-key value* options that make up the original configuration, e.g. `button .b -text "Hello!" -command {do something}` After creation, communication with the widget goes via a created command that corresponds to its name. For instance, the configuration options can be queried `set text [.b cget -text]` or changed `.b configure -text Goodbye! -background red` Some \"methods\" like *cget, configure* are generic to all widget classes, others are specific to one or a few. For instance, both \'text*and*entry*accept the*insert\'\' method. See the manual pages for all the details. Widgets appear on screen only after they have been given to a **geometry manager** (see more below). Example: `text .t -wrap word`\ `pack .t -fill both -expand 1` As widget creation commands return the pathname, these two steps can also be nested like `pack [text .t -wrap word] -fill both -expand 1` The **destroy** command deletes a widget and all of its child widgets, if present: `destroy .b` The following sub-chapters describe the widgets available in Tk. ------------------------------------------------------------------------ #### button With text and/or image, calls a configurable command when clicked. Example: `button .b -text Hello! -command {puts "hello, world"}` #### canvas Scrollable graphic surface for line, rectangle, polygon, oval, and text items, as well as bitmaps and photo images and whole embedded windows. See for example \"A tiny drawing program\" below. Example: `pack [canvas .c -background white]`\ `.c create line 50 50 100 100 150 50 -fill red -width 3`\ `.c create text 100 50 -text Example` **Pan a canvas** (scroll it inside its window with middle mouse-button held down) by inheriting the text widget bindings: ` bind .c <2> [bind Text <2>]`\ ` bind .c ``<B2-Motion>`{=html}` [bind Text ``<B2-Motion>`{=html}`]` #### entry One-line editable text field, horizontally scrollable (see example above). You can specify a validation function to constrain what is entered. Example: `entry .e -width 20 -textvariable myVar`\ `set myVar "this text appears in the entry"` #### frame Container for several widgets, often used with *pack*, or for wrapping \"megawidgets\" #### label One- or multiline field for text display, can be tied to a text variable to update when that variable changes. Linebreaks are specified by \\n in the text to be displayed. #### labelframe A container similar to a **frame**, decorated with a thin rectangle around, and a label at top-left position. Example (a tiny radio band selector): `pack [labelframe .lf -text Band]`\ `pack [radiobutton .lf.am -text AM -variable band -value AM]`\ `pack [radiobutton .lf.fm -text FM -variable band -value FM]`\ `set band AM` ![](Labelframe_radiobuttons.jpg "Labelframe_radiobuttons.jpg") #### listbox Multiline display of a list, scrollable. Single or multiple items can be selected with the mouse. #### menu To add a menu to a GUI application, take steps of three kinds: - Create the toplevel horizontal menu (needed only once): `. configure -menu [menu .m]` - For each item in the top menu, create a cascaded submenu, e.g. `.m add cascade -label File -menu [menu .m.mFile]` - For each entry in a submenu, add it like this: `.m.mFile add command -label Open -command {openFile ...}`\ `.m.mFile add separator` As these commands are a bit verbose, one can wrap them into a little helper: `proc m+ {head name {cmd ""}} {`\ `   if {![winfo exists .m.m$head]} {`\ `        .m add cascade -label $head -menu [menu .m.m$head -tearoff 0]`\ `   }`\ `   if [regexp ^-+$ $name] {`\ `           .m.m$head add separator`\ `   } else {.m.m$head add command -label $name -comm $cmd}`\ `}` Demo example - now menu items can be created in a much clearer way: `. configure -menu [menu .m]`\ `m+ File Open {.t insert end "opened\n"}`\ `m+ File Save {.t insert end "saved\n"}`\ `m+ File -----`\ `m+ File Exit exit`\ `m+ Edit Cut ...`\ `pack [text .t -wrap word] -fill both -expand 1` #### radiobutton A button with a selector field which can be on or off, and a label. Clicking the selector field with the mouse changes the value of an associated global variable. Typically, multiple radiobuttons are tied to the same variable. For examples, see **labelframe** above. #### scrollbar Horizontal or vertical scrollbars (vertical being the default, for horizontal specify: -orientation horizontal, or -ori hori if you like it short) can be tied to canvas, entry, listbox or text widgets. The interaction between a scrollbar and its scrolled widget goes with callbacks, in which one notifies the other: - scrollbar to widget: *xview* or *yview* method - widget to scrollbar: *set* method Arguments to these methods will be automatically added when the callbacks are invoked. For example, here\'s how to connect a text widget with a vertical scrollbar: `pack [scrollbar .y -command ".t yview"] -side right -fill y`\ `pack [text .t -wrap word -yscrollc ".y set"] \`\ `     -side right -fill both -expand 1` With most widgets, scrollbars adjust automatically to the widget\'s contents. For canvas widgets, you need to update the scrollregion after adding new items. most simply like this: `$canvas configure -scrollregion [$canvas bbox all]` #### text Scrollable editable multiline text with many formatting options. Can also contain images and embedded widgets. The default wrapping setting is \"none\", so you might need a horizontal scrollbar to see all of long lines. In many cases it\'s more user-friendly to configure a text widget as *-wrap word* - then you only need a vertical scrollbar at most. Positions in a text widget are specified as *line.column*, where line starts from 1, and column from 0, so 1.0 is the very first character in a text widget. Example how to delete all contents: `$t delete 1.0 end` For highlighting part of the contents, you can define *tags* and assign them to subsequences: `$t tag configure ul -underline 1`\ `$t insert end "The next word is " {} underlined ul ", the rest is not."` #### toplevel Standalone frame window, mostly with decorations (title bar, buttons) from the window manager. When you start Tk, you receive an initially empty toplevel named \".\" (one dot). If you want more toplevels, create them like this: `toplevel .mySecondWindow` Such toplevels are logically children of \".\". To assign a nice title to a toplevel, use `wm title $toplevel "This is the title"` You can also control the geometry (size and position) of a toplevel with `wm geometry $toplevel ${width}x$height+$x+$y` ------------------------------------------------------------------------ ### Geometry managers ------------------------------------------------------------------------ The purpose of geometry managers is to compute the required height, width, and location of widgets, and map them on screen. Besides *grid*, *pack* and *place*, the *canvas* and *text* widgets can also manage embedded widgets. Calls to geometry managers always start with the manager\'s name, then (mostly) one or more widget names, then any number of *-name value* options #### grid This geometry manager is best suited for tabular window layout consisting of rows and columns. Example, to put three widgets in a horizontal row: `grid .1 .2 .3 -sticky news` The *-sticky* option indicates what side of its box the widget should stick to, in compass direction; \"news\" is north-east-west-south\", i.e. all four sides. Here\'s a minimal solution to display a table (list of lists) in a grid of labels: ![](grid_table.jpg "grid_table.jpg") `package require Tk`\ `proc table {w content args} {`\ `    frame $w -bg black`\ `    set r 0`\ `    foreach row $content {`\ `        set fields {}`\ `        set c 0`\ `        foreach col $row {`\ `            lappend fields [label $w.$r/$c -text $col]`\ `            incr c`\ `        }`\ `        eval grid $fields -sticky news -padx 1 -pady 1`\ `        incr r`\ `    }`\ `    set w`\ `}` `#--- Test:`\ `table .t {`\ `   {Row Head1 Head2}`\ `   {1   foo   42}`\ `   {2   bar   1234}`\ `   {3   grill testing}`\ `}`\ `pack .t` `#--- Changing the contents, given row and column number:`\ `after 2000 .t.3/2 config -text Coucou` #### pack This used to be the workhorse manager, but in recent years has been less popular than **grid**. Anyway, it is still good for cases where you have widgets aligned in only one direction (horizontally or vertically). For more complex layouts, one used to insert intermediate frames, but grid makes such jobs just easier. Example: `pack .x -fill both -expand 1 -side left` #### place This geometry manager is not often used, mostly for special applications, like when you want to highlight the current tab of a tab notebook. It allows pixel-precise placement of widgets, but is less dynamic in reaction to resizing of the toplevel or inner widgets. ### Dialogs Dialogs are toplevels that are to tell a message, or answer a question. You don\'t have to assign a widget path name to them. Just call them as functions and evaluate the result (often \"\" if the dialog was canceled). #### tk_getOpenFile A file selector dialog (limited to existing files). Returns the selected file with path name, or \"\" if canceled. #### tk_getSaveFile A file selector dialog, which also allows specification of a not existing file. Returns the selected file with path name, or \"\" if canceled. #### tk_messageBox A simple dialog that displays a string and can be closed with an \"OK\" button. Example: `tk_messageBox -message "hello, world!"` #### tk_chooseColor Displays a dialog for color selection. The returned value is the selected color in one of the representations conformant to Tcl\'s comprehension of such information; on Microsoft Windows systems this might constitute a hexadecimal string in the format "#RRGGBB". Upon abortion of the process, the empty string is instead delivered. The dialog may be configured to preselect a certain default color via the "-initialcolor" option, a subordination into a parent widget with "-parent", and a title caption through "-title". ` tk_chooseColor -initialcolor #FF0000 -parent . -title "What tincture do you wish?"` #### Custom dialogs Besides the prefabricated dialogs that come with Tk, it\'s also not too hard to build custom ones. As a very simple example, here\'s a \"value dialog\" that prompts the user for to type in a value: ![](ValueDialog.jpg "ValueDialog.jpg") `proc value_dialog {string} {`\ `   set w [toplevel .[clock seconds]]`\ `   wm resizable $w 0 0`\ `   wm title $w "Value request"`\ `   label  $w.l -text $string`\ `   entry  $w.e -textvar $w -bg white`\ `   bind $w.e ``<Return>`{=html}` {set done 1}`\ `   button $w.ok     -text OK     -command {set done 1}`\ `   button $w.c      -text Clear  -command "set $w {}"`\ `   button $w.cancel -text Cancel -command "set $w {}; set done 1"`\ `   grid $w.l  -    -        -sticky news`\ `   grid $w.e  -    -        -sticky news`\ `   grid $w.ok $w.c $w.cancel`\ `   vwait done`\ `   destroy $w`\ `   set ::$w`\ `}` Test: `set test [value_dialog "Give me a value please:"]`\ `puts test:$test`\ `pack [ label .l -text "Value: '$test' " ]` For a more elaborate example, here is a record editor dialog (multiple fields, each with a label and entry (or text for multi-line input)): `proc editRecord {title headers fields} {`\ `    set oldfocus [focus]`\ `    set w [toplevel .[clock clicks]]`\ `    wm resizable $w 1 0`\ `    wm title $w $title`\ `    set n 0`\ `    foreach h $headers f $fields {`\ `        if ![regexp {(.+)([=+])} $h -> hdr type] {set hdr $h; set type ""}`\ `        label $w.h$n -text $hdr -anchor ne`\ `        switch -- $type {`\ `            = {label $w.e$n -width [string length $f] -text $f -anchor w -bg white}`\ `            + {[text $w.e$n -width 20 -height 6] insert end $f}`\ `            default {[entry $w.e$n -width [string length $f]] insert end $f}`\ `        }`\ `        grid $w.h$n $w.e$n -sticky news`\ `        incr n`\ `    }`\ `    button $w.ok -text OK -width 5 -command [list set $w 1]`\ `    button $w.cancel -text Cancel -command [list set $w 0]`\ `    grid $w.ok $w.cancel -pady 5`\ `    grid columnconfigure $w 1 -weight 1`\ `    vwait ::$w`\ `    if [set ::$w] { #-- collect the current entry contents`\ `        set n 0`\ `        foreach h $headers f $fields {`\ `            regexp {([^=+].+)([=+]?)} $h -> hdr type`\ `            switch -- $type {`\ `                "" {lappend res [$w.e$n get]}`\ `                =  {lappend res [$w.e$n cget -text]}`\ `                +  {lappend res [$w.e$n get 1.0 end]}`\ `            }`\ `            incr n`\ `        }`\ `    } else {set res {}}`\ `    destroy $w`\ `    unset ::$w ;#-- clean up the vwait variable`\ `    focus $oldfocus`\ `    return $res`\ `}` Quick test: `editRecord Test {foo= bar grill+} {one two three}` ### Megawidgets made easy The term \"megawidgets\" is popular for compound widgets that in themselves contain other widgets, even though they will hardly number a million (what the prefix *Mega-* suggests), more often the child widgets\' number will not exceed ten. To create a megawidget, one needs one proc with the same signature as Tk widget creation commands. This proc will, when called, create another proc named after the widget, and dispatch methods either to specific handlers, or the generic widget command created by Tk. #### A little notebook Plain Tk does not contain a \"notebook\" widget, with labeled tabs on top that raise one of the \"pages\", but it\'s easy to make one. This example demonstrates how the tabs are implemented as buttons in a frame, and how the original Tk command named like the frame is \"overloaded\" to accept the additional *add* and *raise* methods: `proc notebook {w args} {`\ `   frame $w`\ `   pack [frame $w.top] -side top -fill x -anchor w`\ `   rename $w _$w`\ `   proc $w {cmd args} { #-- overloaded frame command`\ `       set w [lindex [info level 0] 0]`\ `       switch -- $cmd {`\ `           add     {notebook'add   $w $args}`\ `           raise   {notebook'raise $w $args}`\ `           default {eval [linsert $args 0 _$w $cmd]}`\ `       }`\ `   }`\ `   return $w`\ `}` `proc notebook'add {w title} {`\ `   set btn [button $w.top.b$title -text $title -command [list $w raise $title]]`\ `   pack $btn -side left -ipadx 5`\ `   set f [frame $w.f$title -relief raised -borderwidth 2]`\ `   pack $f -fill both -expand 1`\ `   $btn invoke`\ `   bind $btn <3> "destroy {$btn}; destroy {$f}" ;# (1)`\ `   return $f`\ `}` `proc notebook'raise {w title} {`\ `   foreach i [winfo children $w.top] {$i config -borderwidth 0}`\ `   $w.top.b$title config -borderwidth 1`\ `   set frame $w.f$title`\ `   foreach i [winfo children $w] {`\ `       if {![string match *top $i] && $i ne $frame} {pack forget $i}`\ `   }`\ `   pack $frame -fill both -expand 1`\ `}` Test and demo code: `package require Tk`\ `pack [notebook .n] -fill both -expand 1`\ `set p1 [.n add Text]`\ `pack   [text $p1.t -wrap word] -fill both -expand 1`\ `set p2 [.n add Canvas]`\ `pack   [canvas $p2.c -bg yellow] -fill both -expand 1`\ `set p3 [.n add Options]`\ `pack   [button $p3.1 -text Console -command {console show}]`\ `.n raise Text`\ `wm geometry . 400x300` ### Binding events Events within Tcl/Tk include actions performed by the user, such as pressing a key or clicking the mouse. To react to mouse and keyboard activity, the bind command is used. As shown in the calculator example: ``` tcl pack [entry .e -textvar e -width 50] bind .e <Return> { ``` The `bind` keyword operates on `.e` and associates the event related to the `<return>` event. The following bracket indicates a start of a set of procedures which are executed when the event is performed. ### BWidget BWidget is an extension to Tk written in pure Tcl (therefore it can even run on Windows Mobile-driven cell phones). It offers mega-widgets (all class names starting with Uppercase) like - ComboBox - NoteBook - Tree !`ifile01.jpg` *Screenshot of a NoteBook and a Tree, on a PocketPC under Windows/CE* #### Tree examples Here is a \"hello world\" example of a Tree widget (this is a complete script). The root node is constantly called *root*, for the others you have to make up names: `package require BWidget`\ `pack [Tree .t]`\ `.t insert end root n1  -text hello`\ `.t insert end root n2  -text world`\ `.t insert end n2   n21 -text (fr:monde)`\ `.t insert end n2   n22 -text (de:Welt)` The famous typewriter test sentence represented as a syntax tree: `package require BWidget`\ `pack [Tree .t -height 16] -fill both -expand 1`\ `foreach {from to text} {`\ `   root S S`\ `   S   np1  NP`\ `   S   vp   VP`\ `   np1 det1 Det:The`\ `   np1 ap1  AP`\ `   ap1 adj1 Adj:quick`\ `   ap1 adj2 Adj:brown`\ `   ap1 n1   N:fox`\ `   vp  v    V:jumps`\ `   vp  pp   PP`\ `   pp  prep Prep:over`\ `   pp  np2  NP`\ `   np2 det2 Det:the`\ `   np2 ap2  AP`\ `   ap2 adj3 Adj:lazy`\ `   ap2 n2   N:dog`\ `   `\ `} {.t insert end $from $to -text $text}`\ `.t opentree S` ### Tk resources #### Colors Colors in Tk can be specified in three ways: - a symbolic name, like: red green blue yellow magenta cyan - a hex string preceded by a #: #RGB, #RRGGBB, #RRRRGGGGBBBB - a list of three non-negative integers The last form is only returned by commands. To specify a color to a command, you\'ll have to hex-format it. For instance, white could be described as #FFFFFF. To turn a symbolic name into its RGB components: `winfo rgb . $colorname` Here is the list of defined color names (as from X11\'s rgb.txt): `set COLORS { snow {ghost white} {white smoke} gainsboro {floral white}`\ `   {old lace} linen {antique white} {papaya whip} {blanched almond}`\ `   bisque {peach puff} {navajo white} moccasin cornsilk ivory {lemon`\ `   chiffon} seashell honeydew {mint cream} azure {alice blue}`\ `   lavender {lavender blush} {misty rose} white black {dark slate`\ `   gray} {dim gray} {slate gray} {light slate gray} gray {light grey}`\ `   {midnight blue} navy {cornflower blue} {dark slate blue} {slate`\ `   blue} {medium slate blue} {light slate blue} {medium blue} {royal`\ `   blue} blue {dodger blue} {deep sky blue} {sky blue} {light sky`\ `   blue} {steel blue} {light steel blue} {light blue} {powder blue}`\ `   {pale turquoise} {dark turquoise} {medium turquoise} turquoise`\ `   cyan {light cyan} {cadet blue} {medium aquamarine} aquamarine`\ `   {dark green} {dark olive green} {dark sea green} {sea green}`\ `   {medium sea green} {light sea green} {pale green} {spring green}`\ `   {lawn green} green chartreuse {medium spring green} {green yellow}`\ `   {lime green} {yellow green} {forest green} {olive drab} {dark`\ `   khaki} khaki {pale goldenrod} {light goldenrod yellow} {light`\ `   yellow} yellow gold {light goldenrod} goldenrod {dark goldenrod}`\ `   {rosy brown} {indian red} {saddle brown} sienna peru burlywood`\ `   beige wheat {sandy brown} tan chocolate firebrick brown {dark`\ `   salmon} salmon {light salmon} orange {dark orange} coral {light`\ `   coral} tomato {orange red} red {hot pink} {deep pink} pink {light`\ `   pink} {pale violet red} maroon {medium violet red} {violet red}`\ `   magenta violet plum orchid {medium orchid} {dark orchid} {dark`\ `   violet} {blue violet} purple {medium purple} thistle snow2 snow3`\ `   snow4 seashell2 seashell3 seashell4 AntiqueWhite1 AntiqueWhite2`\ `   AntiqueWhite3 AntiqueWhite4 bisque2 bisque3 bisque4 PeachPuff2`\ `   PeachPuff3 PeachPuff4 NavajoWhite2 NavajoWhite3 NavajoWhite4`\ `   LemonChiffon2 LemonChiffon3 LemonChiffon4 cornsilk2 cornsilk3`\ `   cornsilk4 ivory2 ivory3 ivory4 honeydew2 honeydew3 honeydew4`\ `   LavenderBlush2 LavenderBlush3 LavenderBlush4 MistyRose2 MistyRose3`\ `   MistyRose4 azure2 azure3 azure4 SlateBlue1 SlateBlue2 SlateBlue3`\ `   SlateBlue4 RoyalBlue1 RoyalBlue2 RoyalBlue3 RoyalBlue4 blue2 blue4`\ `   DodgerBlue2 DodgerBlue3 DodgerBlue4 SteelBlue1 SteelBlue2`\ `   SteelBlue3 SteelBlue4 DeepSkyBlue2 DeepSkyBlue3 DeepSkyBlue4`\ `   SkyBlue1 SkyBlue2 SkyBlue3 SkyBlue4 LightSkyBlue1 LightSkyBlue2`\ `   LightSkyBlue3 LightSkyBlue4 SlateGray1 SlateGray2 SlateGray3`\ `   SlateGray4 LightSteelBlue1 LightSteelBlue2 LightSteelBlue3`\ `   LightSteelBlue4 LightBlue1 LightBlue2 LightBlue3 LightBlue4`\ `   LightCyan2 LightCyan3 LightCyan4 PaleTurquoise1 PaleTurquoise2`\ `   PaleTurquoise3 PaleTurquoise4 CadetBlue1 CadetBlue2 CadetBlue3`\ `   CadetBlue4 turquoise1 turquoise2 turquoise3 turquoise4 cyan2 cyan3`\ `   cyan4 DarkSlateGray1 DarkSlateGray2 DarkSlateGray3 DarkSlateGray4`\ `   aquamarine2 aquamarine4 DarkSeaGreen1 DarkSeaGreen2 DarkSeaGreen3`\ `   DarkSeaGreen4 SeaGreen1 SeaGreen2 SeaGreen3 PaleGreen1 PaleGreen2`\ `   PaleGreen3 PaleGreen4 SpringGreen2 SpringGreen3 SpringGreen4`\ `   green2 green3 green4 chartreuse2 chartreuse3 chartreuse4`\ `   OliveDrab1 OliveDrab2 OliveDrab4 DarkOliveGreen1 DarkOliveGreen2`\ `   DarkOliveGreen3 DarkOliveGreen4 khaki1 khaki2 khaki3 khaki4`\ `   LightGoldenrod1 LightGoldenrod2 LightGoldenrod3 LightGoldenrod4`\ `   LightYellow2 LightYellow3 LightYellow4 yellow2 yellow3 yellow4`\ `   gold2 gold3 gold4 goldenrod1 goldenrod2 goldenrod3 goldenrod4`\ `   DarkGoldenrod1 DarkGoldenrod2 DarkGoldenrod3 DarkGoldenrod4`\ `   RosyBrown1 RosyBrown2 RosyBrown3 RosyBrown4 IndianRed1 IndianRed2`\ `   IndianRed3 IndianRed4 sienna1 sienna2 sienna3 sienna4 burlywood1`\ `   burlywood2 burlywood3 burlywood4 wheat1 wheat2 wheat3 wheat4 tan1`\ `   tan2 tan4 chocolate1 chocolate2 chocolate3 firebrick1 firebrick2`\ `   firebrick3 firebrick4 brown1 brown2 brown3 brown4 salmon1 salmon2`\ `   salmon3 salmon4 LightSalmon2 LightSalmon3 LightSalmon4 orange2`\ `   orange3 orange4 DarkOrange1 DarkOrange2 DarkOrange3 DarkOrange4`\ `   coral1 coral2 coral3 coral4 tomato2 tomato3 tomato4 OrangeRed2`\ `   OrangeRed3 OrangeRed4 red2 red3 red4 DeepPink2 DeepPink3 DeepPink4`\ `   HotPink1 HotPink2 HotPink3 HotPink4 pink1 pink2 pink3 pink4`\ `   LightPink1 LightPink2 LightPink3 LightPink4 PaleVioletRed1`\ `   PaleVioletRed2 PaleVioletRed3 PaleVioletRed4 maroon1 maroon2`\ `   maroon3 maroon4 VioletRed1 VioletRed2 VioletRed3 VioletRed4`\ `   magenta2 magenta3 magenta4 orchid1 orchid2 orchid3 orchid4 plum1`\ `   plum2 plum3 plum4 MediumOrchid1 MediumOrchid2 MediumOrchid3`\ `   MediumOrchid4 DarkOrchid1 DarkOrchid2 DarkOrchid3 DarkOrchid4`\ `   purple1 purple2 purple3 purple4 MediumPurple1 MediumPurple2`\ `   MediumPurple3 MediumPurple4 thistle1 thistle2 thistle3 thistle4`\ `   gray1 gray2 gray3 gray4 gray5 gray6 gray7 gray8 gray9 gray10`\ `   gray11 gray12 gray13 gray14 gray15 gray16 gray17 gray18 gray19`\ `   gray20 gray21 gray22 gray23 gray24 gray25 gray26 gray27 gray28`\ `   gray29 gray30 gray31 gray32 gray33 gray34 gray35 gray36 gray37`\ `   gray38 gray39 gray40 gray42 gray43 gray44 gray45 gray46 gray47`\ `   gray48 gray49 gray50 gray51 gray52 gray53 gray54 gray55 gray56`\ `   gray57 gray58 gray59 gray60 gray61 gray62 gray63 gray64 gray65`\ `   gray66 gray67 gray68 gray69 gray70 gray71 gray72 gray73 gray74`\ `   gray75 gray76 gray77 gray78 gray79 gray80 gray81 gray82 gray83`\ `   gray84 gray85 gray86 gray87 gray88 gray89 gray90 gray91 gray92`\ `   gray93 gray94 gray95 gray97 gray98 gray99`\ `}` In addition, the following are defined on Windows: `set WINDOWSCOLORS {`\ `   SystemButtonFace SystemButtonText SystemDisabledText SystemHighlight`\ `   SystemHightlightText SystemMenu SystemMenuText SystemScrollbar`\ `   SystemWindow SystemWindowFrame SystemWindowText`\ `}` #### Cursors For every widget, you can specify how the mouse cursor should look when over it. Here\'s the list of defined cursor names: `set cursors {`\ `   X_cursor arrow based_arrow_down based_arrow_up boat bogosity`\ `   bottom_left_corner bottom_right_corner bottom_side bottom_tee`\ `   box_spiral center_ptr circle clock coffee_mug cross cross_reverse`\ `   crosshair diamond_cross dot dotbox double_arrow draft_large draft_small`\ `   draped_box exchange fleur gobbler gumby hand1 hand2 heart icon`\ `   iron_cross left_ptr left_side left_tee leftbutton ll_angle lr_angle`\ `   man middlebutton mouse pencil pirate plus question_arrow right_ptr`\ `   right_side right_tee rightbutton rtl_logo sailboat sb_down_arrow`\ `   sb_h_double_arrow sb_left_arrow sb_right_arrow sb_up_arrow`\ `   sb_v_double_arrow shuttle sizing spider spraycan star target tcross`\ `   top_left_arrow top_left_corner top_right_corner top_side top_tee `\ `   trek ul_angle umbrella ur_angle watch xterm`\ `}` A little tool that presents the cursor names, and shows each cursor shape when mousing over: `set ncols 4`\ `for {set i 0} {$i<$ncols} {incr i} {`\ `   lappend cols col$i`\ `}`\ `set nmax [expr {int([llength $cursors]*1./$ncols)}]`\ `foreach col $cols {`\ `   set $col [lrange $cursors 0 $nmax]`\ `   set cursors [lrange $cursors [expr $nmax+1] end]`\ `}`\ `label .top -text "Move the cursor over a name to see how it looks" \`\ `   -relief ridge`\ `grid .top -columnspan $ncols -sticky news -ipady 2`\ `for {set i 0} {$i<[llength $col0]} {incr i} {`\ `   set row {}`\ `   foreach col $cols {`\ `       set name [lindex [set $col] $i]`\ `       if {$name eq ""} break`\ `       lappend row .l$name`\ `       label .l$name -text $name -anchor w`\ `       bind .l$name ``<Enter>`{=html}` [list %W config -cursor $name]`\ `   }`\ `   eval grid $row -sticky we`\ `}` #### Fonts Fonts are provided by the windowing system. Which are available depends on the local installation. Find out which fonts are available with `font families` The typical description of a font is a list of up to three elements: `family size ?style?` Example: `set f ``{{Bitstream Cyberbit} 10 bold} Family is a name like Courier, Helvetica, Times, ... Best pick one of the names delivered by ''font families'', though there may be some mappings like "Helvetica" -> "Arial" Size is point size (a typographer's point is 1/72th of an inch) if positive, or pixel size if negative. Normal display fonts often have a size of 9 or 10. Style can be a list of zero or more of bold, italic, underlined, ... ==== Images: photos and bitmaps ==== Tk allows simple yet powerful operations on images. These come in two varieties: bitmaps and photos. Bitmaps are rather limited in functionality, they can be specified in XBM format, and rendered in configurable colors. Photos have much more possibilities - you can load and save them in different file formats (Tk itself supports PPM and GIF - for others, use the Img extension), copy them with many options, like scaling/subsampling or mirroring, and get or set the color of single pixels. Setting can also do rectangular regions in one go, as the following example shall demonstrate that creates a photo image of a tricolore flag (three even-spaced vertical bands - like France, Italy, Belgium, Ireland and many more). The default is France. You can specify the width, the height will be 2/3 of that. The procedure returns the image name - just save it in -format GIF if you want: proc tricolore {w {colors {blue white red}}`{=mediawiki}`} {`\ `   set im [image create photo]`\ `   set fromx 0`\ `   set dx [expr $w/3]`\ `   set tox $dx`\ `   set toy [expr $w*2/3]`\ `   foreach color $colors {`\ `       $im put $color -to $fromx 0 $tox $toy`\ `       incr fromx $dx; incr tox $dx`\ `   }`\ `   set im`\ `}` `# Test - display flag on canvas:`\ `pack [canvas .c -width 200 -height 200 -background grey]`\ `.c create image 100 100 -image [tricolore 150]` `# Test - save image of flag to file:`\ `[tricolore 300] write tric.gif -format gif` ### Debugging Tk programs A Tk program under development can be very rapidly debugged by adding such bindings: `bind . ``<F1>`{=html}` {console show}` This works only on Windows and Macintosh (pre-OS-X) and brings up a console in which you can interact with the Tcl interpreter, inspect or modify global variables, configure widgets, etc. `bind . ``<Escape>`{=html}` {eval [list exec wish $argv0] $argv &; exit}` This starts a new instance of the current program (assuming you edited a source file and saved it to disk), and then terminates the current instance. For short debugging output, one can also use the window\'s title bar. For example, to display the current mouse coordinates when it moves: `bind . ``<Motion>`{=html}` {wm title . %X/%Y}` ### Other languages Other programming languages have modules that interface and use Tcl/Tk: - In R (programming language), there\'s a tcltk library, invoked with the command **library(tcltk)** - In Python, there\'s a tkinter module, invoked with **import tkinter** or **from tkinter import \*** - Common Lisp can communicate with Tcl/Tk via several externally available libraries, including **CL-TK** and **LTK**
# Tcl Programming/Tk examples The following examples originally appeared in the Tcler\'s Wiki <http://wiki.tcl.tk> . They are all in the public domain - no rights reserved. ### A funny cookbook This funny little program produces random cooking recipes. Small as it is, it can produce 900 different recipes, though they might not be to everybody\'s taste\... The basic idea is to pick an arbitrary element from a list, which is easily done in Tcl with the following: `proc ? L {lindex $L [expr {int(rand()*[llength $L])}]}` This is used several times in: `proc recipe {} {`\ `  set a {`\ `    {3 eggs} {an apple} {a pound of garlic}`\ `    {a pumpkin} {20 marshmallows}`\ `  }`\ `  set b {`\ `    {Cut in small pieces} {Dissolve in lemonade}`\ `    {Bury in the ground for 3 months}`\ `    {Bake at 300 degrees} {Cook until tender}`\ `  }`\ `  set c {parsley snow nutmeg curry raisins cinnamon}`\ `  set d {`\ `     ice-cream {chocolate cake} spinach {fried potatoes} rice {soy sprouts}`\ `  }`\ `  return "   Take [? $a].`\ `  [? $b].`\ `  Top with [? $c].`\ `  Serve with [? $d]."`\ `}` And as modern programs always need a GUI, here is a minimal one that appears when you source this file at top level, and shows a new recipe every time you click on it: `if {[file tail [info script]]==[file tail $argv0]} {`\ `  package require Tk`\ `  pack [text .t -width 40 -height 5]`\ `  bind .t <1> {showRecipe %W; break}`\ `  proc showRecipe w {`\ `    $w delete 1.0 end`\ `    $w insert end [recipe]`\ `  }`\ `  showRecipe .t`\ `}` Enjoy! ### A little A/D clock This is a clock that shows time either analog or digital - just click on it to toggle. #!/usr/bin/env tclsh package require Tk proc every {ms body} {eval $body; after $ms [info level 0]} proc drawhands w { $w delete hands set secSinceMidnight [expr {[clock sec]-[clock scan 00:00:00]}] foreach divisor {60 3600 43200} length {45 40 30} width {1 3 7} { set angle [expr {$secSinceMidnight * 6.283185 / $divisor}] set x [expr {50 + $length * sin($angle)}] set y [expr {50 - $length * cos($angle)}] $w create line 50 50 $x $y -width $width -tags hands } } proc toggle {w1 w2} { if [winfo ismapped $w2] { foreach {w2 w1} [list $w1 $w2] break ;# swap } pack forget $w1 pack $w2 } #-- Creating the analog clock: canvas .analog -width 100 -height 100 -bg white every 1000 {drawhands .analog} pack .analog #-- Creating the digital clock: label .digital -textvar ::time -font {Courier 24} every 1000 {set ::time [clock format [clock sec] -format %H:%M:%S]} bind . <1> {toggle .analog .digital} ### A little pie chart image:TkPiechart.jpg Arc elements of a canvas are by default rendered as pie slices (part of the circumference of a circle, connected by radius lines to the center. Hence it s rather easy to produce a pie chart. The following code is a bit more complex, as it also determines positions for the labels of the pies: `proc piechart {w x y width height data} {`\ `   set coords [list $x $y [expr {$x+$width}] [expr {$y+$height}]]`\ `   set xm  [expr {$x+$width/2.}]`\ `   set ym  [expr {$y+$height/2.}]`\ `   set rad [expr {$width/2.+20}]`\ `   set sum 0`\ `   foreach item $data {set sum [expr {$sum + [lindex $item 1]}]}`\ `   set start 270`\ `   foreach item $data {`\ `       foreach {name n color} $item break`\ `       set extent [expr {$n*360./$sum}]`\ `       $w create arc $coords -start $start -extent $extent -fill $color`\ `       set angle [expr {($start-90+$extent/2)/180.*acos(-1)}]`\ `       set tx [expr $xm-$rad*sin($angle)]`\ `       set ty [expr $ym-$rad*cos($angle)]`\ `       $w create text $tx $ty -text $name:$n  -tag txt`\ `       set start [expr $start+$extent]`\ `   }`\ `   $w raise txt`\ `}` Testing: `pack [canvas .c -bg white]`\ `piechart .c 50 50 150 150 {`\ `   {SPD  199 red}`\ `   {CDU  178 gray}`\ `   {CSU   23 blue}`\ `   {FDP   60 yellow}`\ `   {Grüne 58 green}`\ `   {Linke 55 purple}`\ `}` ### A little 3D bar chart image:3DBarchart.jpg The following script displays a bar chart on a canvas, with pseudo-3-dimensional bars - a rectangle in front as specified, embellished with two polygons - one for the top, one for the side:} `proc 3drect {w args} {`\ `   if [string is int -strict [lindex $args 1]] {`\ `      set coords [lrange $args 0 3]`\ `   } else {`\ `      set coords [lindex $args 0]`\ `   }`\ `   foreach {x0 y0 x1 y1} $coords break`\ `   set d [expr {($x1-$x0)/3}]`\ `   set x2 [expr {$x0+$d+1}]`\ `   set x3 [expr {$x1+$d}]`\ `   set y2 [expr {$y0-$d+1}]`\ `   set y3 [expr {$y1-$d-1}]`\ `   set id [eval [list $w create rect] $args]`\ `   set fill [$w itemcget $id -fill]`\ `   set tag [$w gettags $id]`\ `   $w create poly $x0 $y0 $x2 $y2 $x3 $y2 $x1 $y0 \`\ `       -fill [dim $fill 0.8] -outline black`\ `   $w create poly $x1 $y1 $x3 $y3 $x3 $y2 $x1 $y0 \`\ `       -fill [dim $fill 0.6] -outline black -tag $tag`\ `}` For a more plastic look, the fill color of the polygons is reduced in brightness (\"dimmed\"): `proc dim {color factor} {`\ `  foreach i {r g b} n [winfo rgb . $color] d [winfo rgb . white] {`\ `     set $i [expr int(255.*$n/$d*$factor)]`\ `  }`\ `  format #%02x%02x%02x $r $g $b`\ `}` Draw a simple scale for the y axis, and return the scaling factor: `proc yscale {w x0 y0 y1 min max} {`\ `  set dy   [expr {$y1-$y0}]`\ `  regexp {([1-9]+)} $max -> prefix`\ `  set stepy [expr {1.*$dy/$prefix}]`\ `  set step [expr {$max/$prefix}]`\ `  set y $y0`\ `  set label $max`\ `  while {$label>=$min} {`\ `     $w create text $x0 $y -text $label -anchor w`\ `     set y [expr {$y+$stepy}]`\ `     set label [expr {$label-$step}]`\ `  }`\ `  expr {$dy/double($max)}`\ `}` An interesting sub-challenge was to round numbers very roughly, to 1 or maximally 2 significant digits - by default rounding up, add \"-\" to round down: `proc roughly {n {sgn +}} {`\ `  regexp {(.+)e([+-])0*(.+)} [format %e $n] -> mant sign exp`\ `  set exp [expr $sign$exp]`\ `  if {abs($mant)<1.5} {`\ `     set mant [expr $mant*10]`\ `     incr exp -1`\ `  }`\ `  set t [expr round($mant $sgn 0.49)*pow(10,$exp)]`\ `  expr {$exp>=0? int($t): $t}`\ `}` So here is my little bar chart generator. Given a canvas pathname, a bounding rectangle, and the data to display (a list of {name value color} triples), it figures out the geometry. A gray \"ground plane\" is drawn first. Note how negative values are tagged with \"d\"(eficit), so they look like they \"drop through the plane\". `proc bars {w x0 y0 x1 y1 data} {`\ `   set vals 0`\ `   foreach bar $data {`\ `      lappend vals [lindex $bar 1]`\ `   }`\ `   set top [roughly [max $vals]]`\ `   set bot [roughly [min $vals] -]`\ `   set f [yscale $w $x0 $y0 $y1 $bot $top]`\ `   set x [expr $x0+30]`\ `   set dx [expr ($x1-$x0-$x)/[llength $data]]`\ `   set y3 [expr $y1-20]`\ `   set y4 [expr $y1+10]`\ `   $w create poly $x0 $y4 [expr $x0+30] $y3 $x1 $y3 [expr $x1-20] $y4 -fill gray65`\ `   set dxw [expr $dx*6/10]`\ `   foreach bar $data {`\ `      foreach {txt val col} $bar break`\ `      set y [expr {round($y1-($val*$f))}]`\ `      set y1a $y1`\ `      if {$y>$y1a} {swap y y1a}`\ `      set tag [expr {$val<0? "d": ""}]`\ `      3drect $w $x $y [expr $x+$dxw] $y1a -fill $col -tag $tag`\ `      $w create text [expr {$x+12}] [expr {$y-12}] -text $val`\ `      $w create text [expr {$x+12}] [expr {$y1a+2}] -text $txt -anchor n`\ `      incr x $dx`\ `   }`\ `   $w lower d`\ `}` Generally useful helper functions: `proc max list {`\ `   set res [lindex $list 0]`\ `   foreach e [lrange $list 1 end] {`\ `      if {$e>$res} {set res $e}`\ `   }`\ `   set res`\ `}`\ `proc min list {`\ `   set res [lindex $list 0]`\ `   foreach e [lrange $list 1 end] {`\ `      if {$e<$res} {set res $e}`\ `   }`\ `   set res`\ `}`\ `proc swap {_a _b} {`\ `   upvar 1 $_a a $_b b`\ `   foreach {a b} [list $b $a] break`\ `}` Testing the whole thing (see screenshot): `pack [canvas .c -width 240 -height 280]`\ `bars .c 10 20 240 230 {`\ `  {red 765 red}`\ `  {green 234 green}`\ `  {blue 345 blue}`\ `  {yel-\nlow 321 yellow}`\ `  {ma-\ngenta 567 magenta}`\ `  {cyan -123 cyan}`\ `  {white 400 white}`\ `}`\ `.c create text 120 10 -anchor nw -font {Helvetica 18} -text "Bar Chart\nDemo"` ### A little calculator ![](Tcl_calculator.jpg "Tcl_calculator.jpg") Here is a small calculator in Tcl/Tk. In addition to the buttons on screen, you can use any of expr\'s other functionalities via keyboard input. `package require Tk`\ `wm title . Calculator`\ `grid [entry .e -textvar e -just right] -columnspan 5`\ `bind .e ``<Return>`{=html}` =`\ `set n 0`\ `foreach row {`\ `   {7 8 9 + -}`\ `   {4 5 6 * /}`\ `   {1 2 3 ( )}`\ `   {C 0 . =  }`\ `} {`\ `   foreach key $row {`\ `       switch -- $key {`\ `           =       {set cmd =}`\ `           C       {set cmd {set clear 1; set e ""}}`\ `           default {set cmd "hit $key"}`\ `       }`\ `       lappend keys [button .[incr n] -text $key -command $cmd]`\ `   }`\ `   eval grid $keys -sticky we ;#-padx 1 -pady 1`\ `   set keys [list]`\ `}`\ `grid .$n -columnspan 2 ;# make last key (=) double wide`\ `proc = {} {`\ `   regsub { =.+} $::e "" ::e ;# maybe clear previous result`\ `   if [catch {set ::res [expr [string map {/ *1.0/} $::e]]}] {`\ `       .e config -fg red`\ `   }`\ `   append ::e = $::res `\ `   .e xview end`\ `   set ::clear 1`\ `}`\ `proc hit {key} {`\ `   if $::clear {`\ `       set ::e ""`\ `       if ![regexp {[0-9().]} $key] {set ::e $::res}`\ `       .e config -fg black`\ `       .e icursor end`\ `       set ::clear 0`\ `   }`\ `   .e insert end $key`\ `}`\ `set clear 0`\ `focus .e           ;# allow keyboard input`\ `wm resizable . 0 0` And, as Cameron Laird noted, this thingy is even programmable: enter for example `[proc fac x {expr {$x<2? 1: $x*[fac [incr x -1]]}}]` into the entry, disregard warnings; now you can do `[fac 10]` and receive \[fac 10\] = 3628800.0 as result\... ### A little slide rule The slide rule was an analog, mechanical device for approximate engineering computing, made obsolete by the pocket calculator since about the 1970-80s. The basic principle is that multiplication is done by adding logarithms, hence most of the scales are logarithmic, with uneven increments. ![](Sliderule_Tk.jpg "Sliderule_Tk.jpg") This fun project recreates a slide rule (roughly an Aristo-Rietz Nr. 89 with 7 scales - high-notch ones had up to 24) with a white \"body\" and a beige \"slide\" which you can move left or right with mouse button 1 clicked, or in pixel increment with the `<Shift-Left>`{=html}/`<Shift-Right>`{=html} cursor keys. Finally, the blue line represents the \"mark\" (how is that correctly called? \"runner\"? \"slider\"?) which you can move with the mouse over the whole thing to read a value. Fine movements with `<Left>`{=html}/`<Right>`{=html}. Due to rounding errors (integer pixels), this plaything is even less precise than a physical slide rule was, but maybe you still enjoy the memories\... The screenshot shows how I found out that 3 times 7 is approx. 21\... (check the A and B scales). `proc ui {} {`\ `   set width 620`\ `   pack [canvas .c -width $width -height 170 -bg white]`\ `   pack [label .l -textvariable info -fg blue] -fill x`\ `   .c create rect 0 50 $width 120 -fill grey90`\ `   .c create rect 0 50 $width 120 -fill beige -outline beige \`\ `       -tag {slide slidebase}`\ `   .c create line 0 0 0 120 -tag mark -fill blue`\ `   drawScale .c K  x3    10 5    5 log10 1 1000 186.6666667`\ `   drawScale .c A  x2    10 50  -5 log10 1 100 280`\ `   drawScale .c B  x2    10 50   5 log10 1 100 280 slide`\ `   drawScale .c CI 1/x   10 90 -5 -log10 1 10  560 slide`\ `   drawScale .c C  x     10 120 -5 log10 1 10  560 slide`\ `   drawScale .c D  x     10 120  5 log10 1 10  560`\ `   drawScale .c L "lg x" 10 160 -5 by100  0 10   5600`\ `   bind .c ``<Motion>`{=html}` {.c coords mark %x 0 %x 170; set info [values .c]}`\ `   bind .c <1> {set x %x}`\ `   bind .c ``<B1-Motion>`{=html}` {%W move slide [expr {%x-$x}] 0; set x %x}`\ `   bind . ``<Shift-Left>`{=html}`  {.c move slide -1 0; set info [values .c]}`\ `   bind . ``<Shift-Right>`{=html}` {.c move slide  1 0; set info [values .c]}`\ `   bind . ``<Left>`{=html}`  {.c move mark -1 0; set info [values .c]}`\ `   bind . ``<Right>`{=html}` {.c move mark  1 0; set info [values .c]}`\ `}` `proc drawScale {w name label x y dy f from to fac {tag {}}} {`\ `   set color [expr {[string match -* $f]? "red": "black"}]`\ `   $w create text $x [expr $y+2*$dy] -text $name -tag $tag -fill $color`\ `   $w create text 600 [expr $y+2*$dy] -text $label -tag $tag -fill $color`\ `   set x [expr {[string match -* $f]? 580: $x+10}]`\ `   set mod 5`\ `   set lastlabel ""`\ `   set lastx 0`\ `   for {set i [expr {$from*10}]} {$i<=$to*10} {incr i} {`\ `       if {$i>100} {`\ `           if {$i%10} continue ;# coarser increments`\ `           set mod 50`\ `       }`\ `       if {$i>1000} {`\ `           if {$i%100} continue ;# coarser increments`\ `           set mod 500`\ `       }`\ `       set x0 [expr $x+[$f [expr {$i/10.}]]*$fac]`\ `       set y1 [expr {$i%(2*$mod)==0? $y+2.*$dy: $i%$mod==0? $y+1.7*$dy: $y+$dy}]`\ `       set firstdigit [string index $i 0]`\ `       if {$y1==$y+$dy && abs($x0-$lastx)<2} continue`\ `       set lastx $x0`\ `       if {$i%($mod*2)==0 && $firstdigit != $lastlabel} {`\ `           $w create text $x0 [expr $y+3*$dy] -text $firstdigit \`\ `              -tag $tag -font {Helvetica 7} -fill $color`\ `           set lastlabel $firstdigit`\ `       }`\ `       $w create line $x0 $y $x0 $y1 -tag $tag -fill $color`\ `   }`\ `}` `proc values w {`\ `   set x0 [lindex [$w coords slidebase] 0]`\ `   set x1 [lindex [$w coords mark] 0]`\ `   set lgx [expr {($x1-20)/560.}]`\ `   set x [expr {pow(10,$lgx)}]`\ `   set lgxs [expr {($x1-$x0-20)/560.}]`\ `   set xs [expr {pow(10,$lgxs)}]`\ `   set res     K:[format %.2f [expr {pow($x,3)}]]`\ `   append res "  A:[format %.2f [expr {pow($x,2)}]]"`\ `   append res "  B:[format %.2f [expr {pow($xs,2)}]]"`\ `   append res "  CI:[format %.2f [expr {pow(10,-$lgxs)*10}]]"`\ `   append res "  C:[format %.2f $xs]"`\ `   append res "  D:[format %.2f $x]"`\ `   append res "  L:[format %.2f $lgx]"`\ `}` `proc pow10 x {expr {pow(10,$x)}}`\ `proc log10 x {expr {log10($x)}}`\ `proc -log10 x {expr {-log10($x)}}`\ `proc by100  x {expr {$x/100.}}` `#--------------------------------`\ `ui`\ `bind . ``<Escape>`{=html}` {exec wish $argv0 &; exit}` ### A minimal doodler Here is a tiny but complete script that allows doodling (drawing with the mouse) on a canvas widget: `proc doodle {w {color black}} {`\ `   bind $w <1>         [list doodle'start %W %x %y $color]`\ `   bind $w ``<B1-Motion>`{=html}` {doodle'move %W %x %y}`\ `}`\ `proc doodle'start {w x y color} {`\ `   set ::_id [$w create line $x $y $x $y -fill $color]`\ `}`\ `proc doodle'move {w x y} {`\ `   $w coords $::_id [concat [$w coords $::_id] $x $y]`\ `}`\ `pack [canvas .c -bg white] -fill both -expand 1`\ `doodle       .c`\ `bind .c ``<Double-3>`{=html}` {%W delete all}` ![](Doodler.jpg "Doodler.jpg") And here it comes again, but this time with explanations: The \"Application Program Interface\" (API) for this, if you want such ceremonial language, is the doodle command, where you specify which canvas widget should be enabled to doodle, and in which color (defaults to black):} `proc doodle {w {color black}} {`\ `   bind $w <1>         [list doodle'start %W %x %y $color]`\ `   bind $w ``<B1-Motion>`{=html}` {doodle'move %W %x %y}`\ `}` It registers two bindings for the canvas, one (\<1\>) when the left mouse-button is clicked, and the other when the mouse is moved with button 1 (left) down. Both bindings just call one internal function each. On left-click, a line item is created on the canvas in the specified fill color, but with no extent yet, as start and end points coincide. The item ID (a number assigned by the canvas) is kept in a global variable, as it will have to persist long after this procedure has returned: `proc doodle'start {w x y color} {`\ `   set ::_id [$w create line $x $y $x $y -fill $color]`\ `}` The left-motion procedure obtains the coordinates (alternating x and y) of the globally known doodling line object, appends the current coordinates to it, and makes this the new coordinates - in other words, extends the line to the current mouse position: `proc doodle'move {w x y} {`\ `   $w coords $::_id [concat [$w coords $::_id] $x $y]`\ `}` That\'s all we need to implement doodling - now let\'s create a canvas to test it, and pack it so it can be drawn as big as you wish: `pack [canvas .c -bg white] -fill both -expand 1` And this line turns on the doodle functionality created above (defaulting to black): `doodle       .c` Add a binding for double-right-click/double-button-3, to clear the canvas (added by MG, Apr 29 04) `bind .c ``<Double-3>`{=html}` {%W delete all}` ### A tiny drawing program Here is a tiny drawing program on a canvas. Radio buttons on top allow choice of draw mode and fill color. In \"Move\" mode, you can of course move items around. Right-click on an item to delete it. ![](Tinydraw.jpg "Tinydraw.jpg") A radio is an obvious \"megawidget\" to hold a row of radiobuttons. This simple one allows text or color mode: } `proc radio {w var values {col 0}} {`\ `   frame $w`\ `   set type [expr {$col? "-background" : "-text"}]`\ `   foreach value $values {`\ `       radiobutton $w.v$value $type $value -variable $var -value $value \`\ `           -indicatoron 0`\ `       if $col {$w.v$value config -selectcolor $value -borderwidth 3}`\ `   }`\ `   eval pack [winfo children $w] -side left`\ `   set ::$var [lindex $values 0]`\ `   set w`\ `}` Depending on draw mode, the mouse events \"Down\" and \"Motion\" have different handlers, which are dispatched by names that look like array elements. So for a mode X, we need a pair of procs, down(X) and move(X). Values used between calls are kept in global variables. First, the handlers for free-hand line drawing: `proc down(Draw) {w x y} {`\ `   set ::ID [$w create line $x $y $x $y -fill $::Fill]`\ `}`\ `proc move(Draw) {w x y} {`\ `   $w coords $::ID [concat [$w coords $::ID] $x $y]`\ `}` `#-- Movement of an item`\ `proc down(Move) {w x y} {`\ `   set ::ID [$w find withtag current]`\ `   set ::X $x; set ::Y $y`\ `}`\ `proc move(Move) {w x y} {`\ `   $w move $::ID [expr {$x-$::X}] [expr {$y-$::Y}]`\ `   set ::X $x; set ::Y $y`\ `}` `#-- Clone an existing item`\ `proc serializeCanvasItem {c item} {`\ `   set data [concat [$c type $item] [$c coords $item]]`\ `   foreach opt [$c itemconfigure $item] {`\ `       # Include any configuration that deviates from the default`\ `       if {[lindex $opt end] != [lindex $opt end-1]} {`\ `           lappend data [lindex $opt 0] [lindex $opt end]`\ `           }`\ `       }`\ `   return $data`\ `   }`\ `proc down(Clone) {w x y} {`\ `   set current [$w find withtag current]`\ `   if {[string length $current] > 0} {`\ `       set itemData [serializeCanvasItem $w [$w find withtag current]]`\ `       set ::ID [eval $w create $itemData]`\ `       set ::X $x; set ::Y $y`\ `   }`\ `}`\ `interp alias {} move(Clone) {} move(Move)` `#-- Drawing a rectangle`\ `proc down(Rect) {w x y} {`\ `   set ::ID [$w create rect $x $y $x $y -fill $::Fill]`\ `}`\ `proc move(Rect) {w x y} {`\ `   $w coords $::ID [lreplace [$w coords $::ID] 2 3 $x $y]`\ `}` `#-- Drawing an oval (or circle, if you're careful)`\ `proc down(Oval) {w x y} {`\ `   set ::ID [$w create oval $x $y $x $y -fill $::Fill]`\ `}`\ `proc move(Oval) {w x y} {`\ `   $w coords $::ID [lreplace [$w coords $::ID] 2 3 $x $y]`\ `}` Polygons are drawn by clicking the corners. When a corner is close enough to the first one, the polygon is closed and drawn. `proc down(Poly) {w x y} {`\ `   if [info exists ::Poly] {`\ `       set coords [$w coords $::Poly]`\ `       foreach {x0 y0} $coords break`\ `       if {hypot($y-$y0,$x-$x0)<10} {`\ `           $w delete $::Poly`\ `           $w create poly [lrange $coords 2 end] -fill $::Fill`\ `           unset ::Poly`\ `       } else {`\ `           $w coords $::Poly [concat $coords $x $y]`\ `       }`\ `   } else {`\ `       set ::Poly [$w create line $x $y $x $y -fill $::Fill]`\ `   }`\ `}`\ `proc move(Poly) {w x y} {#nothing}` `#-- With little more coding, the Fill mode allows changing an item's fill color:`\ `proc down(Fill) {w x y} {$w itemconfig current -fill $::Fill}`\ `proc move(Fill) {w x y} {}` `#-- Building the UI`\ `set modes {Draw Move Clone Fill Rect Oval Poly}`\ `set colors {`\ `   black white magenta brown red orange yellow green green3 green4`\ `   cyan blue blue4 purple`\ `}`\ `grid [radio .1 Mode $modes] [radio .2 Fill $colors 1] -sticky nw`\ `grid [canvas .c -relief raised -borderwidth 1] - -sticky news`\ `grid rowconfig . 0 -weight 0`\ `grid rowconfig . 1 -weight 1` `#-- The current mode is retrieved at runtime from the global Mode variable:`\ `bind .c <1>         {down($Mode) %W %x %y}`\ `bind .c ``<B1-Motion>`{=html}` {move($Mode) %W %x %y}`\ `bind .c <3>         {%W delete current}` For saving the current image, you need the Img extension, so just omit the following binding if you don\'t have Img: `bind . ``<F1>`{=html}` {`\ `   package require Img`\ `   set img [image create photo -data .c]`\ `   set name [tk_getSaveFile -filetypes ``{{GIFF .gif} {"All files" *}}`{=mediawiki}`\`\ `       -defaultextension .gif]`\ `   if {$name ne ""} {$img write $name; wm title . $name}`\ `}` `#-- This is an always useful helper in development:`\ `bind . ``<Escape>`{=html}` {exec wish $argv0 &; exit}` ### A minimal editor Here\'s an utterly simple editor, in 26 lines of code, which just allows to load and save files, and of course edit, and cut and paste, and whatever is built-in into the text widget anyway. And it has a bit \"online help\"\... ;-) It is always a good idea to start a source file with some explanations on the name, purpose, author, and date. I have recently picked up the habit to put this information into a string variable (which in Tcl can easily span multiple lines), so the same info is presented to the reader of the source code, and can be displayed as online help: } `set about "minEd - a minimal editor`\ `Richard Suchenwirth 2003`\ `F1: help`\ `F2: load`\ `F3: save`\ `"` The visible part of a Graphical User Interface (GUI) consists of widgets. For this editor, I of course need a text widget, and a vertical scrollbar. With the option \"-wrap word\" for the text widget, another horizontal scrollbar is not needed - lines longer than the window just wrap at word boundaries. Tk widgets come on the screen in two steps: first, they are created with an initial configuration; then, handed to a \"geometry manager\" for display. As widget creation commands return the pathname, they can be nested into the manager command (pack in this case), to keep all settings for a widget in one place. This may lead to over-long lines, though. Although the scrollbar comes to the right of the text, I create and pack it first. The reason is that when a window is made smaller by the user, the widgets last packed first lose visibility. These two lines also illustrate the coupling between a scrollbar and the widget it controls: - the scrollbar sends a yview message to it when moved - the widget sends a set message to the scrollbar when the view changed, for instance from cursor keys And these two lines already give us an editor for arbitrarily long text, with built-in capabilities of cut, copy, and paste - see the text man page. Only file I/O has to be added by us to make it really usable. `pack [scrollbar .y -command ".t yview"] -side right -fill y`\ `pack [text .t -wrap word -yscrollc ".y set"] -side right -fill both -expand 1` Are you targetting 8.4 or later? If so, add -undo 1 to the options to text and get full undo/redo support! `pack [text .t -wrap word -yscrollc ".y set" -undo 1] -side right -fill both -expand 1` The other important part of a GUI are the bindings - what event shall trigger what action. For simplicity, I\'ve limited the bindings here to a few of the function keys on top of typical keyboards: `bind . ``<F1>`{=html}` {tk_messageBox -message $about}` Online help is done with a no-frills tk_messageBox with the \"about\" text defined at start of file. - The other bindings call custom commands, which get a filename argument from Tk\'s file selector dialogs: `bind . ``<F2>`{=html}` {loadText .t [tk_getOpenFile]}`\ `bind . ``<F3>`{=html}` {saveText .t [tk_getSaveFile]}` These dialogs can also be configured in a number of ways, but even in this simple form they are quite powerful - allow navigation around the file system, etc. On Windows they call the native file selectors, which have a history of previously opened files, detail view (size/date etc.) When this editor is called with a filename on the command line, that file is loaded on startup (simple as it is, it can only handle one file at a time): `if {$argv != ""} {loadText .t [lindex $argv 0]}` The procedures for loading and saving text both start with a sanity check of the filename argument - if it\'s an empty string, as produced by file selector dialogs when the user cancels, they return immediately. Otherwise, they transfer file content to text widget or vice-versa. loadText adds the \"luxury\" that the name of the current file is also put into the window title. Then it opens the file, clears the text widget, reads all file contents in one go, and puts them into the text widget. `proc loadText {w fn} {`\ `   if {$fn==""} return`\ `   wm title . [file tail $fn]`\ `   set fp [open $fn]`\ `   $w delete 1.0 end`\ `   $w insert end [read $fp]`\ `   close $fp`\ `}` saveText takes care not to save the extra newline that text widgets append at end, by limiting the range to \"end - 1 c\"(haracter). `proc saveText {w fn} {`\ `   if {$fn==""} return`\ `   set fp [open $fn w]`\ `   puts -nonewline $fp [$w get 1.0 "end - 1 c"]`\ `   close $fp`\ `}` ### File watch Some editors (e.g. PFE, MS Visual Studio) pop up an alert dialog when a file was changed on disk while being edited - that might lead to edit conflicts. Emacs shows a more subtle warning at the first attempt to change a file that has changed on disk. Here I try to emulate this feature. It is oversimplified because it does not update the mtime (file modification time) to check, once you saved it from the editor itself. So make sure to call text\'watch\'file again after saving. Using the global variable ::\_twf it is at least possible to avoid false alarms - for a more serious implementation one might use a namespaced array of watchers, indexed by file name, in case you want multiple edit windows. } `proc text'watch'file {w file {mtime -}} {`\ `   set checkinterval 1000 ;# modify as needed`\ `   if {$mtime eq "-"} {`\ `       if [info exists ::_twf] {after cancel $::_twf}`\ `       set file [file join [pwd] $file]`\ `       text'watch'file $w $file [file mtime $file]`\ `   } else {`\ `       set newtime [file mtime $file]`\ `       if {$newtime != $mtime} {`\ `           set answer [tk_messageBox -type yesno -message \`\ `               "The file\n$file\nhas changed on disk. Reload it?"]`\ `           if {$answer eq "yes"} {text'read'file $w $file}`\ `           text'watch'file $w $file`\ `       } else {set ::_twf [after $checkinterval [info level 0]]}`\ `   }`\ `}`\ `proc text'read'file {w file} {`\ `   set f [open $file]`\ `   $w delete 1.0 end`\ `   $w insert end [read $f]`\ `   close $f`\ `}` `#-- Testing:`\ `pack [text .t -wrap word] -fill both -expand 1`\ `set file textwatch.tcl`\ `text'read'file  .t $file`\ `text'watch'file .t $file` The dialog should come up when you change the file externally, say by touch-ing it in pure Tcl, which might be done with editing it in another editor, or `file mtime $filename [clock seconds]` ### Tiny presentation graphics This is a crude little canvas presentation graphics that runs on PocketPCs, but also on bigger boxes (one might scale fonts and dimensions there). Switch pages with Left/Right cursor, or left/right mouseclick (though a stylus cannot right-click). Not many features, but the code is very compact, and with a cute little language for content specification, see example at end (which shows what I presented at the 2003 Euro-Tcl convention in Nuremberg\...)} `proc slide args {`\ `  global slides`\ `  if {![info exist slides]} slide'init`\ `  incr slides(N)`\ `  set slides(title,$slides(N)) [join $args]`\ `}`\ `proc slide'line {type args} {`\ `  global slides`\ `  lappend slides(body,$slides(N)) [list $type [join $args]]`\ `}`\ `foreach name {* + -} {interp alias {} $name {} slide'line $name}` `proc slide'init {} {`\ `  global slides`\ `  array set slides {`\ `     canvas .c  N 0  show 1 dy 20`\ `     titlefont {Tahoma 22 bold} * {Tahoma 14 bold} + {Tahoma 12}`\ `     - {Courier 10}`\ `  }`\ `  pack [canvas .c -bg white] -expand 1 -fill both`\ `  foreach e {<1> ``<Right>`{=html}`} {bind . $e {slide'show 1}}`\ `  foreach e {<3> ``<Left>`{=html}`} {bind . $e {slide'show -1}}`\ `  wm geometry . +0+0`\ `  after idle {slide'show 0}`\ `}` `proc slide'show delta {`\ `  upvar #0 slides s`\ `  incr s(show) $delta`\ `  if {$s(show)<1 || $s(show)>$s(N)} {`\ `     incr s(show) [expr -$delta]`\ `  } else {`\ `     set c $s(canvas)`\ `     $c delete all`\ `     set x 10; set y 20`\ `     $c create text $x $y -anchor w -text $s(title,$s(show))\`\ `        -font $s(titlefont) -fill blue`\ `     incr y $s(dy)`\ `     $c create line $x $y 2048 $y -fill red -width 4`\ `     foreach line $s(body,$s(show)) {`\ `        foreach {type text} $line break`\ `        incr y $s(dy)`\ `        $c create text $x $y -anchor w -text $text \`\ `        -font $s($type)`\ `     }`\ `  }`\ `}`\ `bind . ``<Up>`{=html}` {exec wish $argv0 &; exit} ;# dev helper` The rest is data - or is it code? Anyway, here\'s my show: `slide i18n - Tcl for the world`\ `+ Richard Suchenwirth, Nuremberg 2003`\ `+`\ `* i18n: internationalization`\ `+ 'make software work with many languages'`\ `+`\ `* l10n: localization`\ `+ 'make software work with the local language'` `slide Terminology`\ `* Glyphs:`\ `+ visible elements of writing`\ `* Characters:`\ `+ abstract elements of writing`\ `* Byte sequences:`\ `+ physical text data representation`\ `* Rendering: character -> glyph`\ `* Encoding: character <-> byte sequence` `slide Before Unicode`\ `* Bacon (1580), Baudot: 5-bit encodings`\ `* Fieldata (6 bits), EBCDIC (8 bits)`\ `* ASCII (7 bits)`\ `+ world-wide "kernel" of encodings`\ `* 8-bit codepages: DOS, Mac, Windows`\ `* ISO 8859-x: 16 varieties` `slide East Asia`\ `* Thousands of characters/country`\ `+ Solution: use 2 bytes, 94x94 matrix`\ `+ Japan: JIS C-6226/0208/0212`\ `+ China: GB2312-80`\ `+ Korea: KS-C 5601`\ `+`\ `* coexist with ASCII in EUC encodings` `slide Unicode covers all`\ `* Common standard of software industry`\ `* kept in synch with ISO 10646`\ `+ Used to be 16 bits, until U 3.1`\ `+ Now needs up to 31 bits`\ `* Byte order problem:`\ `+ little-endian/big-endian`\ `+ U+FEFF "Byte Order Mark"`\ `+ U+FFFE --illegal--` `slide UTF-8`\ `* Varying length: 1..3(..6) bytes`\ `+ 1 byte: ASCII`\ `+ 2 bytes: pages 00..07, Alphabets`\ `+ 3 bytes: pages 08..FF, rest of BMP`\ `+ >3 bytes: higher pages`\ `+`\ `* Standard in XML, coming in Unix` `slide Tcl i18n`\ `* Everything is a Unicode string (BMP)`\ `+ internal rep: UTF-8/UCS-2`\ `* Important commands:`\ `- fconfigure \$ch -encoding \$e`\ `- encoding convertfrom \$e \$s`\ `- encoding convertto   \$e \$s`\ `+`\ `* msgcat supports l10n:`\ `- {"File" -> [mc "File"]}` `slide Tk i18n`\ `* Any widget text is Unicoded`\ `* Automatic font finding`\ `+ Fonts must be provided by system`\ `+`\ `* Missing: bidi treatment`\ `+ right-to-left conversion (ar,he)` `slide Input i18n`\ `* Keyboard rebinding (bindtags)`\ `* East Asia: keyboard buffering`\ `+ Menu selection for ambiguities`\ `+`\ `* Virtual keyboard (buttons, canvas)`\ `* String conversion: *lish family`\ `- {[ruslish Moskva]-[greeklish Aqh'nai]}` `slide i18n - Tcl for the world`\ `+`\ `+`\ `+ Thank you.` ### Timeline display Yet another thing to do with a canvas: history visualisation of a horizontal time-line, for which a year scale is displayed on top. The following kinds of objects are so far available: - \"eras\", displayed in yellow below the timeline in boxes - \"background items\" that are grey and stretch over all the canvas in height - normal items, which get displayed as stacked orange bars ![](Timeliner.jpg "Timeliner.jpg") You can zoom in with \<1\>, out with \<3\> (both only in x direction). On mouse motion, the current year is displayed in the toplevel\'s title. Normal items can be a single year, like the Columbus example, or a range of years, for instance for lifetimes of persons. (The example shows that Mozart didn\'t live long\...) `namespace eval timeliner {`\ `   variable ""`\ `   array set "" {-zoom 1  -from 0 -to 2000}`\ `}` `proc timeliner::create {w args} {`\ `   variable ""`\ `   array set "" $args`\ `   #-- draw time scale`\ `   for {set x [expr ($(-from)/50)*50]} {$x<=$(-to)} {incr x 10} {`\ `       if {$x%50 == 0} {`\ `           $w create line $x 8 $x 0`\ `           $w create text $x 8 -text $x -anchor n`\ `       } else {`\ `           $w create line $x 5 $x 0`\ `       }`\ `   }`\ `   bind $w ``<Motion>`{=html}` {timeliner::title %W %x ; timeliner::movehair %W %x}`\ `   bind $w <1> {timeliner::zoom %W %x 1.25}`\ `   bind $w <2> {timeliner::hair %W %x}`\ `   bind $w <3> {timeliner::zoom %W %x 0.8}`\ `}` `proc timeliner::movehair {w x} {`\ `   variable ""`\ `   if {[llength [$w find withtag hair]]} {`\ `       set x [$w canvasx $x]`\ `       $w move hair [expr {$x - $(x)}] 0`\ `       set (x) $x`\ `   }`\ `}`\ `proc timeliner::hair {w x} {`\ `   variable ""`\ `   if {[llength [$w find withtag hair]]} {`\ `       $w delete hair`\ `   } else {`\ `       set (x) [$w canvasx $x]`\ `       $w create line $(x) 0 $(x) [$w cget -height] \`\ `                 -tags hair -width 1 -fill red`\ `   }`\ `}` `proc timeliner::title {w x} {`\ `   variable ""`\ `   wm title . [expr int([$w canvasx $x]/$(-zoom))]`\ `}` `proc timeliner::zoom {w x factor} {`\ `   variable ""`\ `   $w scale all 0 0 $factor 1`\ `   set (-zoom) [expr {$(-zoom)*$factor}]`\ `   $w config -scrollregion [$w bbox all]`\ `   if {[llength [$w find withtag hair]]} {`\ `       $w delete hair`\ `       set (x) [$w canvasx $x]`\ `       $w create line $(x) 0 $(x) [$w cget -height] \`\ `                 -tags hair -width 1 -fill red`\ `   }`\ `}` This command adds an object to the canvas. The code for \"item\" took me some effort, as it had to locate a free \"slot\" on the canvas, searching top-down: `proc timeliner::add {w type name time args} {`\ `   variable ""`\ `   regexp {(\d+)(-(\d+))?} $time -> from - to`\ `   if {$to eq ""} {set to $from}`\ `   set x0 [expr {$from*$(-zoom)}]`\ `   set x1 [expr {$to*$(-zoom)}]`\ `   switch -- $type {`\ `       era    {set fill yellow; set outline black; set y0 20; set y1 40}`\ `       bgitem {set fill gray; set outline {}; set y0 40; set y1 1024}`\ `       item   {`\ `           set fill orange`\ `           set outline yellow`\ `           for {set y0 60} {$y0<400} {incr y0 20} {`\ `               set y1 [expr {$y0+18}]`\ `               if {[$w find overlap [expr $x0-5] $y0 $x1 $y1] eq ""} break`\ `           }`\ `       }`\ `   }`\ `   set id [$w create rect $x0 $y0 $x1 $y1 -fill $fill -outline $outline]`\ `   if {$type eq "bgitem"} {$w lower $id}`\ `   set x2 [expr {$x0+5}]`\ `   set y2 [expr {$y0+2}]`\ `   set tid [$w create text $x2 $y2 -text $name -anchor nw]`\ `   foreach arg $args {`\ `       if {$arg eq "!"} {`\ `           $w itemconfig $tid -font "[$w itemcget $tid -font] bold"`\ `       }`\ `   }`\ `   $w config -scrollregion [$w bbox all]`\ `}` Here\'s a sample application, featuring a concise history of music in terms of composers: `scrollbar .x -ori hori -command {.c xview}`\ `pack      .x -side bottom -fill x`\ `canvas    .c -bg white -width 600 -height 300 -xscrollcommand {.x set}`\ `pack      .c -fill both -expand 1`\ `timeliner::create .c -from 1400 -to 2000` These nifty shorthands for adding items make data specification a breeze - compare the original call, and the shorthand: `   timeliner::add .c item Purcell 1659-1695`\ `   - Purcell 1659-1695` With an additional \"!\" argument you can make the text of an item bold: `foreach {shorthand type} {* era  x bgitem - item} {`\ `   interp alias {} $shorthand {} timeliner::add .c $type`\ `}` Now for the data to display (written pretty readably): `* {Middle Ages} 1400-1450`\ `- Dufay 1400-1474`\ `* Renaissance    1450-1600`\ `- Desprez 1440-1521`\ `- Luther 1483-1546`\ `- {Columbus discovers America} 1492`\ `- Palestrina 1525-1594 !`\ `- Lasso 1532-1594`\ `- Byrd 1543-1623`\ `* Baroque        1600-1750`\ `- Dowland 1563-1626`\ `- Monteverdi 1567-1643`\ `- Schütz 1585-1672`\ `- Purcell 1659-1695`\ `- Telemann 1681-1767`\ `- Rameau 1683-1764`\ `- Bach,J.S. 1685-1750 !`\ `- Händel 1685-1759`\ `x {30-years war} 1618-1648`\ `* {Classic era}  1750-1810`\ `- Haydn 1732-1809 !`\ `- Boccherini 1743-1805`\ `- Mozart 1756-1791 !`\ `- Beethoven 1770-1828 !`\ `* {Romantic era} 1810-1914`\ `- {Mendelssohn Bartholdy} 1809-1847`\ `- Chopin 1810-1849`\ `- Liszt 1811-1886`\ `- Verdi 1813-1901`\ `x {French revolution} 1789-1800`\ `* {Modern era}   1914-2000`\ `- Ravel 1875-1937 !`\ `- Bartók 1881-1945`\ `- Stravinskij 1882-1971`\ `- Varèse 1883-1965`\ `- Prokof'ev 1891-1953`\ `- Milhaud 1892-1974`\ `- Honegger 1892-1955`\ `- Hindemith 1895-1963`\ `- Britten 1913-1976`\ `x WW1 1914-1918`\ `x WW2 1938-1945` ### Fun with functions ![](funplot.jpg "funplot.jpg") My teenage daughter hates math. In order to motivate her, I beefed up an earlier little function plotter which before only took one function, in strict Tcl (expr) notation, from the command line. Now there\'s an entry widget, and the accepted language has also been enriched: beyond exprs rules, you can omit dollar and multiplication signs, like 2x+1, powers can be written as x3 instead of (\$x\*\$x\*\$x); in simple cases you can omit parens round function arguments, like sin x2. Hitting `<Return>`{=html} in the entry widget displays the function\'s graph. If you need some ideas, click on the \"?\" button to cycle through a set of demo functions, from boring to bizarre (e.g. if rand() is used). Besides default scaling, you can zoom in or out. Moving the mouse pointer over the canvas displays x and y coordinates, and the display changes to white if you\'re on a point on the curve. The target was not reached: my daughter still hates math. But at least I had hours of Tcl (and function) fun again, surfing in the Cartesian plane\... hope you enjoy it too! `proc main {} {`\ `   canvas .c -bg white -borderwidth 0`\ `   bind   .c ``<Motion>`{=html}` {displayXY .info %x %y}`\ `   frame  .f`\ `     label  .f.1 -text "f(x) = "`\ `     entry  .f.f -textvar ::function -width 40`\ `       bind .f.f ``<Return>`{=html}` {plotf .c $::function}`\ `     button .f.demo -text " ? " -pady 0 -command {demo .c}`\ `     label  .f.2 -text " Zoom: "`\ `     entry  .f.fac -textvar ::factor -width 4`\ `       set                  ::factor 32`\ `       bind .f.fac ``<Return>`{=html}`               {zoom .c 1.0}`\ `     button .f.plus  -text " + " -pady 0 -command {zoom .c 2.0}`\ `     button .f.minus -text " - " -pady 0 -command {zoom .c 0.5}`\ `     eval pack [winfo children .f] -side left -fill both`\ `   label  .info -textvar ::info -just left`\ `   pack .info .f -fill x -side bottom`\ `   pack .c -fill both -expand 1`\ `   demo .c`\ `}` `set ::demos {`\ `       "cos x3" 2 1-x 0.5x2 x3/5 "sin x" "sin x2" 1/x sqrt(x)`\ `       "tan x/5" x+1/x x abs(x) "exp x" "log x" "log x2"`\ `       round(x) "int x%2" "x-int x" "0.2tan x+1/tan x" x*(rand()-0.5)`\ `       x2/5-1/(2x) "atan x" sqrt(1-x2) "abs(x-int(x*2))" (x-1)/(x+1)`\ `       "sin x-tan x" "sin x-tan x2" "x-abs(int x)" 0.5x-1/x`\ `       -0.5x3+x2+x-1 3*sin(2x) -0.05x4-0.2x3+1.5x2+2x-3 "9%int x"`\ `       0.5x2/(x3-3x2+4) "abs x2-3 int x" "int x%3"`\ `}` `proc displayXY {w cx cy} {`\ `       set x [expr {double($cx-$::dx)/$::factor}]`\ `       set y [expr {double(-$cy+$::dy)/$::factor}]`\ `       set ::info [format "x=%.2f y=%.2f" $x $y]`\ `       catch {`\ `       $w config -fg [expr {abs([expr $::fun]-$y)<0.01?"white":"black"}]`\ `       } ;# may divide by zero, or other illegal things`\ `}` `proc zoom {w howmuch} {`\ `   set ::factor [expr round($::factor*$howmuch)]`\ `   plotf $w $::function`\ `}` `proc plotf {w function} {`\ `   foreach {re subst} {`\ `       {([a-z]) +(x[0-9]?)} {\1(\2)}   " " ""   {([0-9])([a-z])} {\1*\2}`\ `       x2 x*x   x3 x*x*x    x4 x*x*x*x   x \$x   {e\$xp} exp`\ `   } {regsub -all $re $function $subst function}`\ `   set ::fun $function`\ `   set ::info "Tcl: expr $::fun"`\ `   set color [lpick {red blue purple brown green}]`\ `   plotline $w [fun2points $::fun] -fill $color`\ `}` `proc lpick L {lindex $L [expr {int(rand()*[llength $L])}]}` `proc fun2points {fun args} {`\ `   array set opt {-from -10.0 -to 10.0 -step .01}`\ `   array set opt $args`\ `   set res "{"`\ `   for {set x $opt(-from)} {$x<= $opt(-to)} {set x [expr {$x+$opt(-step)}]} {`\ `       if {![catch {expr $fun} y]} {`\ `           if {[info exists lasty] && abs($y-$lasty)>100} {`\ `               append res "\} \{" ;# incontinuity`\ `           }`\ `           append res " $x $y"`\ `           set lasty $y`\ `       } else {append res "\} \{"}`\ `   }`\ `   append res "}"`\ `}` `proc plotline {w points args} {`\ `   $w delete all`\ `   foreach i $points {`\ `       if {[llength $i]>2} {eval $w create line $i $args -tags f}`\ `   }`\ `   set fac $::factor`\ `   $w scale all 0 0 $fac -$fac`\ `   $w create line -10000 0 10000 0      ;# X axis`\ `   $w create line 0 -10000 0 10000      ;# Y axis`\ `   $w create line $fac 0     $fac -3    ;# x=1 tick`\ `   $w create line -3   -$fac 0    -$fac ;# y=1 tick`\ `   set ::dx [expr {[$w cget -width]/2}]`\ `   set ::dy [expr {[$w cget -height]/2}]`\ `   $w move all $::dx $::dy`\ `   $w raise f`\ `}` `proc demo {w} {`\ `   set ::function [lindex $::demos 0] ;# cycle through...`\ `   set ::demos [concat [lrange $::demos 1 end] [list $::function]]`\ `   set ::factor 32`\ `   plotf $w $::function`\ `}` `main` ### Functional imaging In Conal Elliott\'s Pan project (\"Functional Image Synthesis\", \[1\]), images (of arbitrary size and resolution) are produced and manipulated in an elegant functional way. Functions written in Haskell (see Playing Haskell) are applied, mostly in functional composition, to pixels to return their color value. FAQ: \"Can we have that in Tcl too?\" ![](funimj.jpg "funimj.jpg") As the funimj demo below shows, in principle yes; but it takes some patience (or a very fast CPU) - for a 200x200 image the function is called 40000 times, which takes 9..48 seconds on my P200 box. Still, the output often is worth waiting for\... and the time used to write this code was negligible, as the Haskell original could with few modifications be represented in Tcl. Functional composition had to be rewritten to Tcl\'s Polish notation - Haskell\'s `foo 1 o bar 2 o grill` (where \"o\" is the composition operator) would in Tcl look like `o {foo 1} {bar 2} grill` As the example shows, additional arguments can be specified; only the last argument is passed through the generated \"function nest\": `proc f {x} {foo 1 [bar 2 [grill $x]]}` But the name of the generated function is much nicer than \"f\": namely, the complete call to \"o\" is used, so the example proc has the name `"o {foo 1} {bar 2} grill"` which is pretty self-documenting ;-) I implemented \"o\" like this: `proc o args {`\ `   # combine the functions in args, return the created name`\ `   set name [info level 0]`\ `   set body "[join $args " `$$"] \$x" append body [string repeat$$` [expr {[llength $args]-1}]]`\ `   proc $name x $body`\ `   set name`\ `}`\ `# Now for the rendering framework:` `proc fim {f {zoom 100} {width 200} {height -}} {`\ `   # produce a photo image by applying function f to pixels`\ `   if {$height=="-"} {set height $width}`\ `   set im [image create photo -height $height -width $width]`\ `   set data {}`\ `   set xs {}`\ `   for {set j 0} {$j<$width} {incr j} {`\ `       lappend xs [expr {($j-$width/2.)/$zoom}]`\ `   }`\ `   for {set i 0} {$i<$height} {incr i} {`\ `       set row {}`\ `       set y [expr {($i-$height/2.)/$zoom}]`\ `       foreach x $xs {`\ `           lappend row [$f [list $x $y]]`\ `       }`\ `       lappend data $row`\ `   }`\ `   $im put $data`\ `   set im`\ `}` Basic imaging functions (\"drawers\") have the common functionality point -\> color, where point is a pair {x y} (or, after applying a polar transform, {r a}\...) and color is a Tk color name, like \"green\" or #010203: `proc  vstrip p {`\ `   # a simple vertical bar`\ `   b2c [expr {abs([lindex $p 0]) < 0.5}]`\ `}`\ `proc udisk p {`\ `   # unit circle with radius 1`\ `   foreach {x y} $p break`\ `   b2c [expr {hypot($x,$y) < 1}]`\ `}`\ `proc xor {f1 f2 p} {`\ `   lappend f1 $p; lappend f2 $p`\ `   b2c [expr {[eval $f1] != [eval $f2]}]`\ `}`\ `proc and {f1 f2 p} {`\ `   lappend f1 $p; lappend f2 $p`\ `   b2c [expr {[eval $f1] == "#000" && [eval $f2] == "#000"}]`\ `}`\ `proc checker p {`\ `   # black and white checkerboard`\ `   foreach {x y} $p break`\ `   b2c [expr {int(floor($x)+floor($y)) % 2 == 0}]`\ `}`\ `proc gChecker p {`\ `   # greylevels correspond to fractional part of x,y`\ `   foreach {x y} $p break`\ `   g2c [expr {(fmod(abs($x),1.)*fmod(abs($y),1.))}]`\ `}`\ `proc bRings p {`\ `   # binary concentric rings`\ `   foreach {x y} $p break`\ `   b2c [expr {round(hypot($x,$y)) % 2 == 0}]`\ `}`\ `proc gRings p {`\ `   # grayscale concentric rings`\ `   foreach {x y} $p break`\ `   g2c [expr {(1 + cos(3.14159265359 * hypot($x,$y))) / 2.}]`\ `}`\ `proc radReg {n p} {`\ `   # n wedge slices starting at (0,0)`\ `   foreach {r a} [toPolars $p] break`\ `   b2c [expr {int(floor($a*$n/3.14159265359))%2 == 0}]`\ `}`\ `proc xPos p {b2c [expr {[lindex $p 0]>0}]}` `proc cGrad p {`\ `   # color gradients - best watched at zoom=100`\ `   foreach {x y} $p break`\ `   if {abs($x)>1.} {set x 1.}`\ `   if {abs($y)>1.} {set y 1.}`\ `   set r [expr {int((1.-abs($x))*255.)}]`\ `   set g [expr {int((sqrt(2.)-hypot($x,$y))*180.)}]`\ `   set b [expr {int((1.-abs($y))*255.)}]`\ `   c2c $r $g $b`\ `}` Beyond the examples in Conal Elliott\'s paper, I found out that function imaging can also be abused for a (slow and imprecise) function plotter, which displays the graph for y = f(x) if you call it with \$y + f(\$x) as first argument: `proc fplot {expr p} {`\ `   foreach {x y} $p break`\ `   b2c [expr abs($expr)<=0.04] ;# double eval required here!`\ `}` Here is a combinator for two binary images that shows in different colors for which point both or either are \"true\" - nice but slow:} `proc bin2 {f1 f2 p} {`\ `   set a [eval $f1 [list $p]]`\ `   set b [eval $f2 [list $p]]`\ `   expr {`\ `       $a == "#000" ?`\ `           $b == "#000" ? "green"`\ `           : "yellow"`\ `       : $b == "#000" ? "blue"`\ `       : "black"`\ `   }`\ `}`\ `#--------------------------------------- Pixel converters:` `proc g2c {greylevel} {`\ `   # convert 0..1 to #000000..#FFFFFF`\ `   set hex [format %02X [expr {round($greylevel*255)}]]`\ `   return #$hex$hex$hex`\ `}`\ `proc b2c {binpixel} {`\ `   # 0 -> white, 1 -> black`\ `   expr {$binpixel? "#000" : "#FFF"}`\ `}`\ `proc c2c {r g b} {`\ `   # make Tk color name: {0 128 255} -> #0080FF`\ `   format #%02X%02X%02X $r $g $b`\ `}`\ `proc bPaint {color0 color1 pixel} {`\ `   # convert a binary pixel to one of two specified colors`\ `   expr {$pixel=="#000"? $color0 : $color1}`\ `}` This painter colors a grayscale image in hues of the given color. It normalizes the given color through dividing by the corresponding values for \"white\", but appears pretty slow too: `proc gPaint {color pixel} {`\ `   set abspixel [lindex [rgb $pixel] 0]`\ `   set rgb [rgb $color]`\ `   set rgbw [rgb white]`\ `   foreach var {r g b} in $rgb ref $rgbw {`\ `       set $var [expr {round(double($abspixel)*$in/$ref/$ref*255.)}]`\ `   }`\ `   c2c $r $g $b`\ `}` This proc caches the results of \[winfo rgb\] calls, because these are quite expensive, especially on remote X displays - rmax `proc rgb {color} {`\ `   upvar "#0" rgb($color) rgb`\ `   if {![info exists rgb]} {set rgb [winfo rgb . $color]}`\ `   set rgb`\ `}`\ `#------------------------------ point -> point transformers` `proc fromPolars p {`\ `   foreach {r a} $p break`\ `   list [expr {$r*cos($a)}] [expr {$r*sin($a)}]`\ `}`\ `proc toPolars p {`\ `   foreach {x y} $p break`\ `   # for Sun, we have to make sure atan2 gets no two 0's`\ `   list [expr {hypot($x,$y)}] [expr {$x||$y? atan2($y,$x): 0}]`\ `}`\ `proc radInvert p {`\ `   foreach {r a} [toPolars $p] break`\ `   fromPolars [list [expr {$r? 1/$r: 9999999}] $a]`\ `}`\ `proc rippleRad {n s p} {`\ `   foreach {r a} [toPolars $p] break`\ `   fromPolars [list [expr {$r*(1.+$s*sin($n*$a))}] $a]`\ `}`\ `proc slice {n p} {`\ `   foreach {r a} $p break`\ `   list $r [expr {$a*$n/3.14159265359}]`\ `}`\ `proc rotate {angle p} {`\ `   foreach {x y} $p break`\ `   set x1 [expr {$x*cos(-$angle) - $y*sin(-$angle)}]`\ `   set y1 [expr {$y*cos(-$angle) + $x*sin(-$angle)}]`\ `   list $x1 $y1`\ `}`\ `proc swirl {radius p} {`\ `   foreach {x y} $p break`\ `   set angle [expr {hypot($x,$y)*6.283185306/$radius}]`\ `   rotate $angle $p`\ `}` Now comes the demo program. It shows the predefined basic image operators, and some combinations, on a button bar. Click on one, have some patience, and the corresponding image will be displayed on the canvas to the right. You can also experiment with image operators in the entry widget at bottom - hit `<Return>`{=html} to try. The text of sample buttons is also copied to the entry widget, so you can play with the parameters, or rewrite it as you wish. Note that a well-formed funimj composition consists of: - the composition operator \"o\" - zero or more \"painters\" (color -\> color) - one \"drawer\" (point -\> color) - zero or more \"transformers\" (point -\> point) } `proc fim'show {c f} {`\ `   $c delete all`\ `   set ::try $f ;# prepare for editing`\ `   set t0 [clock seconds]`\ `   . config -cursor watch`\ `   update ;# to make the cursor visible`\ `   $c create image 0 0 -anchor nw -image [fim $f $::zoom]`\ `   wm title . "$f: [expr [clock seconds]-$t0] seconds"`\ `   . config -cursor {}`\ `}`\ ` proc fim'try {c varName} {`\ `   upvar #0 $varName var`\ `   $c delete all`\ `   if [catch {fim'show $c [eval $var]}] {`\ `       $c create text 10 10 -anchor nw -text $::errorInfo`\ `   }`\ `}` Composed functions need only be mentioned once, which creates them, and they can later be picked up by info procs. The o looks nicely bullet-ish here.. `o bRings`\ `o cGrad`\ `o checker`\ `o gRings`\ `o vstrip`\ `o xPos`\ `o {bPaint brown beige} checker`\ `o checker {slice 10} toPolars`\ `o checker {rotate 0.1}`\ `o vstrip {swirl 1.5}`\ `o checker {swirl 16}`\ `o {fplot {$y + exp($x)}}`\ `o checker radInvert`\ `o gRings {rippleRad 8 0.3}`\ `o xPos {swirl .75}`\ `o gChecker`\ `o {gPaint red} gRings`\ `o {bin2 {radReg 7} udisk}`\ `#----------------------------------------------- testing` `frame .f2`\ `set c [canvas .f2.c]`\ `set e [entry .f2.e -bg white -textvar try]`\ `bind $e ``<Return>`{=html}` [list fim'try $c ::try]`\ `scale .f2.s -from 1 -to 100 -variable zoom -ori hori -width 6`\ `#--------------------------------- button bar:`\ `frame .f`\ `set n 0`\ `foreach imf [lsort [info procs "o *"]] {`\ `   button .f.b[incr n] -text $imf -anchor w -pady 0 \`\ `       -command [list fim'show $c $imf]`\ `}`\ `set ::zoom 25`\ `eval pack [winfo children .f] -side top -fill x -ipady 0`\ `eval pack [winfo children .f2] -side top -fill x`\ `pack .f .f2 -side left -anchor n`\ `bind . ``<Escape>`{=html}` {exec wish $argv0 &; exit} ;# dev helper`\ `bind . ? {console show} ;# dev helper, Win/Mac only` ### TkPhotoLab The following code can be used for experiments in image processing, including - convolutions (see below) - conversion from color to greylevel - conversion from greylevel to faux color - brightness and contrast modification Tcl is not the fastest in heavy number-crunching, as needed when going over many thousands of pixels, but I wouldn\'t consider C for a fun project ;) So take your time, or get a real CPU. At least you can watch the progress, as the target image is updated after every row. ![](TkPhotoLab.jpg "TkPhotoLab.jpg") *Edge enhancement by Laplace5 filter* The demo UI shows two images, the original on the left, the processing result on the right. You can push the result to the left with Options/Accept. See the menus for what goodies I have supplied. But what most interested me were \"convolutions\", for which you can edit the matrix (fixed at 3x3 - slow enough..) and click \"Apply\" to run it over the input image. \"C\" to set the matrix to all zeroes. Convolution is a technique where a target pixel is colored according to the sum of the product of a given matrix and its neighbors. As an example, the convolution matrix `1 1 1`\ `1 1 1`\ `1 1 1` colors the pixel in the middle with the average of itself and its eight neighbors, which will myopically blur the picture. `0 0 0`\ `0 1 0`\ `0 0 0` should just faithfully repeat the input picture. These `0  -1  0       -1 -1 -1`\ `-1  5 -1  or:  -1  9 -1`\ `0  -1  0       -1 -1 -1` enhance {horizont,vertic}al edges, and make the image look \"crispier\". } `proc convolute {inimg outimg matrix} {`\ `   set w [image width  $inimg]`\ `   set h [image height $inimg]`\ `   set matrix [normalize $matrix]`\ `   set shift  [expr {[matsum $matrix]==0? 128: 0}]`\ `   set imat [photo2matrix $inimg]`\ `   for {set i 1} {$i<$h-1} {incr i} {`\ `       set row {}`\ `       for {set j 1} {$j<$w-1} {incr j} {`\ `          foreach var {rsum gsum bsum} {set $var 0.0}`\ `          set y [expr {$i-1}]`\ `          foreach k {0 1 2} {`\ `             set x [expr {$j-1}]`\ `             foreach l {0 1 2} {`\ `                if {[set fac [lindex $matrix $k $l]]} {`\ `                    foreach {r g b} [lindex $imat $y $x] {}`\ `                    set rsum [expr {$rsum + $r * $fac}]`\ `                    set gsum [expr {$gsum + $g * $fac}]`\ `                    set bsum [expr {$bsum + $b * $fac}]`\ `                }`\ `                incr x`\ `             }`\ `             incr y`\ `           }`\ `           if {$shift} {`\ `               set rsum [expr {$rsum + $shift}]`\ `               set gsum [expr {$gsum + $shift}]`\ `               set bsum [expr {$bsum + $shift}]`\ `           }`\ `           lappend row [rgb [clip $rsum] [clip $gsum] [clip $bsum]]`\ `       }`\ `       $outimg put [list $row] -to 1 $i`\ `       update idletasks`\ `   }`\ `}` `proc alias {name args} {eval [linsert $args 0 interp alias {} $name {}]}` `alias rgb   format #%02x%02x%02x` `proc lambda {argl body} {K [set n [info level 0]] [proc $n $argl $body]}` `proc K      {a b} {set a}` `proc clip   x {expr {$x>255? 255: $x<0? 0: int($x)}}` `proc photo2matrix image {`\ `   set w [image width  $image]`\ `   set h [image height $image]`\ `   set res {}`\ `   for {set y 0} {$y<$h} {incr y} {`\ `       set row {}`\ `       for {set x 0} {$x<$w} {incr x} {`\ `           lappend row [$image get $x $y]`\ `       }`\ `       lappend res $row`\ `   }`\ `   set res`\ `}` `proc normalize matrix {`\ `    #-- make sure all matrix elements add up to 1.0`\ `    set sum [matsum $matrix]`\ `    if {$sum==0} {return $matrix} ;# no-op on zero sum`\ `    set res {}`\ `    foreach inrow $matrix {`\ `        set row {}`\ `        foreach el $inrow {lappend row [expr {1.0*$el/$sum}]}`\ `        lappend res $row`\ `    }`\ `    set res`\ `}` `proc matsum matrix {expr [join [join $matrix] +]}` The following routines could also be generified into one: `proc color2gray image {`\ `   set w [image width  $image]`\ `   set h [image height $image]`\ `   for {set i 0} {$i<$h} {incr i} {`\ `       set row {}`\ `       for {set j 0} {$j<$w} {incr j} {`\ `           foreach {r g b} [$image get $j $i] break`\ `           set y [expr {int(0.299*$r + 0.587*$g + 0.114*$b)}]`\ `           lappend row [rgb $y $y $y]`\ `       }`\ `       $image put [list $row] -to 0 $i`\ `       update idletasks`\ `   }`\ `}` `proc color2gray2 image {`\ `   set i -1`\ `   foreach inrow [photo2matrix $image] {`\ `       set row {}`\ `       foreach pixel $inrow {`\ `           foreach {r g b} $pixel break`\ `           set y [expr {int(($r + $g + $b)/3.)}]`\ `           lappend row [rgb $y $y $y]`\ `       }`\ `       $image put [list $row] -to 0 [incr i]`\ `       update idletasks`\ `   }`\ `}` An experiment in classifying graylevels into unreal colors: `proc gray2color image {`\ `   set i -1`\ `   set colors {black darkblue blue purple red orange yellow white}`\ `   set n [llength $colors]`\ `   foreach inrow [photo2matrix $image] {`\ `       set row {}`\ `       foreach pixel $inrow {`\ `           set index [expr {[lindex $pixel 0]*$n/256}]`\ `           lappend row [lindex $colors $index]`\ `       }`\ `       $image put [list $row] -to 0 [incr i]`\ `       update idletasks`\ `   }`\ `}` `proc grayWedge image {`\ `   $image blank`\ `   for {set i 0} {$i<256} {incr i} {`\ `       $image put [rgb $i $i $i] -to $i 0 [expr {$i+1}] 127`\ `   }`\ `}` A number of algorithms are very similar, distinguished only by a few commands in the center. Hence I made them generic, and they take a function name that is applied to every pixel rgb, resp. a pair of pixel rgb\'s. They are instantiated by an alias that sets the function fancily as a lambda: `proc generic_1 {f target source} {`\ `   set w [image width  $source]`\ `   set h [image height $source]`\ `   for {set i 0} {$i<$h} {incr i} {`\ `       set row {}`\ `       for {set j 0} {$j<$w} {incr j} {`\ `           foreach {r g b} [$source get $j $i] break`\ `           lappend row [rgb [$f $r] [$f $g] [$f $b]]`\ `       }`\ `       $target put [list $row] -to 0 $i`\ `       update idletasks`\ `   }`\ `}` `alias invert    generic_1 [lambda x {expr {255-$x}}]`\ `alias contrast+ generic_1 [lambda x {clip [expr {128+($x-128)*1.25}]}]`\ `alias contrast- generic_1 [lambda x {clip [expr {128+($x-128)*0.8}]}]` `proc generic_2 {f target with} {`\ `   set w [image width  $target]`\ `   set h [image height $target]`\ `   for {set i 0} {$i<$h} {incr i} {`\ `       set row {}`\ `       for {set j 0} {$j<$w} {incr j} {`\ `           foreach {r g b} [$target get $j $i] break`\ `           foreach {r1 g1 b1} [$with get $j $i] break`\ `           lappend row [rgb [$f $r $r1] [$f $g $g1] [$f $b $b1]]`\ `       }`\ `       $target put [list $row] -to 0 $i`\ `       update idletasks`\ `   }`\ `}` `alias blend      generic_2 [lambda {a b} {expr {($a+$b)/2}}]`\ `alias difference generic_2 [lambda {a b} {expr {255-abs($a-$b)}}]` A histogram is a count of which color value occurred how often in the current image, separately for red, green and blue. For graylevel images, the displayed \"curves\" should exactly overlap, so you see only the blue dots that are drawn last. `proc histogram {image {channel 0}} {`\ `   set w [image width  $image]`\ `   set h [image height $image]`\ `   for {set i 0} {$i<256} {incr i} {set hist($i) 0}`\ `   for {set i 0} {$i<$h} {incr i} {`\ `       for {set j 0} {$j<$w} {incr j} {`\ `           incr hist([lindex [$image get $j $i] $channel])`\ `       }`\ `   }`\ `   set res {}`\ `   for {set i 0} {$i<256} {incr i} {lappend res $hist($i)}`\ `   set res`\ `}` `proc drawHistogram {target input} {`\ `   $target blank`\ `   set a [expr {6000./([image height $input]*[image width $input])}]`\ `   foreach color {red green blue} channel {0 1 2} {`\ `       set i -1`\ `       foreach val [histogram $input $channel] {`\ `           $target put $color -to [incr i] \`\ `               [clip [expr {int(128-$val*$a)}]]`\ `       }`\ `       update idletasks`\ `   }`\ `}` Demo UI: `if {[file tail [info script]] eq [file tail $argv0]} {`\ `   package require Img ;# for JPEG etc.`\ `   proc setFilter {w matrix} {`\ `       $w delete 1.0 end`\ `       foreach row $matrix {$w insert end [join $row \t]\n}`\ `       set ::info "Click 'Apply' to use this filter"`\ `   }`\ `   label .title -text TkPhotoLab -font {Helvetica 14 italic} -fg blue`\ `   label .( -text ( -font {Courier 32}`\ `   set txt [text .t -width 20 -height 3]`\ `   setFilter .t ``{{0 -1 0} {-1 5 -1} {0 -1 0}}`{=mediawiki}\ `   label .) -text ) -font {Courier 32}`\ `   button .c -text C -command {setFilter .t ``{{0 0 0} {0 0 0} {0 0 0}}`{=mediawiki}`}`\ `   grid .title .( .t .) .c -sticky news`\ `   button .apply -text Apply -command applyConv`\ `   grid x ^ ^ ^ .apply -sticky ew`\ `   grid [label .0 -textvar info] - - -sticky w`\ `   grid [label .1] - [label .2] - - -sticky new` `   proc loadImg { {fn ""}} {`\ `       if {$fn==""} {set fn [tk_getOpenFile]}`\ `       if {$fn != ""} {`\ `           cd [file dirname [file join [pwd] $fn]]`\ `           set ::im1 [image create photo -file $fn]`\ `           .1 config -image $::im1`\ `           set ::im2 [image create photo]`\ `           .2 config -image $::im2`\ `           $::im2 copy $::im1 -shrink`\ `           set ::info "Loaded image 1 from $fn"`\ `       }`\ `   }`\ `   proc saveImg { {fn ""}} {`\ `       if {$fn==""} {set fn [tk_getSaveFile]}`\ `       if {$fn != ""} {`\ `           $::im2 write $fn -format JPEG`\ `           set ::info "Saved image 2 to $fn"`\ `       }`\ `   }`\ `   proc applyConv {} {`\ `       set ::info "Convolution running, have patience..."`\ `       set t0 [clock clicks -milliseconds]`\ `       convolute $::im1 $::im2 [split [$::txt get 1.0 end] \n]`\ `       set dt [expr {([clock click -milliseconds]-$t0)/1000.}]`\ `       set ::info "Ready after $dt sec"`\ `   }` A little wrapper for simplified menu creation - see below for its use: `   proc m+ {head name {cmd ""}} {`\ `       if {![winfo exists .m.m$head]} {`\ `           .m add cascade -label $head -menu [menu .m.m$head -tearoff 0]`\ `       }`\ `       if [regexp ^-+$ $name] {`\ `           .m.m$head add separator`\ `       } else {.m.m$head add command -label $name -comm $cmd}`\ `   }` `   . config -menu [menu .m]`\ `   m+ File Open.. loadImg`\ `   m+ File Save.. saveImg`\ `   m+ File ---`\ `   m+ File Exit   exit` `   m+ Edit Blend      {blend $im2 $im1}`\ `   m+ Edit Difference {difference $im2 $im1}`\ `   m+ Edit ---`\ `   m+ Edit Negative   {invert     $im2 $im1}`\ `   m+ Edit Contrast+  {contrast+  $im2 $im1}`\ `   m+ Edit Contrast-  {contrast-  $im2 $im1}`\ `   m+ Edit ---`\ `   m+ Edit Graylevel  {$im2 copy $im1 -shrink; color2gray  $im2}`\ `   m+ Edit Graylevel2 {$im2 copy $im1 -shrink; color2gray2 $im2}`\ `   m+ Edit "Add Noise" {`\ `       generic_1 [lambda x {expr {rand()<.01? int(rand()*255):$x}}] $im2 $im1`\ `   }`\ `   m+ Edit gray2color {$im2 copy $im1 -shrink; gray2color $im2}`\ `   m+ Edit Octary {generic_1 [lambda x {expr {$x>127? 255:0}}] $im2 $im1}`\ `   m+ Edit ---`\ `   m+ Edit HoriMirror {$im2 copy $im1 -shrink -subsample -1 1}`\ `   m+ Edit VertMirror {$im2 copy $im1 -shrink -subsample 1 -1}`\ `   m+ Edit "Upside down" {$im2 copy $im1 -shrink -subsample -1 -1}`\ `   m+ Edit ---`\ `   m+ Edit "Zoom x 2" {$im2 copy $im1 -shrink -zoom 2}`\ `   m+ Edit "Zoom x 3" {$im2 copy $im1 -shrink -zoom 3}` `   m+ Options "Accept (1<-2)" {$im1 copy $im2 -shrink}`\ `   m+ Options ---`\ `   m+ Options "Gray wedge" {grayWedge $im2}`\ `   m+ Options Histogram  {drawHistogram $im2 $im1}` `   m+ Filter Clear {setFilter .t ``{{0 0 0} {0 0 0} {0 0 0}}`{=mediawiki}`}`\ `   m+ Filter ---`\ `   m+ Filter Blur0  {setFilter .t ``{{1 1 1} {1 0 1} {1 1 1}}`{=mediawiki}`}`\ `   m+ Filter Blur1  {setFilter .t ``{{1 1 1} {1 1 1} {1 1 1}}`{=mediawiki}`}`\ `   m+ Filter Gauss2 {setFilter .t ``{{1 2 1} {2 4 2} {1 2 1}}`{=mediawiki}`}`\ `   m+ Filter ---`\ `   m+ Filter Laplace5 {setFilter .t ``{{0 -1 0} {-1 5 -1} {0 -1 0}}`{=mediawiki}`}`\ `   m+ Filter Laplace9 {setFilter .t {{-1 -1 -1} {-1 9 -1} {-1 -1 -1}}}`\ `   m+ Filter LaplaceX {setFilter .t ``{{1 -2 1} {-2 5 -2} {1 -2 1}}`{=mediawiki}`}`\ `   m+ Filter ---`\ `   m+ Filter Emboss   {setFilter .t ``{{2 0 0} {0 -1 0} {0 0 -1}}`{=mediawiki}`}`\ `   m+ Filter HoriEdge {setFilter .t {{-1 -1 -1} {0 0 0} {1 1 1}}}`\ `   m+ Filter VertEdge {setFilter .t {{-1 0 1} {-1 0 1} {-1 0 1}}}`\ `   m+ Filter SobelH   {setFilter .t ``{{1 2 1} {0 0 0} {-1 -2 -1}}`{=mediawiki}`}`\ `   m+ Filter SobelV   {setFilter .t ``{{1 0 -1} {2 0 -2} {1 0 -1}}`{=mediawiki}`}` `   bind . ``<Escape>`{=html}` {exec wish $argv0 &; exit}`\ `   bind . ``<F1>`{=html}` {console show}`\ `   loadImg aaa.jpg`\ `}`
# Tcl Programming/TCL and ADP `<font size=3>`{=html}**Tcl and ADP Reference**`</font>`{=html} This is a reference for using Tcl with ADP pages, for people setting up a site with the ArsDigita Community System (see OpenACS for details). The first half is just a Tcl overview; the second half deals with .adp pages, custom tags, and AOLServer resources and parameters. ## Tcl Overview ### Basic Tcl Language Features **`; or newline`**` statement separator`\ **`\`**` statement continuation if last character in line`\ **`#`**` comment out rest of line (if 1st non−whitespace char)`\ **`var`**` simple variable`\ **`var(index)`**` associative array variable`\ **`var(i,j)`**` multidimensional associative array variable`\ **`$var`**` variable substitution (also ${var}xyz)`\ **`[expr 1+2]`**` command substitution`\ **`\char`**` backslash substitution`\ **`"hello $a"`**` quoting with substitution`\ **`{hello $a}`**` quoting with no subst (deferred substitution)`\ *The only datatype in Tcl is a string. Some commands interpret arguments as numbers/booleans; those formats are:*\'\ **`Integer`**`: 12 0xff(hex) 0377(octal)`\ **`Floating Pt`**`: 2.1 3. 6e4 7.91e+16`\ **`Boolean`**`: true false 0 1 yes no` ### Backslash Substitutions **`\a`**` audible alert (0x7)`\ **`\b`**` backspace (0x8)`\ **`\f`**` form feed (0xC)`\ **`\n`**` newline (0xA)`\ **`\r`**` carriage return (0xD)`\ **`\t`**` horizontal tab (0x9)`\ **`\v`**` vertical tab (0xB)`\ **`\space`**` space`\ **`\newline`**` space`\ **`\ddd`**` octal value (d=0−7)`\ **`\xdd`**` hex value (d=0−9,a−f)`\ **`\c`**` replace ’\c’ with ’c’`\ **`\\`**` backslash` ### Operators and Math Functions *The **expr** command recognizes these operators, in decreasing order of precedence:* − ~ ! unary minus, bitwise NOT, logical NOT * / % multiply, divide, remainder + − add, subtract << >> bitwise shift left, bitwise shift right < > <= >= boolean comparisons == != boolean equals, not equals & bitwise AND ^ bitwise exclusive OR | bitwise inclusive OR && logical AND || logical OR x ? y : z if x != 0, then y, else z *All operators support integers. All support floating point except : `~, %, <<, >>, %, ^, and |`. Boolean operators can also be used for string operands, in which case string comparison will be used. This occurs if any of the operands are not valid numbers. The following operators have \"lazy evaluation\" as in C:*\ **`&&, ||, ?:`**\ *The expr command recognizes the following math functions:*\ `abs hypot int double floor ceil fmod round`\ `cos sin tan acos asin atan atan2 cosh sinh tanh`\ `log log10 exp pow sqrt'''` ### Regular Expressions regex | regex match either expression regex* match zero or more of regex regex+ match one or more of regex regex? Match zero or one of regex . any single character except newline ^ match beginning of string $ match end of string \c match character c c match character c [abc] match set of characters [^abc] match characters not in set [a−z] match range of characters [^a−z] match characters not in range ( ) group expressions ### Pattern Globbing ? match any single character * match zero or more characters [abc] match set of characters [a−z] match range of characters \c match character c {a,b,...} match any of string a, b, etc. ~ home directory (for glob command) ~user match user’s home directory (for glob command) Note: for the glob command, a "." at the beginning of a file’s name or just after "/" must be matched explicitly and all "/" characters must be matched explicitly. ### Control Flow break Abort innermost containing loop command case Obsolete, see switch continue Skip to next iteration of innermost containing loop. exit[returnCode] Terminate the process, return returnCode (an integer which defaults to 0) to the system as the exit status. for start test next body Looping command where start, next, and body are Tcl command strings and test is an expression string to be passed to expr command. foreach varname list body The Tcl command string body is evaluated for each item in the string list where the variable varname is set to the item’s value. if expr1 [then] body1 [elseif expr2 [then] body2...] [[else] bodyN] If expression string expr1 evaluates true, Tcl command string body1 is evaluated. Otherwise if expr2 is true, body2 is evaluated, and so on. If none of the expressions evaluate to true, then bodyN is executed. return [−code code] [−errorinfo info] [−errorcode code] [string] Return immediately from current procedure with string as return value. switch [options] string pattern1 body1 [ pattern2 body2 ...] The string argument is matched against each of the pattern arguments in order. As soon as it finds a pattern that matches string, it evaluates the corresponding Tcl command string body. If no match is found and the last pattern is the keyword default, its command string is evaluated while test body Evaluates the Tcl command string body as long as expression string test evaluates to true. ### Lists Note: list indices start at 0 and the word end may be used to reference the last element in the list. concat [arg arg ...] Returns concatenation of each string join list [joinString] Returns string created by joining all elements of list with joinString. lappend varName [value value ...] Appends each value to the end of the list stored in varName. lindex list index Returns value of element at index in list. linsert list index element [element ...] Returns new list formed by using each arg as an element. llength list Returns number of elements in list. lrange list first last Returns new list from slice of list at indices first through last inclusive. lsearch [mode] list pattern Returns index of first element in list that matches pattern (−1 for no match). Mode may be −exact, −glob(default) or −regexp. lsort [switches] list Returns new list formed by sorting list according to switches. These are: −ascii string comparison (default) −integer integer comparisons −real floating−point comparisons −increasing sort in increasing order (default) −decreasing sort in decreasing order −command cmd Use command which takes two arguments and returns an integer less than, equal to, or greater than zero. split string [splitChars] Returns a list formed by splitting string at each character in splitChars. ### Strings append varName [value value ...] Appends each of the given values to the string stored in varName. format formatString [arg arg ...] Returns a formatted string generated in the ANSI C sprintf manner. regexp [switches] exp string [matchVar] [subMatchVar ...] Returns 1 if the regular expression exp matches part or all of string, 0 otherwise. If specified, matchVar will be wet to all the characters in the match and the following subMatchVar’s will be set to matched parenthesized subexpressions. The −nocase switch can be specified to ignore case in matching. The −indices switch can be specified so that matchVar and subMatchVar will be set to the start and ending indice3s in string of their corresponding match. regsub [switches] exp string subSpec varName Replaces the first portion of string that matches the regular expression exp with subSpec and places results in varName. Returns count of number of replacements made. The −nocase switch can be specified to ignore case in matching. The −all switch will cause all matches to be substituted for. scan string formatString varName [varName ...] Extracts values into given variables using ANSI C sscanf behavior. string compare string1 string2 Return −1, 0, or 1, depending on whether string1 is lexicographically less than, equal to, or greater than string2. string first string1 string2 Return index in string2 of first occurrence of string1 (−1 if not found). string index string charIndex Returns the charIndex’th character in string. string last string1 string2 Return index in string2 of last occurrence of string1 (−1 if not found). string length string Returns number of characters in string. string match pattern string Returns 1 if glob pattern matches string, 0 otherwise. string range string first last Returns characters from string at indices first through last inclusive. string tolower string Returns new string formed by converting all chars in string to lower case. string toupper string Returns new string formed by converting all chars in string to upper case. string trim string [chars] Returns new string formed by removing from string any leading or trailing characters present in the set chars. string trimleft string [chars] Same as string trim for leading characters only. string trimright string [chars] Same as string trim for trailing characters only. string wordend string index Returns index of character just after last one in word at index in string. string wordstart string index Returns index of first character of word at index in string. subst [−nobackslashes] [−nocommands] [−novariables] string Returns result of backslash, command, and variable substitutions on string. Each may be turned off by switch. ## The Tcl \<\--\> ADP interface ### Including TCL code in ADP pages *Inline replacement:* `<%= tcl code that evaluates to the text you want embedded %>` *State changing Code:* `<% tcl commands to change tcl environment (set vars, do db queries, etc) %>` *Example:* `Two plus two is <%= [expr 2+2] %>` ### Defining custom tags ``` tcl ns_register_adptag "codeexample" "/codeexample" tcl_adp_codeexample proc tcl_adp_codeexample {string tagset} { return "<blockquote> <code><pre>${string}</pre></code> </blockquote> " } ``` ### Using AOLServer Parameters [ad_parameter UsersCanCreateRoomsP chat] ### Resourcing tcl in AOLserver *source−file.tcl − to source a particular file.* set_the_usual_form_variables ns_eval [list source $file] ns_return 200 text/html ok wget −O − "http://localhost:8000/source− file.tcl?file=/web/server1/tcl/myfile.tcl" *Note: this does not work for registered tag changes. To cause a reload of everything:* <% set dir [ns_info tcllib] set list [exec ls $dir] foreach file $list { source $dir/$file ns_puts "sourced: $file "}%> ### Using ns_set *When one queries a database, the variable that is set is an ns_set:* # ask AOLserver to give us a database connection set db [ns_db gethandle] set sql_query "select first_names, last_name from users where user_id = $user_id" # actually send the query to the RDBMS; tell AOLserver we # expect exactly one row back set selection [ns_db 1row $db $sql_query] <pre> ''Getting information out of an ns_set:'' <pre> set first_names [ns_set get $selection "first_names"] set last_name [ns_set get $selection "last_name"] ns_return 200 text/plain "User #$user_id is $first_names $last_name" ### Dealing with Form Variables *Importing form variables into a tcl or adp page* `set_the_usual_form_variables` *Manipulating Forms Directly:* `ns_getform` ### Decode *Do logic w/o breaking out of an ns_write. Just like SQL !* `[util_decode unknown val1 res1 val2 res2 valN resN defaultresult]` ### Dealing With .ini file Parameters *ad_parameter* `ad_parameter name { subsection "" } { default "" }` Returns the value of a configuration parameter set in one of the .ini files in /web/yourdomain/parameters. If the parameter doesn’t exist, returns the default specified as the third argument (or empty string if not default is specified). Note that AOLserver reads these files when the server starts up and stores parameters in an in−memory hash table. The plus side of this is that there is no hit to the file system and no need to memoize a call to ad_parameter. The minus side is that you have to restart the server if you want to test a change made to the .ini file. *ad_parameter_section* `ad_parameter_section { subsection "" }` Returns all the vars in a parameter section as an ns_set. Relies on undocumented AOLserver Tcl API call ns_configsection (analogous C API call is documented). Differs from the API call in that it returns an empty ns_set if the parameter section does not exist. ### Converting tcl to adp *inclusion of sub−files* # Source user−new.adp. We would redirect to it, but we don’t want # the password exposed! # source "[ns_url2file "/register/user−new.tcl"]" # return ns_adp_include user−new.adp ns_adp_break
# Tcl Programming/Appendix ## Appendix ### Resources - The main page of Tcl developers is the Tcl Developer Xchange. - Download a free binary ActiveTcl distribution at ActiveState. - The main USENET forum dedicated to this language is *<news:comp.lang.tcl>*. - In German, there\'s also <http://www.self-tcl.de/forum> for questions and answers - The main user wiki is The Tclers Wiki. - The Tclers\' Chat can provide quick response to questions: Jabber all.tclers.tk:5222, IRC freenode #tcl, or Webchat <http://mini.net/cgi-bin/chat.cgi> (all of the three being relayed between each other) - The Tcl man pages can be found here. - The Tk man pages can be found here. - Documentation on Tcllib, the Tcl standard library is here. - There is a tutorial for Tcl here. For Web development, there are: - pure-Tcl Web servers like Tclhttpd, which can be embedded in your Tcl-enabled applications to provide Web-based interfaces, - Tcl-based Web servers like AOLServer, which are much faster than their pure-Tcl cousins and able to support a heavy load, and - Tcl Web server modules (see Apache Tcl for examples) that enable Tcl Web applications with bog-standard Web servers. ### ActiveState Community License *This is the license of the \"Batteries-included\" ActiveTcl distribution. Note that you cannot redistribute ActiveTcl \"outside your organization\" without written permission.* The part between \"AGREEMENT\" and \"Definitions:\" is the more free, BSD-style license of Tcl and Tk itself. **Preamble:** The intent of this document is to state the conditions under which the Package (ActiveTcl) may be copied and distributed, such that ActiveState maintains control over the development and distribution of the Package, while allowing the users of the Package to use the Package in a variety of ways. The Package may contain software covered by other licenses: **TCL LICENSE AGREEMENT** This software is copyrighted by the Regents of the University of California, Sun Microsystems, Inc., Scriptics Corporation, and other parties. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. The authors hereby grant permission to use, copy, modify, distribute, and license this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. No written agreement, license, or royalty fee is required for any of the authorized uses. Modifications to this software may be copyrighted by their authors and need not follow the licensing terms described here, provided that the new terms are clearly indicated on the first page of each file where they apply. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. GOVERNMENT USE: If you are acquiring this software on behalf of the U.S. government, the Government shall have only \"Restricted Rights\" in the software and related documentation as defined in the Federal Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you are acquiring the software on behalf of the Department of Defense, the software shall be classified as \"Commercial Computer Software\" and the Government shall have only \"Restricted Rights\" as defined in Clause 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the authors grant the U.S. Government and others acting in its behalf permission to use and distribute the software in accordance with the terms specified in this license. **Definitions:** \"ActiveState\" refers to ActiveState Corp., the Copyright Holder of the Package. \"Package\" refers to those files, including, but not limited to, source code, binary executables, images, and scripts, which are distributed by the Copyright Holder. \"You\" is you, if you are thinking about copying or distributing this Package. **Terms:** 1\. You may use this Package for commercial or non-commercial purposes without charge. 2\. You may make and give away verbatim copies of this Package for personal use, or for use within your organization, provided that you duplicate all of the original copyright notices and associated disclaimers. You may not distribute copies of this Package, or copies of packages derived from this Package, to others outside your organization without specific prior written permission from ActiveState (although you are encouraged to direct them to sources from which they may obtain it for themselves). 3\. You may apply bug fixes, portability fixes, and other modifications derived from ActiveState. A Package modified in such a way shall still be covered by the terms of this license. 4\. ActiveState\'s name and trademarks may not be used to endorse or promote packages derived from this Package without specific prior written permission from ActiveState. 5\. THIS PACKAGE IS PROVIDED \"AS IS\" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ActiveState Community License Copyright (C) 2001-2003 ActiveState Corp. All rights reserved.
# Wikijunior:Kings and Queens of England/Introduction Welcome to the Wikijunior book on Kings and Queens of England. In this book, we will start by looking at the very first Anglo-Saxon Kings of England. We will then move on to show how the Crown changed hands many times as a result of conquest. We see some powerful kings and some weak ones. We see how the Crown has battled Parliament. We look at the period where power finally did transfer to Parliament through to the times of our current queen, Elizabeth II. At the end we will also look at who the next kings of England may be. We will find out about eleven Kings called Edward and nine called Henry and a nine-day queen and King Philip, who most people have now forgotten about. But first let\'s start way back in 871 with the Anglo-Saxons and the only king of England to be called \"Great,\" Alfred.
# Wikijunior:Kings and Queens of England/The House of Lancaster ## Henry IV (1399- 1413) !Henry IV{width="190"} **Henry IV** was born on 3 April 1367 at Bolingbroke Castle in Lincolnshire, which was why he was also known as Henry Bolingbroke. His father was the third son of King Edward III of England, John of Gaunt. After landing in Yorkshire in 1398, Henry had enough support to be declared king by parliament in 1399. As king, Henry consulted with parliament often, but he sometimes disagreed with them, particularly over church matters. Henry was the first English king to allow the burning of heretics. Henry spent much of his reign defending himself against plots, rebellions and assassination attempts. Rebellions continued throughout the first ten years of Henry\'s reign. These included the revolt of Owen Glendower, who declared himself Prince of Wales in 1400, and the rebellion of Henry Percy, 1st Earl of Northumberland. The king\'s success in putting down these rebellions was due partly to the military ability of his eldest son, Henry, who would later become King. In 1406, English soldiers captured the future King James I of Scotland as he was going to France. James remained a prisoner of Henry for the rest of Henry\'s reign. ### Marriages and children In 1381, 18 years before becoming king, Henry married Mary de Bohun. They had two daughters and four sons, one of which was the future King Henry V of England. Mary died in 1394, and in 1403 Henry married Joanna of Navarre, the daughter of Charles d\'Évreux, King of Navarre. She was the widow of John V of Brittany, with whom she had four daughters and four sons, but she and Henry had no children. The later years of Henry\'s reign were marked by serious health problems. He had some sort of disfiguring skin disease, and more seriously suffered acute attacks of some grave illness in June 1405, April 1406, June 1408, during the winter of 1408-09, December 1412, and then finally a fatal bout in March 1413. Unusually for a king of England, he was buried not at Westminster Abbey but at Canterbury Cathedral, as near to the shrine of Thomas Becket as possible. ## Henry V (1413-1422) !King Henry V. **Henry V** was born in Monmouth in 1387. He was king from 1413 to his death in 1422 By the time Henry died, he had not only consolidated power as the King of England but had also effectively accomplished what generations of his ancestors had failed to achieve through decades of war: unification of the crowns of England and France in a single person. ### Life before became King When Henry\'s father, Henry Bolingbroke, was exiled in 1398, Richard II took the boy into his own charge and treated him kindly. In 1399 the Lancastrian revolution brought Bolingbroke. He was created Duke of Lancaster on 10 November 1399, the third person to hold the title that year. In 1403 the sixteen-year-old prince was almost killed by an arrow which became lodged in his face. An ordinary soldier would have been left to die from such a wound, but Henry had the benefit of the best possible care, and, over a period of several days after the incident, the royal physician crafted a special tool in order to extract the tip of the arrow without doing further damage. The operation was successful. The Welsh revolt of Owen Glendower took up much of Henry\'s attention until 1408. Then, as a result of the King\'s ill-health, Henry began to take a wider interest in politics. From January 1410, he had practical control of the government. In 1413 his father died and Henry became king. ### Reign When he became king, Henry had to deal with three main problems: the restoration of domestic peace, the healing of rift in the Church and the recovery of English prestige in Europe. Henry tackled all of the domestic policies together, and gradually built on them a wider policy. From the first he made it clear that he would rule England as the head of a united nation. The heirs of those who had suffered in the last reign were restored gradually to their titles and estates. Henry then turned his attention to foreign affairs, in particular the war with France and his claim to be King of it. 25 October 1415 saw Henry score a great success in this campaign at Agincourt. The command of the sea was secured by driving the Genoese allies of the French out of the English Channel. Successful diplomacy saw the Holy Roman Emperor, Sigismund, cease his support of Henry\'s French foes, whilst the Treaty of Canterbury helped end the rift in the Church. With the French having lost the support of the Genoese and the Holy Roman Emperor, with these 2 allies gone, the war was renewed on a larger scale in 1417. Lower Normandy was quickly conquered, and Rouen was cut off from Paris and besieged. The French were paralysed by the disputes of Burgundians and Armagnacs. Henry skilfully played them off one against the other, without relaxing his warlike energy. In January 1419 Rouen fell. By August the English were outside the walls of Paris. The internal disputes of the French parties ended with the killing of John of Burgundy by men loyal to the heir to the French throne. Philip, the new Duke of Burgundy, and the French court threw themselves into Henry\'s arms. After six months\' negotiation Henry was recognised as heir and regent of France. On 2 June 1420, Henry married Catherine of Valois, the French king\'s daughter. Following his death, Catherine secretly married a Welsh courtier, Owen Tudor, grandfather of the future King Henry VII of England. ### Death Henry then made plans for a new Crusade began to take shape as the French situation became clearer. Henry visited to England in 1421, but returned to France after forces led by the Duke of Clarence were defeated at the Battle of Baugé. The hardships of the longer winter siege of Meaux broke down his health, and he died of dysentery at Bois de Vincennes on 31 August 1422. Had he lived another two months, he would have been crowned King of France. Henry was buried in Westminster Abbey. He was succeeded by his infant son, Henry. ## Henry VI (1422-1461, 1470-1471) !Henry VI{width="150"} **Henry VI** was born at Windsor Castle on 6 December 1421, the son of King Henry V. He was King of England from 1422, when he was nine months old. In 1423, parliament was called and a regency council was appointed. Humphrey, Duke of Gloucester, Henry IV\'s youngest son, was appointed Protector and Defender of the Realm and the Church until the King came of age, but the Council had the power to replace him at any time. His duties were limited to keeping the peace and summoning and dissolving Parliament. Henry was eventually crowned King of England in Westminster Abbey on 6 November 1429 a month before his eighth birthday, and as King of France at Notre Dame in Paris on 16 December 1431. However, during the rule of the regency council, much of the ground his father gained in France was lost. A revival of French fortunes, beginning with the military victories of Joan of Arc, led to the French nobles preferring the French dauphin, who was crowned as King of France at Reims. Diplomatic errors as well as military failures resulted in the loss of most of the English territories in France. Henry assumed the reins of government when he was declared of age in 1437. On gaining his majority, Henry VI proved to be a deeply spiritual man, lacking the worldly wisdom necessary to allow him to rule effectively. Right from the time he assumed control as king, he allowed his court to be dominated by a few noble favorites, and the peace party, which was in favour of ending the war in France, quickly came to dominate. ### Marriage It was thought that the best way of pursuing peace with France was through a marriage with King Charles VII of France\'s niece, Margaret of Anjou. Henry agreed, especially when he heard reports of Margaret\'s stunning beauty. Charles agreed to the marriage on condition that he would not have to provide the customary dowry and instead would receive the lands of Maine and Anjou from the English. These conditions were agreed to in the Treaty of Tours, but the cession of Maine and Anjou was kept secret from parliament. It was known that this would be hugely unpopular with the English populace. The marriage went ahead in 1445 and Margaret\'s character seems to have complemented that of Henry\'s in that she was prepared to take decisions and show leadership where he was content to be led by her. In this much Margaret proved a more competent ruler than Henry ever was, even though she was only sixteen at that time. The issue of Maine and Anjou finally became public knowledge in 1446. ### Reign The government\'s increasing unpopularity was due to a breakdown in law and order, corruption, the distribution of royal land to the king\'s court favourites, the troubled state of the crown\'s finances, and the steady loss of territories in France. In 1447, this unpopularity took the form of a Commons campaign against the Duke of Suffolk, who was the most unpopular of all the King\'s favourites was widely seen as a traitor, partly because of his role in negotiating the Treaty of Tours. Henry was forced to send him into exile, but his ship was boarded in the English Channel, and he was murdered. His body was found on the beach at Dover. In 1449, the Duke of Somerset, who was leading the campaign in France, started more battles in Normandy, but by the autumn had been pushed back to Caen. By 1450, the French had retaken the whole province. Returning troops, who had often not been paid, added to the sense of lawlessness in the southern counties of England, and Jack Cade led a rebellion in Kent in 1450. Henry came to London with an army to crush the rebellion, but was persuaded to keep half his troops behind while the other half met Cade at Sevenoaks. Cade triumphed and went on to occupy London. In the end, the rebellion achieved nothing, and London was retaken after a few days of disorder, but the rebellion showed that feelings of discontent were running high. In 1450, the Duchy of Aquitaine, held since Henry II\'s time, was also lost, leaving Calais as England\'s only remaining territory in France. By 1452, Richard, Duke of York, who had been sidelined by being made ruler of Ireland, was persuaded to return amd claim his rightful place on the council, and put an end to bad government. His cause was a popular one, and he soon raised an army at Shrewsbury. The king\'s supporters raised their own similar-sized force in London. A stand-off took place south of London, with the Duke of York giving a list of grievances and demands to the king\'s supporters. One of the demands was the arrest of the Duke of Somerset. The king initially agreed, but Margaret intervened to prevent it. By 1453, the Duke of Somerset regained his influence, and the Duke of York was again isolated. In the meantime, an English advance in Aquitaine had retaken Bordeaux and was having some success, and the queen announced that she was pregnant. However, English success in Aquitaine was short-lived, and on hearing the news of the English defeat in August 1453, Henry slipped into a mental breakdown and became completely unaware of everything that was going on around him. This was to last for more than a year, and Henry failed even to respond to the birth of his own son and heir, Edward. The Duke of York, meanwhile, had gained a very important ally, the Earl of Warwick, who was one of the very influential and rich. The Duke York was named regent as Protector of the Realm in 1454, and the queen lost all her power. Somerset was held prisoner in the Tower of London. The Duke of York\'s months as regent were spent tackling the problem of government overspending. On Christmas Day 1454, however, Henry regained his senses. ### Henry\'s character Henry was kind and generous to those he cared about, giving away land and titles to his advisors. He dressed simply. He was keen on reading and \'book-learning\' but did not like leading his country in battle. Keen on the promotion of education, Henry gave generous grants for the foundation of both Eton College near Windsor, for the education of students from poor backgrounds, and King\'s College, Cambridge, where they could continue their education. Henry seems to have been a decent man, but completely unsuited to kingship. He allowed himself to dominated by the power-hungry factions which surrounded him at court and was later powerless to stop the outbreak of bloody civil war. It was too much for him to cope with, as his recurring mental illness from 1453 onwards showed. ### The Wars of the Roses Nobles who had grown in power during Henry\'s reign, but who did not like Henry\'s government, took matters into their own hands by backing the claims of the rival House of York, first to the regency, and then to the throne itself. After a violent struggle between the houses of Lancaster and York, Henry was deposed on 4 March 1461 by his cousin, Edward of York, who became King Edward IV. But Edward failed to capture Henry and his queen, and they were able to flee into exile abroad. During the first period of Edward IV\'s reign, Lancastrian resistance continued mainly under the leadership of Queen Margaret and the few nobles still loyal to her in the northern counties of England and Wales. Henry was captured by King Edward in 1465 and subsequently held captive in the Tower of London. Queen Margaret was exiled, first in Scotland and then in France. However, she was determined to win back for her husband and son, and with the help of King Louis XI of France she eventually allied with the Earl of Warwick, who had fallen out with Edward IV. Warwick returned to England, defeated the Yorkists in battle, set Henry VI free and restored him to the throne on 30 October 1470. Henry\'s return to the throne lasted a very short time. By this time, years in hiding followed by years as a prisoner had taken their toll on Henry, who had been weak-willed and mentally unstable to start with. Henry looked tired and vacant as Warwick and his men paraded him through the streets of London as the rightful King of England. Within a few months Warwick had gone too far by declaring war on Burgundy, whose ruler responded by giving Edward IV the assistance he needed to win back his throne by force. ### Death Henry VI was again held prisoner, this time in the Tower of London, and he was murdered there on 21 May 1471. Popular legend has accused Richard III of his murder, as well as the murder of Henry VI\'s son, Edward. Each year on the anniversary of Henry VI\'s death, the Provosts of Eton and King\'s College, Cambridge, lay roses and lilies on the altar which now stands where he died. King Henry VI was originally buried in Chertsey Abbey. In 1485 his body was moved to St George\'s Chapel at Windsor Castle. He was succeeded as king by Edward, son of Richard, Duke of York. ## References
# Wikijunior:Kings and Queens of England/The House of York ## Edward IV (1461-1470, 1471-1483) !Edward IV **Edward IV** was born on 28 April 1442 at Rouen in France. He was the eldest son of Richard, Duke of York, a leading claimant to the throne of England. Richard\'s challenge to the ruling family started the Wars of the Roses. When his father was killed in 1460 whilst pressing his claim to be king against Henry VI at the Battle of Wakefield, Edward inherited his claim. Edward won the support of Richard Neville, the Earl of Warwick, whose nickname is \"The Kingmaker\". Edward then defeated the Lancastrians in a number of battles. While Henry was campaigning in the north, Warwick gained control of London and had Edward declared king in 1461. Edward strengthened his claim with victory at the Battle of Towton in the same year, where the Lancastrian army was virtually wiped out. ### Marriage and children Edward was tall, strong, handsome, generous, and popular. Warwick, believing that he could continue to rule through Edward, wanted him to marry into a major European family. Edward, however, secretly married a widow, Elizabeth Woodville. They had ten children together. Under an act of Parliament of 1484, one year after Edward IV\'s death, all of Edward\'s children by Elizabeth Woodville were declared illegitimate on the grounds that Edward had been due to marry another woman, Eleanor Talbot, before he entered into marriage with Elizabeth Woodville. This claim was only made after all these parties had died. The act was repealed shortly after Henry VII became king. Edward also had many mistresses and had several illegitimate children. ### A series of conflicts Elizabeth\'s family had little land, which was where real power came from, but Warwick did not like the influence they now had. Warwick allied himself with Edward\'s younger brother George, Duke of Clarence, and led an army against Edward. The main part of the king\'s army (without Edward) was defeated at the Battle of Edgecote Moor, and Edward was later captured at Olney. Warwick tried to rule in Edward\'s name, but the nobles, many of whom owed their position to the king, were not happy. A rebellion forced Warwick to free Edward, who tried to make peace with Warwick and Clarence. This did not work and they rebelled again in 1470, after which Warwick and Clarence were forced to flee to France. There, they allied with Henry VI\'s wife, Margaret, and Warwick agreed to restore Henry VI to the throne in return for French support. They invaded in 1470. This time, Edward was forced to flee after Warwick\'s brother switched to the Lancastrian side, making Edward\'s military position too weak, and Henry VI was king once more. Edward fled to Burgundy. The rulers of Burgundy were his brother-in-law Charles, Duke of Burgundy, and his sister Margaret of Burgundy. After France declared war on Burgundy, Charles helped Edward to raise an army to win back his kingdom. When he returned to England with a small force he avoided capture by saying that he only wished to reclaim his dukedom. This is similar to the claim Henry Bolingbroke made seventy years before. The city of York, however, closed its gates to him, but as he marched southwards he began to gather support, and Clarence reunited with him. Edward defeated Warwick at the Battle of Barnet. With Warwick dead, he ended the remaining Lancastrian resistance at the Battle of Tewkesbury in 1471. The Lancastrian heir, Edward of Westminster, Prince of Wales, was killed either on the battlefield or shortly afterwards. A few days later, on the night that Edward re-entered London, Henry VI, who held prisoner, was murdered to make sure there was no remaining Lancastrian opposition. Edward did not face any further rebellions after his restoration. The only rival left was Henry Tudor, who was living in exile. Edward declared war on France in 1475, which ended with the Treaty of Picquigny, under which he was immediately paid 75,000 crowns, and then received a yearly pension of 50,000 crowns. Edward backed an attempt by Alexander Stewart, 1st Duke of Albany, brother of the Scottish king, James III, to take the throne in 1482. Although Edinburgh and James III were both captured, the Duke of Albany went back on his agreements with Edward, and the English forces were pulled back. England did, however, recover the border town of Berwick-upon-Tweed. ### Death Edward fell ill at Easter 1483, and made some changes to his will, the most important being his naming of his brother, the Duke of Gloucester, as Protector after his death. He died on 9 April 1483 and is buried in St George\'s Chapel at Windsor Castle. He was succeeded by his twelve-year-old son, Edward. Edward IV\'s daughter, Elizabeth of York, later became King Henry VII\'s queen. ### Was Edward illegitimate? There have been many rumours that Edward IV was himself illegitimate, in which case he should never have been king. In his time, it was noted that Edward IV did not look much like his father. Before he became king in 1483, Richard III himself declared that Edward was illegitimate, and parliament even considered the matter. William Shakespeare, in his play, *Richard III*, which was written over a hundred years later, also referred to the claim. To this day it is not known whether these rumours were true. ## Edward V (1483) !King Edward V and the Duke of York in the Tower of London{width="150"} **Edward V** was born in sanctuary within Westminster Abbey on 4 November 1470, while his mother was taking refuge from the Lancastrians who were then in charge of the kingdom while his father, the Yorkist King Edward IV of England, was out of power. After his father returned to the throne, he was made Prince of Wales in June 1471 and appeared with his parents on state occasions. Edward IV had set up a Council of Wales and the Marches, and sent his son to Ludlow Castle to be its president. The prince was at Ludlow when news came of his father\'s sudden death. Therefore Edward became king on 9 April 1483, aged only 12. His father\'s brother Richard, Duke of Gloucester, was given the role of Protector to his young nephews, Edward V and Richard, Duke of York. He caught up with Edward on his journey from Ludlow and took the princes to London. Less than three months later, Richard took the throne himself after parliament declared Edward to be illegitimate. After the two boys went to the Tower of London, they were never seen in public again. What happened to them is one of the great mysteries of history, and many books have been written on the subject. It is believed that they were killed, and the usual suspects are: their uncle, King Richard; Henry Stafford, 2nd Duke of Buckingham; and Henry Tudor, who later defeated Richard and took the throne as Henry VII. In 1674 some workmen remodeling the Tower of London dug up a box that had two small human skeletons in it. They threw them on a rubbish heap, but some days or weeks later someone decided they might be the bones of the two princes, so they gathered them up and put some of them in an urn that was buried at Westminster Abbey. In 1933 the bones were taken out and examined and then replaced in the urn. The experts who examined them could not agree on what age the children would have been when they died or even whether they were boys or girls. ## Richard III (1483-1485) !Richard III{width="150"} **Richard III** was born at Fotheringay Castle on 2 October 1452. He was the fourth surviving son of Richard Plantagenet, the 3rd Duke of York, who was a strong claimant to the throne of King Henry VI. He has been portrayed as having a withered arm, limp and a crooked back, but this is most probably an invention from many years later. Richard was King of England from 1483, when he effectively deposed his nephew, Edward V. A rebellion rose against Richard later that year, and he died at the Battle of Bosworth Field in 1485. He is the last English king to die in battle, and he was succeeded by the winner of the battle, Henry Tudor. ### Marriage and children Richard spent much of his childhood at Middleham Castle in Wensleydale, under the care of his uncle, Richard Neville, the 16th Earl of Warwick (the \"Kingmaker\"), as Richard\'s father died when he was young. Following the Yorkist victory over the Lancastrians at the Battle of Tewkesbury, Richard married the widowed Anne Neville, younger daughter of the now dead 16th Earl of Warwick on 12 July 1472. Anne\'s first husband had been Edward of Westminster, son of Henry VI. Richard and Anne had one son, Edward Plantagenet, who was born in 1473. He died soon after being made Prince of Wales in 1483. Richard also had a number of illegitimate children. ### Reign of Edward IV During the reign of his brother, King Edward IV, Richard was a loyal and skilful military commander. He was rewarded with large estates in Northern England, and given the title Duke of Gloucester and the position of Governor of the North, becoming the richest and most powerful noble in England. Richard continued to control the north of England until Edward\'s death. In 1482 Richard recaptured Berwick-upon-Tweed from the Scots, and was noted as being fair and just, making gifts to universities and the Church. ### Death and legacy On 22 June 1483, outside St Paul\'s Cathedral, a statement was read out on behalf of Richard declaring for the first time that he was taking the throne for himself. On 6 July 1483, Richard was crowned at Westminster Abbey. Except for three earls not old enough to be there and a few lesser nobles, the entire peerage attended his coronation. Richard was known as a devout man and an efficient administrator. However, he was a Yorkist and heirless, and had ruthlessly removed many of his enemies but some, led by Henry Tudor, remained. Richard\'s enemies united against him and he fought them at the Battle of Bosworth Field on 22 August 1485, where he was killed. Henry Tudor succeeded Richard to become King Henry VII. Richard was buried at Greyfriars Church, Leicester, but his body was lost during the later Dissolution of the Monasteries. There is currently a memorial plaque on the site of the Cathedral where he may have once been buried. Since his death, Richard III has become one of England\'s most controversial kings. He was portrayed as a bad king by historians of the House of Tudor. He has now largely lost his notoriety, except in relation to the mystery surrounding the two Princes in the Tower. ## References
# Wikijunior:Kings and Queens of England/The Stuarts ## James I (1603-1625) !James I{width="150"} James I was born at Edinburgh Castle on 19 June 1566. James was the only child of Mary, Queen of Scots and her second husband, Lord Darnley. James was a direct descendant of Henry VII through his great-grandmother Margaret Tudor, sister of Henry VIII. He ruled in Scotland as James VI from 24 July 1567 until his death on 27 March 1625. He was also King of England and King of Ireland as James I from 24 March 1603 until his death. He was the first monarch of England from the House of Stuart. James was a successful monarch in Scotland, but he was an unsuccessful monarch in England. He was unable to deal with a hostile Parliament, and the refusal by the House of Commons to levy sufficiently high taxes crippled the royal finances. However, James is considered to have been one of the most intellectual British monarchs. Under him, much of the cultural flourishing of Elizabethan England continued; science, literature and art, contributed by men such as Sir Francis Bacon and William Shakespeare grew by leaps. ### Before becoming King of England In June 1567, Protestant rebels arrested James\'s mother, Mary, Queen of Scots, and imprisoned her. Mary was forced to abdicate the throne on 24 July, giving it to James, then only thirteen months old. He was brought up as a member of the Protestant Church of Scotland. During James VI\'s early reign, power was held by a series of regents, with James taking power himself in 1581, though he did not rule by himself, relying instead on the advice of his closest courtiers. He carried on ruling as King of Scotland, and then, on the death of Queen Elizabeth of England in 1603, an English Accession Council met and proclaimed James King of England. However, Scotland and England remained separate states - it was not until 1707 that the Acts of Union merged the two nations to create a new state, the Kingdom of Great Britain. ### Early reign in England James is noted for creating many new lords. In total, sixty-two people were raised to the English Peerage by James. Elizabeth had only created eight new peers during her 45-year reign. Upon his arrival in London, James was almost immediately faced by religious conflicts in England. He was presented with a petition from Puritans requesting further Anglican Church reform. He accepted the invitation to a conference in Hampton Court, which was subsequently delayed due to the Plague. In 1604, at the Hampton Court Conference, James was unwilling to agree to most of their demands. He did, however, agree to fulfill one request by authorizing an official translation of the Bible, which came to be known as the King James Version. In 1605, a group of Catholic extremists led by Robert Catesby developed a plan, known as the Gunpowder Plot, to cause an explosion in the chamber of the House of Lords, where the King and members of both Houses of Parliament would be gathered for the State Opening of Parliament. The conspirators sought to replace James with his daughter, Elizabeth, who, they hoped, could be forced to convert to Catholicism. One of the conspirators, however, leaked information regarding the plot, which was then foiled. Terrified, James refused to leave his residence for many days. Guy Fawkes, who was to be the one lighting the gunpowder, was tortured on the rack until he revealed the identities of the other conspirators, all of whom were executed or killed during capture. Dolls of Guy Fawkes are still burned each 5 November, which is known as Guy Fawkes, or bonfire, Night, to commemorate the plot. ### Conflict with Parliament and death Following the dissolution of the Addled Parliament, James ruled without a Parliament for seven years. Faced with financial difficulties due to the failure of Parliament to approve new taxes, James sought to enter into a profitable alliance with Spain by marrying his eldest surviving son, Charles, to the daughter of the King of Spain. The proposed alliance with a Roman Catholic kingdom was not well received in Protestant England. James\'s unpopularity was increased by the execution of Sir Walter Raleigh. James lapsed into senility during the last year of his reign. Real power passed to his son, Charles, and to the Duke of Buckingham, although James kept enough power to ensure that a new war with Spain did not occur while he was King. James died at Theobalds House in 1625 of \'tertian ague\' (fever one day in every three), probably brought upon by kidney failure and stroke. He was buried in the Henry VII Lady Chapel in Westminster Abbey. Charles succeeded him as Charles I. ### Issue James\'s children included Henry Frederick, Prince of Wales (who died aged 18 in 1612), Elizabeth, Margaret Stuart (who died in infancy), Charles, Mary and two more children who died in infancy (Robert and Sophia). ## Charles I (1625-1649) !Charles I{width="160"} Charles I was born at Dunfermline Palace on 19 November 1600. He was the second son of James I and Anne of Denmark. He was King of England, Scotland and Ireland from 27 March 1625 until his execution in 1649. He famously engaged in a struggle for power with the Parliament of England. He was a supporter of the Divine Right of Kings, and many in England feared that he was attempting to gain absolute power. There was widespread opposition to many of his actions, especially the levying of taxes without Parliament\'s consent. Religious conflicts continued throughout Charles\'s reign. He selected his Catholic wife, Henrietta Maria, over the objections of Parliament and public opinion. The last years of Charles\' reign were marked by the English Civil War, in which he was opposed by the forces of Parliament, who challenged his attempts to increase his own power, and by Puritans, who were hostile to his religious policies. The war ended in defeat for Charles, who was subsequently tried, convicted and executed for high treason. The monarchy was overthrown, and a commonwealth was established. ### Early life and reign Charles was not as well-regarded as his elder brother, Henry. However, when his elder brother died of typhoid in 1612, Charles became heir to the throne and was later made Prince of Wales. Charles ascended the throne in March 1625 and on 1 May of that year married to Henrietta Maria, who was nine years his junior. She was a sister of King Louis XIII of France. His first Parliament, which he opened in May, was opposed to his marriage to Henrietta Maria, a Roman Catholic, because it feared that Charles would lift restrictions on Roman Catholics and undermine the official establishment of Protestantism. Although he agreed with Parliament that he would not relax restrictions relating to recusants, he promised to do exactly that in a secret marriage treaty with Louis XIII. Charles and his wife had nine children, with three sons and three daughters surviving infancy. ### Personal Rule In January 1629, Charles opened the second session of the Parliament which had been prorogued in June 1628. He hoped that, with the Duke of Buckingham gone, Parliament, which had been refusing to let him raise taxes, would finally cooperate with him and grant him further subsidies. Instead, members of the House of Commons began to voice their opposition to the levying of tonnage and poundage without parliamentary consent. When he requested a parliamentary adjournment in March, members held the Speaker down in his chair whilst three resolutions against Charles were read aloud. The last of these resolutions declared that anyone who paid tonnage or poundage not authorized by Parliament would \"be reputed a betrayer of the liberties of England, and an enemy to the same\". Though the resolution was not formally passed, many members declared their approval. Afterward, when the Commons passed further measures, Charles commanded the dissolution of Parliament. Charles decided that he could not rely on Parliament for further monetary aid. Immediately, he made peace with France and Spain. The following eleven years, during which Charles ruled without a Parliament, have been known as the Eleven Years Tyranny. In the meantime Charles still had to get funds to maintain his treasury. Relying on an all but forgotten feudal statute passed in 1278, requiring anyone who earned £40 or more each year to present himself at the King\'s coronation so that he may join the royal army as a knight, Charles fined everyone who failed to attend his coronation in 1626. He reintroduced the feudal tax known as ship money, which was even more unpopular. A writ issued in 1634 ordered the collection of ship money in peacetime, although laws passed when Edward I and Edward III were on the throne said it should not be collected in peacetime. This action of demanding ship money in peacetime led to a rebellion which forced him to call parliament into session by 1640. ### Short and Long Parliaments A dispute with the Churches in Scotland meant that Charles needed more money. He therefore had to end his personal rule and recall Parliament in April 1640. Although Charles offered to repeal ship money, the House of Commons demanded the discussion of various abuses of power during the period of Charles\'s personal rule. Parliament refused to help Charles and it was dissolved in May 1640, less than a month after it assembled. It became known as the Short Parliament. Charles still tried to defeat the Scots, but failed. The peace treaty he agreed required the King to pay the expenses of the Scottish army he had just fought. Charles took the unusual step of summoning the *magnum concilium*, the ancient council of all the Peers of the Realm, who were considered the King\'s hereditary counsellors. The *magnum concilium* had not been summoned in centuries, and it has not been summoned since Charles\'s reign. On the advice of the peers, Charles summoned another Parliament, which became known as the Long Parliament. The Long Parliament assembled in November 1640 and proved just as difficult to negotiate with as the Short Parliament. To prevent the King from dissolving it at will, Parliament passed the Triennial Act, which required that Parliament was to be summoned at least once every three years. In May 1641, he assented to an even more far-reaching Act, which provided that Parliament could not be dissolved without its own consent. Charles was forced into one concession after another. Ship money, fines in destraint of knighthood and forced loans were declared unlawful, and the hated Courts of Star Chamber and High Commission were abolished. Although he made several important concessions, Charles improved his own military position by securing the favour of the Scots. He finally agreed to the official establishment of Presbyterianism, and in return got considerable anti-parliamentary support. The House of Commons then threatened to impeach Charles\' Catholic Queen, Henrietta Maria, finally leading the King to take desperate action. His wife persuaded him to arrest the five members of the House of Commons who led the anti-Stuart faction on charges of high treason, but, when the King had made his decision, she made the mistake of telling a friend who, in turn, told Parliament. Charles entered the House of Commons with an armed force on 4 January 1642, but found that his opponents had already escaped. Many in Parliament thought Charles\'s actions outrageous, but others had similar sentiments about the actions of Parliament itself. Several members of the House of Commons left to join the royalist party, leaving the King\'s opponents with a majority. It was no longer safe for Charles to be in London, and he went north to raise an army against Parliament. The Queen, at the same time, went abroad to raise money to pay for it. ### Civil war The English Civil War had not yet started, but both sides began to arm. Charles raised the royal standard in Nottingham on 22 August 1642. He then set up his court at Oxford, from where he controlled roughly the north and west of England, Parliament remaining in control of London and the south and east. The Civil War started on 25 October 1642 with the inconclusive Battle of Edgehill and continued indecisively through 1643 and 1644, until the Battle of Naseby tipped the military balance decisively in favour of Parliament. There followed a great number of defeats for the Royalists, and then the Siege of Oxford, from which Charles escaped in April 1646. He put himself into the hands of the Scottish Presbyterian army at Newark, and was taken to nearby Southwell while his \"hosts\" decided what to do with him. The Presbyterians finally arrived at an agreement with Parliament and delivered Charles to them in 1647. He was imprisoned at Holdenby House in Northamptonshire, but was soon transferred to a number of different locations. ### Trial and execution Charles was finally moved to Windsor Castle and then St James\'s Palace. In January 1649, the House of Commons without the assent of either the Sovereign or the House of Lords---passed an Act of Parliament creating a court for Charles\'s trial. The High Court of Justice established by the Act consisted of 135 Commissioners (all firm Parliamentarians). The King\'s trial (on charges of high treason and \"other high crimes\") began on 2 January, but Charles refused to enter a plea, claiming that no court had jurisdiction over a monarch. It was then normal practice to take a refusal to plead as an admission of guilt, which meant that the prosecution could not call witnesses to its case. Fifty-nine of the Commissioners signed Charles\'s death warrant on 29 January, 1649. After the ruling, he was led from St. James\'s Palace, where he was confined, to the Palace of Whitehall, where an execution scaffold had been erected in front of the Banqueting House. Charles was beheaded on 30 January, 1649. One of the revolutionary leaders, Oliver Cromwell, allowed the King\'s head to be sewn back on his body so the family could pay its respects. Charles was buried in private and at night on 7 February 1649, in the Henry VIII vault inside St George\'s Chapel in Windsor Castle. Charles was father to a total of nine legitimate children, two of whom would eventually succeed him as king. Several other children died in childhood. ## Interregnum (1649-1660) The English Interregnum was the period of parliamentary and military rule after the English Civil War, between the execution of Charles I in 1649 and the restoration of Charles II in 1660. This era in English history can be divided into four periods: 1. The first period of the Commonwealth of England from 1649 until 1653 2. The Protectorate under Oliver Cromwell from 1653 to 1659 3. The Protectorate under Richard Cromwell in 1659 4. The second period of the Commonwealth of England from 1659 until 1660 ### Life during the Interregnum Four years after Charles I\'s execution, Oliver Cromwell was offered the Crown. But he refused and chose instead to rule as Lord Protector. Oliver Cromwell was a Puritan and during the Interregnum, he imposed a very strict form of Christianity upon the country. Cromwell granted religious freedom otherwise previously unknown in England, but other forms of expression were suddenly limited (for instance, theatre, which had thrived under the Stuart kings and Elizabeth I, was banned). Cromwell also imposed his own personal vision of Christianity on the masses, with feasts on days of fast disallowed and work on Sundays subject to fine. Richard Cromwell was the successor to his father. But he gave up his position as Lord Protector with little hesitation, resigning or \"abdicating\" after a demand by the Rump Parliament. This was the beginning of a short period of restoration of the Commonwealth of England, and Charles I\'s son, also called Charles, was soon invited back as king. ## Charles II (1660-1685) !Charles II{width="160"} Charles II was born in St James\'s Palace on 29 May 1630. Charles was the eldest surviving son of Charles I and Henrietta Maria of France. He was the King of Scots from 30 January 1649 and King of England and Ireland from 29 May 1660 until his death on 6 February 1685. Unlike his father Charles I, Charles II was skilled at managing the Parliament of England, so much so that Charles is still considered one of England\'s greatest kings. It was during his reign that the Whig and Tory political parties developed. He famously fathered numerous illegitimate children, of whom he acknowledged fourteen. Known as the \"Merry Monarch\", Charles was a patron of the arts. ### Restoration After the death of Oliver Cromwell in 1658, Charles\'s chances of regaining the Crown seemed slim. Oliver Cromwell was succeeded as Lord Protector by his son, Richard Cromwell. However, the new Lord Protector abdicated in 1659. The Protectorate of England was abolished, and the Commonwealth of England established. During the civil and military unrest which followed, George Monck, the Governor of Scotland, was concerned that the nation would descend into anarchy and sought to restore the monarchy. Monck and his army marched into the City of London and forced the Long Parliament to dissolve itself. For the first time in almost twenty years, the members of Parliament faced a general election. A Royalist House of Commons was elected. The Convention Parliament, soon after it assembled on 25 April 1660, heard about the Declaration of Breda, in which Charles agreed, amongst other things, to pardon many of his father\'s enemies. It subsequently declared that Charles II had been the lawful Sovereign since Charles I\'s execution in 1649. Charles set out for England, arriving in Dover on 23 May 1660 and reaching London on 29 May. Although Charles granted amnesty to Cromwell\'s supporters in the *Act of Indemnity and Oblivion*, he went back on his pardon of the commissioners and officials involved in his father\'s trial and execution. Many among those who signed Charles I\'s death warrant were executed in 1660 in the most gruesome fashion: they were hanged, drawn and quartered. Others were given life imprisonment. The body of Oliver Cromwell was also \"executed\". The Convention Parliament was dissolved in December 1660. Shortly after Charles\'s coronation at Westminster Abbey on 23 April 1661, the second Parliament of the reign, the Cavalier Parliament, met. As the Cavalier Parliament was overwhelmingly Royalist, Charles saw no reason to dissolve it and force another general election for seventeen years. ### Foreign policy In 1662 Charles married a Portuguese princess, Catherine of Braganza, who brought him the territories of Bombay and Tangier as dowry. During the same year, however, he sold Dunkirk, a much more valuable strategic outpost to his cousin King Louis XIV of France of France for £40,000. In 1668, England allied itself with Sweden, and with its former enemy the Netherlands, in order to oppose Louis XIV in the War of Devolution. Louis was forced to make peace with the Triple Alliance, but he continued to maintain his aggressive intentions. In 1670, Charles, seeking to solve his financial troubles, agreed to the Treaty of Dover, under which Louis XIV would pay him £200,000 each year. Meanwhile, around 1670, Charles granted the British East India Company the rights to autonomous territorial acquisitions, to mint money, to command fortresses and troops, to form alliances, to make war and peace, and to exercise both civil and criminal jurisdiction over the acquired areas in India. Earlier in 1668 he leased the islands of Bombay for a paltry sum of ten pounds sterling paid in gold. ### Great Plague and Fire In 1665, Charles II was faced with a great health crisis: an outbreak of Bubonic Plague in London commonly referred to as the Great Plague of London. The death toll at one point reached 7000 per week. Charles, his family and court fled from London in July 1665 to Oxford. Various attempts at containing the disease by London public health officials all fell in vain and the disease continued to spread rapidly. On 2 September 1666 came the Great Fire of London. Although it ended the Great Plague by burning of plague-carrying rats and fleas, the fire consumed about 13,200 houses and 87 churches, including the original St. Paul\'s Cathedral. ### Conflict with Parliament Charles\'s wife Queen Catherine was unable to produce an heir. Charles\'s heir was therefore his unpopular Roman Catholic brother, James. In 1678, Titus Oates, a former Anglican cleric, falsely warned of a \"Popish Plot\" to kill the king and replace him with James. Charles did not believe the story, but ordered his chief minister to investigate. He, however, was an anti-Catholic, and encouraged Oates to make his accusations public. The people were seized with an anti-Catholic hysteria; judges and juries across the land condemned the supposed conspirators; numerous innocent individuals were executed. Later in 1678, however, the chief minister was impeached by the House of Commons on the charge of high treason. To save Lord Danby from the impeachment trial in the House of Lords, Charles dissolved the Cavalier Parliament in January 1679. A new Parliament, which met in March of the same year, was quite hostile to the king, and this led to the chief minister being forced to resign and being held prisoner in the Tower of London. ### Later years The Parliament of 1679 was elected at a time when there were strong anti-Catholic sentiments. It was opposed to the prospect of a Catholic monarch. An Exclusion Bill, which sought to exclude James from the line of succession, was introduced. The \"Abhorrers\", those who opposed the Exclusion Bill, would develop into the Tory Party, whilst the \"Petitioners\", those who supported the Exclusion Bill, became the Whig Party. Fearing that the Exclusion Bill would be passed, Charles dissolved Parliament in December 1679. Two further Parliaments were called in Charles\'s reign (one in 1680, the other in 1681), but both were dissolved because they sought to pass the Exclusion Bill. During the 1680s, however, popular support for the Exclusion Bill began to dissolve, and Charles experienced a nationwide surge of loyalty. For the remainder of his reign, Charles ruled as an absolute monarch, without a Parliament. In 1685 Charles died suddenly. When he knew he was dying and in great secrecy, a priest was summoned to his bedside. Charles was admitted into the Catholic Church and received the last rites. He was buried in Westminster Abbey. He was succeeded by his brother, who became James II in England and Ireland, and James VII in Scotland. ## James II (1685-1688) !James II{width="160"} James II of England and VII of Scotland was born at St James\'s Palace on 14 October 1633. He was the second surviving son of Charles I and Henrietta Maria of France. He became King of England, King of Scots and King of Ireland on 6 February 1685. He was the last Roman Catholic monarch to reign over England, Scotland and Ireland. Some of his subjects distrusted his religious policies and alleged despotism, leading a group of them to depose him in the Glorious Revolution. He was replaced not by his Roman Catholic son, James Francis Edward, but by his Protestant daughter and son-in-law, Mary II and William III, who became joint rulers in 1689. The belief that James remained the legitimate ruler became known as Jacobitism (from *Jacobus*, the Latin for James). However, James did not try to return to the throne, instead living the rest of his life under the protection of King Louis XIV of France. His son James Francis Edward Stuart and his grandson Charles Edward Stuart (*Bonnie Prince Charlie*) attempted to restore the Jacobite line after James\'s death on 16 September 1701, but failed. ### Early life Like his brother, James sought refuge in France during the Interregnum, and he served in the French army. In 1656, when his brother, Charles, entered into an alliance with Spain, an enemy of France, he joined the Spanish army. Both armies praised James\'s abilities. In 1660, Charles II was restored to the English Throne, and James returned to England with him. Though he was the heir, it seemed unlikely then that he would inherit the Crown, as it was thought that Charles would have legitimate children. In September 1660, James married Lady Anne Hyde, the daughter of Charles\'s then chief minister, Edward Hyde, 1st Earl of Clarendon. ### Religion James was admitted to the Roman Catholic Church in 1668 or 1669. His Protestant enemies in the Parliament of England then passed the Test Act, which made all civil and military officials swear an oath against certain practices of the Roman Catholic Church and receive communion in the Church of England. James refused to do this and gave up his post of Lord High Admiral as a result. Charles II opposed James\'s conversion, and ordered James\'s children be raised as Protestants, but in 1673, he allowed James (whose first wife had died in 1671) to marry the Catholic Mary of Modena. In 1677, James allowed his daughter, Mary, to marry the Protestant Prince of Orange, William III, who was also his nephew. However, fears of a Catholic monarch remained, and got greater as Charles II\'s wife continued to fail to provide an heir. ### Reign and the Glorious Revolution Charles died without legitimate offspring in 1685, and James became king. At first, there was little opposition to him and many Anglicans supported him as the legitimate monarch. The new Parliament which assembled in May 1685 seemed favourable to James, agreeing to grant him a large income. James, however, faced the Monmouth Rebellion, which was led by Charles II\'s illegitimate son, the Duke of Monmouth. James Scott, 1st Duke of Monmouth declared himself King on 20 June 1685, but was defeated at the Battle of Sedgemoor. Monmouth was executed at the Tower of London soon after. Despite the lack of popular support for Monmouth, James began to distrust his subjects. His judges, most notably Judge Jeffreys (the \"Hanging Judge\"), punished the rebels brutally. Judge Jeffreys\' Bloody Assizes led the people to see their King as a cruel and barbarous ruler. To protect himself from further rebellions, James sought to establish a large standing army. By putting Roman Catholics in charge of several regiments, the King was drawn into a conflict with Parliament. Parliament was prorogued in November 1685, never to meet again during James\'s reign. Religious tension intensified in 1686. In the Declaration of Indulgence in 1687, he suspended laws punishing Roman Catholics and other religious dissenters. In April 1688, James re-issued the Declaration of Indulgence, and ordered Anglican clergymen to read it in their churches. When the Archbishop of Canterbury and six other bishops petitioned for a change in the King\'s religious policies, they were arrested and tried for seditious libel, but were acquitted. Public alarm increased with the birth of a Catholic son and heir, James Francis Edward, to Queen Mary in June, 1688. Several leading Protestants then entered into negotiations with William, Prince of Orange, who was James\'s son-in-law, for him to invade and become king. By September, it had become clear that William was looking to invade. James believed his army could fight them off, but when William landed on 5 November 1688, all of the King\'s Protestant officers went over to William\'s side. On 11 December, James attempted to flee to France. He was caught in Kent, but allowed to escape to France on 23 December. When James left, no Parliament was in session, so William convened a Convention Parliament. The Convention declared on 12 February 1689 that James\'s attempt to flee on 11 December meant that he had abdicated and that the throne had then become vacant (instead of passing to James II\'s son, James Francis Edward). James\'s daughter Mary was declared Queen. She was to rule jointly with her husband William III. The Scottish Estates followed suit on 11 April. William and Mary then granted their assent to the Bill of Rights. This confirmed that William III and Mary II were to be King and Queen. It also charged James II with abusing his power by suspending the Test Acts, the prosecuting of the Seven Bishops for petitioning the Crown, establishing a standing army and imposing cruel punishments. The Act also set out who would be heirs to the Crown. First were any children of William and Mary, to be followed by the Princess Anne and her children, and finally by the children of William by any subsequent marriage. ### Later years and legacy With a French army on his side, James landed in Ireland in March 1689. The Irish Parliament did not follow the example of the English Parliament and instead declared that James remained King. He was, however, defeated at the Battle of the Boyne on 1 July 1690. He fled back to France after the defeat departing. In France, James was allowed to live in a royal castle. An attempt was made to restore him to the throne by killing William III in 1696, but the plot failed. Louis XIV\'s offer to have James elected King of Poland was rejected, after which Louis no longer helped James. He died in 1701 at Saint-Germain-en-Laye, where he was buried. The son of James II, James Francis Edward Stuart (known to his supporters as \"James III and VIII\" and to his opponents as the \"Old Pretender\"), took up the Jacobite cause. He led a rising in Scotland in 1715 shortly after George I became king, but was defeated. Further risings were also defeated. After the rising of 1745 led by Charles Edward Stuart, no serious attempt to restore the Stuart heir has been made. James Francis Edward died in 1766, when he was succeeded by his eldest son, Charles Edward Stuart (known to his supporters as \"Charles III\" and to his opponents as the \"Young Pretender\"). Charles in turn was succeeded by his younger brother Henry Benedict Stuart, a cardinal of the Catholic Church. Henry was the last of James II\'s legitimate descendants. ### Children James had eight children by Anne Hyde, of whom only two, Mary and Anne, survived infancy. They became the next two Queens. By Mary of Modena he had six children, two of whom survived infancy. The most famous of his children by Mary of Modena was James Franci Edward Stuart. He also had a number of illegitimate children. ## William III (1689-1702) and Mary II (1689-1694) After the Glorious Revolution, William III and his wife, Mary II, became joint rulers. ### William !William III{width="200"} William was born in The Hague in the Netherlands on 14 November 1650. He was the son of William II, Prince of Orange, and Mary Stuart. He was Dutch aristocrat and a Protestant Prince of Orange from his birth. He was King William III of England and of Ireland from 13 February 1689, and William II, King of Scots from 11 April 1689 in each case until his death on 8 March 1702. Eight days before he was born, his father died from battle wounds, and so William became the Sovereign Prince of Orange at the moment of his birth. On 23 December 1660, when William was just ten years old, his mother died of smallpox while visiting her brother, King Charles II in England. In her will, Mary made Charles William\'s legal guardian. Charles passed on this responsibility to William\'s paternal grandmother, the Princess Dowager Amalia, with the understanding that Charles\'s advice would be sought whenever it was needed. In 1666, when William was sixteen, the States General of the United Provinces of the Netherlands officially made him a ward of the government, or as William himself called it, a \"Child of State\". This was one in order to prepare William for a role in the nation\'s government. When his time as the government\'s ward ended three years later, William returned to private life. ### Mary !Mary II{width="150"} Mary II was born in London on 30 April 1662. She was the eldest daughter of James II and his first wife, Lady Anne Hyde. She reigned as Queen of England and Ireland from 13 February 1689 until her death on 28 December 1694, and as Queen of Scotland from 11 April 1689 until her death. Mary came to the throne after the Glorious Revolution. Mary reigned jointly with her husband and first cousin, William III, who became the sole ruler upon her death. Mary, although a sovereign in her own right, did not wield power during most of her reign. She did, however, govern the realm when her husband was abroad fighting wars. James II converted to Roman Catholicism in 1668 or 1669, but Mary and Anne were order by Charles II to have a Protestant upbringing, pursuant to the command of Charles II. At the age of fifteen, Princess Mary became engaged to the Protestant Stadtholder and Prince of Orange, William. William was the son of her aunt and Prince William II of Nassau. They married in London on 4 November 1677. Mary went to the Netherlands, where she lived with her husband. She did not enjoy a happy marriage, with her three pregnancies ended in miscarriage or stillbirth. She became popular with the Dutch people, but her husband neglected or even mistreated her and had an affair with one of Mary\'s ladies-in-waiting. ### Reign Although most in England accepted William as Sovereign, he faced considerable opposition in Scotland and Ireland. The Scottish Jacobites, who believed that James II remained the legitimate monarch, won a stunning victory on 27 July 1689 at the Battle of Killiecrankie, but were later beaten within a month. William\'s reputation suffered after the Massacre of Glencoe in 1692, when almost one hundred Scots were murdered for not properly pledging their allegiance to the new King and Queen. Accepting public opinion, William sacked those responsible for the massacre, though they still remained in his favour. In Ireland, where the French aided the rebels, fighting continued for much longer, although James II fled the island after the Battle of the Boyne in 1690. This Battle is still commemorated each year by the Protestants in Northern Ireland. After the Anglo-Dutch Navy defeated a French fleet at in 1692, the naval supremacy of the English became apparent, and Ireland was conquered shortly after. From 1690 onwards, William often remained absent from England. Whilst her husband was away, Mary ruled. She was a firm ruler, and even ordered the arrest of her own uncle for plotting to restore James II to the throne. In 1692, she dismissed and imprisoned the influential John Churchill, 1st Earl of Marlborough on similar charges. In this case the dismissal reduced her popularity and harmed her relationship with her sister Anne. When William was in England, Mary stepped aside from politics. She did, however, get involved in the affairs of the Church, in particular with Church appointments. Mary died of smallpox in 1694. After Mary II\'s death, William III continued to rule as king. Although he had previously mistreated his wife and kept mistresses, William deeply mourned his wife\'s death. Although he was brought up as a Calvinist, he converted to Anglicanism, but his popularity fell greatly during his reign as a sole Sovereign. ### William as sole ruler William, like many other European rulers, became concerned about who would succeed to the throne of Spain, which brought with it vast territories in Italy, the Low Countries and the New World. The question became important as The King of Spain, Charles II, was an invalid with no prospect of having children, and had amongst his closest relatives Louis XIV, the King of France, and Leopold I, the Holy Roman Emperor. William wanted to stop either of these inheriting all Spanish lands. William and Louis XIV agreed to the First Partition Treaty, which provided for the division of the Spanish Empire: Duke Joseph Ferdinand of Bavaria (whom William himself chose) would obtain Spain, while France and the Holy Roman Emperor would divide the remaining territories between them. The Spaniards, however, wanted to keep the Spanish territories united. After Joseph Ferdinand died of smallpox, William and Louis In 1700, the two rulers agreed to the Second Partition Treaty in 1700, under which the territories in Italy would pass to a son of the King of France, and the other Spanish territories would be inherited by a son of the Holy Roman Emperor. This infuriated both the Spanish, who wanted the empire intact, and the Holy Roman Emperor, who wanted the Italian territories. Unexpectedly, King Charles II of Spain changed his will as he lay dying in late 1700. He left all Spanish territories to Philip, a grandson of Louis. The French ignored the Second Partition Treaty and claimed the entire Spanish inheritance. Louis also angered William by recognising James Francis Edward Stuart, the son of the former King James II, who had died in 1701, as King of England. The subsequent conflict, known as the War of the Spanish Succession, continued until 1713. Princess Anne\'s last surviving child, William, Duke of Gloucester, died in July 1700, and, as it was clear that William III would have no more children, Parliament passed the Act of Settlement in 1701, which provided that the Crown would go to the nearest Protestant relative, Sophia, Electress of Hanover and her Protestant heirs when William III died. ### William\'s death In 1702, William died of pneumonia, a complication from a broken collarbone, resulting from a fall off his horse. It was believed by some that his horse had stumbled into a mole\'s burrow, and as a result many Jacobites toasted \"the little gentleman in the black velvet waistcoat\". William was buried in Westminster Abbey alongside his wife. He was succeeded by Queen Anne. ## Anne (1702-1714) !Anne{width="150"} Anne was born in St James\'s Palace on 6 February 1665. She was the second daughter of James, who went on to become James II, and his first wife, Lady Anne Hyde. She was Queen of England, Scotland and Ireland from 8 March 1702 until her death on 1 August 1714. Anne was the last monarch of the House of Stuart. She was succeeded by a distant cousin, George I. Anne\'s reign saw the two party political system develop. ### Early life On 28 July 1683, Anne married the Protestant Prince George of Denmark, brother of the Danish King Christian V. The union was unpopular because Denmark was pro-France union, but it was a happy one for Anne and George. Sarah Churchill became Anne\'s lady of the bedchamber, and, by the latter\'s desire to mark their mutual intimacy and affection, all deference due to her rank was abandoned and the two ladies called each other Mrs Morley and Mrs Freeman. Sarah remained Anne\'s closest friend, and later married John Churchill, the 1st Duke of Marlborough. However, they had a falling out and Sarah was banned from court during the War of the Spanish Succession, when her husband was leading the English armies in the War. By 1700, Anne had been pregnant at least eighteen times. Thirteen times, she miscarried or gave birth to stillborn children. Of the remaining five children, four died before reaching the age of two years. Her only son to survive infancy, William, Duke of Gloucester, died at the age of eleven on 29 July 1700. William and Mary did not have any children, and therefore Anne was the only individual remaining in the line of succession established by the Bill of Rights. If the line ended, then the deposed King James may have reclaimed the Throne. To stop a Roman Catholic from becoming king, Parliament enacted the Act of Settlement 1701, which provided that the Crown would go to Sophia, Electress of Hanover, and her descendants, who descended from James I of England through Elizabeth of Bohemia. ### Early reign William III died on 8 March 1702, leaving the Crown to Anne. At about the same time, the War of the Spanish Succession began. It would continue until the last years of Anne\'s reign, and would dominate both foreign and domestic policy. Soon after becoming Queen, Anne made her husband Lord High Admiral in control of the Royal Navy. Control of the army went to Lord Marlborough. The Duchess of Marlborough was appointed to the post of Mistress of the Robes, the highest office a lady could attain. Anne\'s first government was mostly Tory. The Whigs, who were, unlike the Tories, big supporters of the Warm became more influential after the Duke of Marlborough won a great victory at the Battle of Blenheim in 1704. The Whigs quickly rose to power, and almost all the Tories were removed from the ministry. The Act of Union between England and Scotland was then passed. Under the Act, England and Scotland became one realm called Great Britain on 1 May 1707. The Duchess of Marlborough\'s relationship with Anne worsened during 1707. Anne\'s husband, Prince George of Denmark, then died in October 1708, after which Anne grew even more distant from the Duchess of Marlborough. The Queen ended their friendship in 1709. The fall of the Whigs came about quickly as the expensive War of the Spanish Succession grew unpopular in England. In the general election of 1710, the electorate returned a large Tory majority. The new Tory government began to seek peace in the War of the Spanish Succession. The Tories were ready to compromise by giving Spain to the grandson of the French King, but the Whigs could not bear to see a Bourbon on the Spanish Throne. The dispute was resolved by outside events, when the elder brother of Archduke Charles (whom the Whigs supported) conveniently died in 1711 and Archduke Charles then inherited Austria, Hungary and the throne of the Holy Roman Empire. To also give him the Spanish throne was no longer in Great Britain\'s interests, as he would become too powerful. The Treaty of Utrecht in 1713 provided that peace, although it only got ratified by Great Britain when Anne created twelve new peers in one day to make sure it had enough support in the House of Lords. Under the terms of the ratified treaty, Philip, grandson of the French King Louis XIV, was allowed to remain on the Throne of Spain, and kept Spain\'s New World colonies. The rest of the Spanish territories, however, wer spliy amongst various European princes. Great Britain kept of Gibraltar and Minorca, and got some French colonies in North America. ### Death and legacy Anne died of an abscess and fever arising from gout, at approximately on 1 August 1714. Her body was so swollen that it had to be buried in Westminster Abbey in a vast almost-square coffin. She died shortly after the Electress Sophia (8 June 1714) and so the Electress\'s son, George, became king of Great Britain. Anne\'s reign saw greater influence in government by ministers and a decrease in the influence of the Crown. In 1708, Anne became the last British Sovereign to withhold the Royal Assent from a bill. The shift of power from the Crown to the ministry became even more apparent during the reign of George I, whose chief advisor, Sir Robert Walpole, is often described as the first Prime Minister. The age of Anne was also one of artistic, literary and scientific advancement. In architecture, Sir John Vanbrugh constructed elegant buildings such as Blenheim Palace (the home of the Marlboroughs) and Castle Howard. Writers such as Daniel Defoe, Alexander Pope and Jonathan Swift flourished during Anne\'s reign. Sir Isaac Newton also lived during Anne\'s reign, although he had reached his most important discoveries under William and Mary. ## References
# Wikijunior:Kings and Queens of England/The House of Windsor ## George V (1910--1936) The first monarch of the House of Windsor was George V. However, he started out as being of the House of Saxe-Coburg-Gotha, and so he can be read about in the previous chapter. ## Edward VIII (1936) Edward VIII was born at White Lodge, Richmond upon Thames on 23 June 1894. Edward was the eldest son of George V and Queen Mary. He was King of the United Kingdom of Great Britain and Northern Ireland and the British Dominions beyond the Seas, and Emperor of India from 20 January 1936 until his abdication on 11 December 1936, after which he was Prince Edward and then Duke of Windsor until his death on 28 May 1972. During World War II he was the Governor and Commander-in-Chief of Bahamas after spending a great deal of time in Bermuda. He was known to his family and close friends, by his last Christian name, David. ### Prince of Wales In 1910, George V made Edward Prince of Wales. When the First World War broke out in 1914 Edward joined the army, serving with the Grenadier Guards. Although Edward was willing to serve on the front lines, the British government refused to allow it, because of the harm that the capture of the heir to the throne would cause. However, Edward did witness at first hand the horror of trench warfare, and visited the front line as often as he could. His role in the war, although limited, led to his great popularity among veterans of the conflict. Throughout the 1920s the Prince of Wales represented his father, King George V, at home and abroad on many occasions. He took a special interest in visiting the poorest areas of the country. Abroad the Prince of Wales toured the British Empire, undertaking 13 tours between 1919 and 1935. In 1928, King George V gave Edward a home, Fort Belvedere, near Sunningdale in Berkshire. There Edward had relationships with a series of married women, including the American Wallis Simpson. Simpson had divorced her first husband in 1927 and later married Ernest Simpson. Edward\'s relationship with Wallis Simpson further weakened his poor relationship with his father, King George V. The King and Queen refused to receive Mrs Simpson at court, and his brother, Prince Albert, urged Edward to seek a more suitable wife. Edward, however, had now fallen in love with Wallis and the couple grew ever closer. ### Reign King George V died on 20 January 1936, and Edward became King Edward VIII. The next day he broke royal protocol by watching the proclamation of his own accession to the throne from a window of St James\'s Palace in the company of the still-married Mrs Simpson. It was also at this time that Edward VIII became the first British monarch to fly in an aeroplane, when he flew from Sandringham to London for his Accession Council. It was now becoming clear that the new King wished to marry Mrs Simpson, especially when divorce proceedings between Mr and Mrs Simpson were brought at Ipswich Crown Court. Powerful figures in the British government deemed marriage to Mrs Simpson impossible for Edward, even if Wallis obtained her second divorce, because he had become the Supreme Governor of the Church of England which prohibited remarriage after divorce. On 16 July 1936, an attempt was made on the King\'s life. Jerome Bannigan produced a loaded revolver as the King rode on horseback at Constitution Hill, near Buckingham Palace. Police spotted the gun and pounced on him, and he was quickly arrested. At Bannigan\'s trial, he alleged that \"a foreign power\" had paid him £150 to kill Edward, a claim the court rejected. On 16 November 1936, Edward met with Prime Minister Stanley Baldwin at Fort Belvedere and expressed his desire to marry Wallis Simpson when she became free to do so. The Prime Minister responded by presenting the King with three choices: he could give up the idea of marriage; marry Wallis against his ministers\' wishes; or abdicate. It was clear that Edward was not prepared to give up Wallis. By marrying against the advice of his ministers, it was likely that he would cause the government to resign, prompting a constitutional crisis. The Prime Ministers of the British dominions had also made clear their opposition to the King marrying a divorcée; only the Irish Free State was not opposed to the idea of marriage. Faced with this opposition, Edward chose to abdicate. Edward duly signed an instrument of abdication at Fort Belvedere on 10 December 1936. The next day, he performed his last act as King when he gave Royal Assent to His Majesty\'s Declaration of Abdication Act 1936 which applied to the United Kingdom and all the dominions except the Irish Free State. The Free State passed the equivalent External Relations Act, which included the abdication in its schedule, the next day. On the night of 11 December 1936, Edward, now reverted to the title of The Prince Edward, made a broadcast to the nation and the Empire, explaining his decision to abdicate. He famously said, \"I have found it impossible to carry the heavy burden of responsibility and to discharge my duties as king as I would wish to do without the help and support of the woman I love.\" After the broadcast, Edward left the United Kingdom for France, though he was unable to join Wallis until her divorce became absolute, several months later. His brother, Prince Albert, Duke of York succeeded to the throne as King George VI. George VI made Edward the Duke of Windsor. The Duke of Windsor married Mrs Simpson, who had changed her name by deed poll to Wallis Warfield, in a private ceremony on 3 June 1937 at Chateau de Candé, Monts, France. None of the British royal family attended. ### World War II In 1937, the Duke and Duchess visited Germany as personal guests of the Nazi leader Adolf Hitler, a visit much publicised by the German media. The couple then settled in France. When the Germans invaded the north of France in May 1940, the Windsors fled south, first to Biarritz, then in June to Spain. In July the pair moved to Lisbon. In August a British warship took them to the Bahamas, where the Duke of Windsor was made Governor. He held the post until the end of World War II in 1945. ### Death After the war, the couple returned once again to France in Neuilly near Paris, where they spent much of the remainder of their lives in retirement. The Royal Family never accepted the Duchess and would not receive her formally, although the former King sometimes met his mother and a brother after his abdication. The Duke died of throat cancer in 1972 in Paris, and his body was returned to Britain for burial at Frogmore near Windsor Castle. The Duchess travelled to England to attend his funeral, staying at Buckingham Palace during her visit. The Duchess, on her death a decade and a half later, was buried alongside her husband in Frogmore simply as \"Wallis, his wife\". The Duke and Duchess had no children. ## George VI (1936--1952) !George VI{width="150"} George VI was born at York Cottage on the Sandringham Estate in Norfolk on 14 December 1895. He was the second son of George V and Queen Mary. He was King of the United Kingdom of Great Britain and Northern Ireland and the British dominions beyond the seas from 11 December 1936 until his death on 6 February 1952. George VI was also the Emperor of India (until 1947) and King of Ireland (until 1949). George VI came the throne after the abdication of his brother, Edward VIII. He was king during the Second World War. He was known as Bertie, after his first name, Albert, to his family. ### Early life As a child, George often suffered from ill health and he was described as \"easily frightened and somewhat prone to tears\". Albert developed a severe stammer that lasted for many years as well as chronic stomach problems. He also suffered from knock knees, and to correct this he had to wear splints, which were extremely painful. He was also forced to write with his right hand although he was a natural left-hander. In 1909, Bertie joined the Royal Navy and served as a naval cadet. Despite coming in at the bottom of the class, Albert moved to Dartmouth and served as a midshipman. He was still in the Navy when Edward VII died on 6 May 1910. Albert was now second in line for the throne. Albert served during World War I. He saw action aboard HMS *Collingwood* in the Battle of Jutland in 1916. In 1917 Albert joined the Royal Air Force but did not see any further action in the war. After the war, Albert studied history, economics and civics for a year at Trinity College, Cambridge, from October 1919. In 1920, he began to take on royal duties, representing his father, King George V. ### Marriage and children Albert had a great deal of freedom in choosing his wife. In 1920 he met Lady Elizabeth Bowes-Lyon, the youngest daughter of Claude Bowes-Lyon, 14th Earl of Strathmore and Kinghorne and set his sights on marrying her. She rejected his proposal twice before she said yes. They were married on 26 April 1923. They had two children: Elizabeth, born in 1926, and Margaret, born in 1930. ### Reign The Duke and Duchess lived a relatively sheltered life at their London residence, 145 Piccadilly. When Edward VIII he abdicated on 11 December 1936, however, Albert became King George VI. The growing likelihood of war in Europe would dominate the reign of King George VI. Initially the King and Queen took an appeasement stance against the German dictator Adolf Hitler, and supported the policy of Neville Chamberlain. In 1939, the King and Queen visited Canada from where they made a shorter visit to the United States of America. George was the first reigning British monarch to visit either of these countries. The aim of the tour was mainly political, to shore up Atlantic support for Britain in any upcoming war. The King and Queen were extremely enthusiastically received by the Canadian public. They were also warmly received by the American people, visiting the 1939 New York World\'s Fair and staying at the White House with President Roosevelt. When war broke out in 1939, George VI with his wife chose to stay in London and not flee to Canada, as had been suggested. The King and Queen officially stayed in Buckingham Palace throughout the war, although they often escaped to Windsor Castle to avoid bombing raids. George VI and Queen Elizabeth narrowly avoided death when a lone German bomber despatched to bomb Buckingham Palace attacked. The bomb exploded in the courtyard, shattering windows in the palace. Throughout the war, the King and Queen provided morale-boosting visits throughout the UK, visiting bomb sites and munition factories. On Victory in Europe (VE) Day, the Royal Family appeared on the balcony of Buckingham Palace to celebrate the end of the war in Europe. After the war, George VI\'s reign saw the start of the break up of the British Empire, in particular when India became an independent dominion, with George VI giving up the title of Emperor of India. ### Death The war had taken its toll on the King\'s health. This was made worse by his heavy smoking and he got lung cancer. Increasingly his daughter Princess Elizabeth, the heir to the throne, would take on more of the royal duties as her father\'s health got worse. On 6 February 1952, George VI died aged 56 in his sleep at Sandringham House in Norfolk. He was buried in St George\'s Chapel in Windsor Castle. In 2002, the body of his wife Elizabeth and the ashes of his daughter Princess Margaret were interred in a tomb alongside him. ## Elizabeth II (1952--2022) ![](Elizabeth_II_greets_NASA_GSFC_employees,_May_8,_2007.jpg "Elizabeth_II_greets_NASA_GSFC_employees,_May_8,_2007.jpg") Elizabeth II was born at 17 Bruton Street in Mayfair, London on 21 April 1926. She was the eldest daughter of George VI and Queen Elizabeth. Elizabeth II was Queen of the United Kingdom of Great Britain and Northern Ireland and of many other independent nations. She became Queen on 6 February 1952 at age 25, and ruled until her death on 8 September 2022. Her 70-year reign was the second-longest after King Louis XIV of France (72 years), and the longest of any British monarch ever. ### Early life Elizabeth was thirteen years old when World War II broke out. She and her younger sister, Princess Margaret, were evacuated to Windsor Castle, Berkshire. There was some suggestion that the princesses be sent to Canada, but their mother refused to consider this, famously saying, \"The children could not possibly go without me, I wouldn\'t leave without the King, and the King will never leave\". In 1940 Princess Elizabeth made her first radio broadcast, addressing other children who had been evacuated. In 1945 Princess Elizabeth joined the Women\'s Auxiliary Territorial Service. She was the first and so far only female member of the royal family actually to serve in the military. Elizabeth made her first official visit overseas in 1947, when she went with her parents to South Africa. On her 21st birthday she made a broadcast to the British Commonwealth and Empire pledging to devote her life to the service of the people of the Commonwealth and Empire. ### Marriage and children Elizabeth married Prince Philip of Greece and Denmark on 20 November 1947, who was created the Duke of Edinburgh on the same date. The Duke was Queen Elizabeth\'s second cousin once removed, as they both descended from Christian IX of Denmark. The couple were also third cousins. After their wedding Philip and Elizabeth took up residence at Clarence House, London. But at various times between 1946 and 1953, the Duke of Edinburgh was stationed in Malta as a serving Royal Navy officer. Philip and Elizabeth lived in Malta for a period between 1949 and 1951. On 14 November 1948 Elizabeth gave birth to her first child, Charles. They later had three other children: Anne, Andrew and Edward. ### Reign King George\'s health declined during 1951 and Elizabeth frequently stood in for him at public events. She visited Greece, Italy and Malta (where Philip was then stationed) during the year. In October she toured Canada and visited President Truman in Washington, DC. In January 1952 Elizabeth and Philip set out for a tour of Australia and New Zealand. They had reached Kenya when word arrived of the death of her father on 6 February 1952. They were staying at the Treetops Hotel, where Prince Philip was the one who informed Elizabeth that she was now queen. After the coronation, Elizabeth and Philip moved to Buckingham Palace in central London. It is believed, however, that like many of her predecessors she dislikes the Palace as a residence and considers Windsor Castle, west of London, to be her home. She also spends time at Balmoral Castle in Scotland and at Sandringham House in Norfolk. At the time of Elizabeth\'s accession there was much talk of a \"new Elizabethan age\". As nations have developed economically and in literacy, Queen Elizabeth has witnessed over the past 50 years a gradual transformation of the British Empire into its modern successor, the Commonwealth. She has worked hard to maintain links with former British possessions, and in some cases, such as South Africa after the end of Apartheid, she has played an important role in retaining or restoring good relations. Queen Elizabeth has become the most widely travelled head of state in history and has visited many Commonwealth and non-Commonwealth countries. Her son Charles, the Prince of Wales, welcomed his first child Prince William in 1982. In 2002, Queen Elizabeth celebrated her Golden Jubilee, marking the 50th anniversary of her accession to the Throne. The year saw a large tour of the Commonwealth Realms, including numerous parades and official concerts. Then in 2012, the Queen celebrated her Diamond Jubilee, marking the 60th anniversary of her accession to the Throne. A year later, her grandson William had his first son Prince George. Queen Elizabeth surpassed her great-great-grandmother Queen Victoria to become the longest-reigning British monarch in 2015, and she later became the first British monarch to celebrate her Sapphire Jubilee (65 years) and Platinum Jubilee (70 years) on the throne. In 2021, the Queen\'s husband Prince Philip, the Duke of Edinburgh, died age 99, after 73 years of marriage. Her health started to decline around the same time, and it became more common for the Queen to cancel royal engagements. At the State Opening of Parliament in 2021, she could not attend, and Prince Charles had to give the speech from the throne in her place. Queen Elizabeth was also absent from the celebrations of her Platinum Jubilee during the summer of 2022. Seven months later, on 8 September 2022, she died at Balmoral age 96, bringing the second Elizabethan era to an end. ## Charles III (2022 onwards) !Charles III, seen here in 2005 when he was still the Prince of Wales.{width="160"} Charles III was born at Buckingham Palace in London on 14 November 1948. He is the eldest son of Elizabeth II and Prince Philip, the Duke of Edinburgh. Charles III is King of the United Kingdom of Great Britain and Northern Ireland and 14 other independent nations, as well as Head of the Commonwealth. He became King on 8 September 2022 after the death of his mother. He was only 3 years old when his mother became Queen, but 73 when she died. This makes Charles both the longest-serving heir to the British throne, and the oldest new king in British history. Before his accession, Charles (at the time known as the Prince of Wales) worked extensively on charity, particularly for the Prince\'s Trust. His personal life drew a large amount of public attention, particularly his marriages to the late Lady Diana Spencer and later to Camilla, the Duchess of Cornwall. In the final years of his mother\'s life, Charles began taking over some of her royal duties. ### Early life Charles was born when his grandfather George VI was on the throne, and his mother Elizabeth was first in line. When George VI died in 1952, his mother became Queen as Elizabeth II. Charles became first in line, and also gained the titles Duke of Cornwall and Duke of Rothesay (in Scotland only), which are titles that both automatically go to the heir to the throne. He went to Hill House School in West London, and later the Cheam preparatory school in Berkshire, which the Duke of Edinburgh had also gone to. The Prince finished his education at Gordonstoun, a private boarding school in the north east of Scotland. His father, the Duke of Edinburgh, had previously attended Gordonstoun, becoming head boy. It is often reported that the Prince hated his time at the school, where he was a frequent target for bullies. In 1966 Charles spent two terms at Geelong Grammar School in Victoria, Australia during which time he also visited Papua New Guinea. On his return to Gordonstoun he followed in his father\'s footsteps by becoming head boy. In 1967 he left Gordonstoun with two A levels, in history and French. Traditionally, the heir to the throne would go straight into the military after finishing school. However, Charles went to university at Trinity College, Cambridge where he studied Anthropology and Archaeology, and later History, earning a 2:2 (a lower second class degree). Charles was the first member of the British royal family to be awarded a degree. He also went to the University College of Wales, Aberystwyth to learn the Welsh language, making him the first English-born Prince of Wales ever to make a serious attempt to do so. He was created the Prince of Wales and Earl of Chester in 1958, though his actual investiture did not take place until 1 July 1969. This was a major ceremony, held at Caernarfon Castle in north Wales, a place traditionally associated with the creation of the title in the 13th century. The Welsh borough of Swansea was granted city status to mark the occasion. He served on HMS Norfolk as Sub Luietenant Prince of Wales in the early seventies. ### Marriages and children In 1980, the Prince of Wales began dating Lady Diana Spencer (born 1961), a woman from the Spencer family of nobility. They announced their engagement on 24 February 1981, and their wedding took place at St Paul\'s Cathedral on 29 July 1981, before 3,500 invited guests. An estimated 750 million people watched it on television around the world, making it one of the most viewed events in television history. Almost immediately, Princess Diana became a star attraction, chased by the press, her every move (including every change in hairstyle) closely followed by millions. However, the marriage soon became troubled. Within five years of the wedding the marriage was already on the brink of collapse, and though they remained publicly a couple, they had effectively separated by the mid-1990s, with him living in Highgrove and her in Kensington Palace. They divorced on 28 August 1996. They had had two sons, Prince William born in 1982 and Prince Henry (known by the name \"Harry\") born two years later. Princess Diana died in a car accident in Paris, France in 1997. During Charles and Diana\'s marriage, and even before it, rumors were circulating that Charles was having an affair with Camilla Parker Bowles (herself married to British Army officer Andrew Parker Bowles). Prince Charles confirmed this after his and Diana\'s divorce, explaining that this was one reason for why their marriage fell apart. As Camilla and her husband had also divorced, Charles and Camilla\'s relationship became publicly known. Over time, opinion shifted to a point where a civil marriage would be acceptable. They married on 9 April 2005 at Windsor Guildhall in Berkshire. Out of respect for Diana, who in the eyes of the public had become closely associated with the title Princess of Wales, it was announced that Camilla would not use this title (even though she as the wife of the Prince of Wales was formally entitled to do so). Camilla was instead Her Royal Highness the Duchess of Cornwall. It was also decided at the time that when Prince Charles one day became king, Camilla would be known as princess consort rather than queen. At the Platinum Jubilee of Elizabeth II in 2022, the Queen announced that she wanted Camilla to be known as queen when Charles became king, which happened when Elizabeth II died later that year. ### Personal interests Charles is a keen horseman and huntsman. He served in the Royal Navy from 1971 to 1976, commanding HMS *Bronington*, a minehunter, from February 1976 until December 1976. He is also a watercolour artist and a published writer. He has exhibited and sold a number of paintings. The Prince\'s Trust, which he founded, is a charity that works mainly with young people, offering loans to groups, businesses and people (often in deprived areas) who had difficulty receiving outside support. Fundraising concerts are regularly held for the Prince\'s Trust, with leading pop, rock and classical musicians taking part To put his ideas on architecture and town planning into practice, Charles is developing the village of Poundbury in Dorset. Prior to commencing work on Poundbury he had published a book and produced a documentary called *A Vision for Britain*. In 1992 he also established The Prince of Wales Institute of Architecture and began the publication of a magazine dealing with architecture, but the latter has since ceased independent operation after being merged with another charity to create The Prince\'s Foundation for the Built Environment in 2001. He is also keen on growing and promoting organic food, although he drew some ridicule when he joked about sometimes talking to his houseplants. Before becoming king, Charles was president of 16 charities, and raised over £100 million for charity in 2004. ### Reign Charles became king immediately when his mother died on 8 September 2022. The following day, he named his eldest son William as the new Prince of Wales. Charles III and his wife Camilla were coronated on 6 May 2023 in a ceremony at Westminster Abbey.
# Wikijunior:Kings and Queens of England/Future monarchs ## Prince William of Wales !Prince William{width="150"} Prince William of Wales was born at St. Mary\'s Hospital, Paddington on 21 June 1982. His parents are Charles, Prince of Wales and Lady Diana Spencer. He is next in the line of succession to the British throne. On 1 March 1991 (St. David\'s Day), Prince William made his first official public appearance during a visit to Cardiff, the capital city of Wales. After arriving by plane, the eight-year-old prince was taken by his parents to Llandaff Cathedral. After a tour of the cathedral, he signed its visitors book, which showed that he was left-handed. Prince William went to the Mrs Jane Mynors\' nursery school and the pre-prep Wetherby School both in West London, and later attended Ludgrove School in Berkshire. After passing an entrance exam he went on to attend Eton College in Berkshire. Whilst there he studied geography, biology and history of art at A-level. Like a growing number of British teenagers, Prince William chose to take a gap year after finishing Eton College. He took part in British Army training in Belize. He spent the final stage of his gap year in southern Chile as a volunteer with Raleigh International. Pictures of the prince cleaning a toilet were broadcast around the world. After his gap year, Prince William attended the University of St Andrews in Fife, Scotland from 2001 until he was graduated in 2005. He started doing a degree course in Arts History, although he later changed his main subject to Geography and gained a Scottish Master of Arts degree with upper-second class honours. In January 2006, the prince began his cadet course at the Royal Military Academy Sandhurst to train as an Army Officer. William joined his brother who had been there since May 2005. In July 2005, William carried out his first official engagements representing Elizabeth II, as Queen of New Zealand, at World War II commemorations in New Zealand. In September of the same year, it was announced that William will become president of The Football Association in May 2006 and patron to the UK charity Centrepoint, which works with homeless young people. In April 2011, he married Kate Middleton. In July 2013, the Duchess of Cambridge gave birth to their son, Prince George of Cambridge, third in line to the throne. The couple\'s second child, their daughter Princess Charlotte of Cambridge who is fourth in line to the throne, was born in May 2015. Prince Louis of Cambridge, the fifth in line to the throne, was born in April 2018. ## Prince George !Prince George (2013).jpg "Prince George (2013)") After William, Prince George of Cambridge will be the king of England. He was born on the 22nd of July, 2013. His full name is George Alexander Louis.
# Wikijunior:Languages/Playing with language We\'ve looked at lots of existing languages from all around the world, but if we really want to have fun with languages then we have to do more than just look; we have to play as well. Imagine if you could talk to your friends in your own private language that no one else knew. Or imagine speaking a language where everything you said sounded silly, or grumpy, or smart. Or imagine making up your own special words for all the things you see around you. In this chapter we\'ll find out how to do all these things and more. Languages are like the recipes for cakes. You start off with a whole bunch of different ingredients and then the recipe tells you how to mix them all together. In a cake you might use some flour and some eggs, a little bit of milk and butter and then maybe some chocolate. In a language you use sounds and words and when you mix them all together you end up with a sentence. And just like in a cake it is important how you combine the ingredients. If you put too much water in your cake you will end up with a slimy sludge instead of a cake. In a language if you don\'t put your words in the right order, if you don\'t follow the language\'s recipe, then you end up with a slimy sludge too. Let\'s try it with a simple sentence: If we didn\'t follow the recipe we might get: ```{=html} <div class="center"> ``` *The moon is made of bright green cheese.* *Cheese is made of the bright green moon.* *Green made of the moon is cheese bright.* ```{=html} </div> ``` And these are just two of the silly sentences you can make by not following the recipe for the language correctly. Try some more by yourself, for example you could try saying it in reverse order---starting with the last word and going to the first. No matter how you rearrange the words, there is only one correct recipe that says that the moon is made of bright green cheese. Some of the other recipes make sentences that make sense but don\'t say what we want them to say, but most recipes just end up being silly. The \"recipe\" of a language that determine which words go where, and what they mean is the *syntax*. Without even realizing it, you already know the recipe to one language---English. You know that putting words in some orders makes sense but in others it doesn\'t. But imagine if you only ever had one kind of cake. It would get boring. It\'s the same in languages: the more different language recipes you know, the more fun it is. If you wanted to make a language recipe there are two different ways you could do it. The first is to get an existing language recipe (for example, English) and use it to make a language cake, putting lots of icing on it so that nobody other than you and your friends know that underneath the icing it is really the same old cake. The other is to make a whole new recipe from scratch. Because it is easier to add icing to a cake that already exists rather than bake a whole new one, we\'ll start with that. ## Putting the icing on our language cake *Nac uoy daer siht ecnetnes? eno siht tuoba woH?* If you can read English then you can read these sentences -- but you might need a hint. When we write a normal word, we start at the left side of a word and keep writing until we reach the right side. But what if we started on the right side and wrote to the left---what if we wrote words backwards? Try reading the sentences above again, but this time read all the words backwards. You might find it easier if you try writing them down. So what did that say? Did it make sense? Try reading the second sentence again but this time instead of reading each word backwards read the whole sentence backwards. Now try saying it out loud. What does it sound like? Is it difficult to say? Why are some of the words hard to say but some of them are easy? We\'ll find out in a later section . You can use talking or writing backwards as a secret language for you and your friends. ## Making a language recipe from scratch Remember the chapter on Quenya? Well, it was a language recipe that J.R.R. Tolkien made up. He spent a large part of his life making Quenya and never really finished it, but don\'t worry: while the language recipes we make here will not be complete like real languages, they will still be usable, so you will be able to say simple things to your friends with them, without anybody else knowing what you are saying. ### How to make a language sound the way you want it to ### All the amazing things words can do ### Mixing all your words together to make sentences
# Linear Algebra/Introduction |current=Introduction |previous=Notation book helps students to master the material of a standard undergraduate linear algebra course. The material is standard in that the topics covered are Gaussian reduction, vector spaces, linear maps, determinants, and eigenvalues and eigenvectors. The audience is also standard: sophomores or juniors, usually with a background of at least one semester of calculus and perhaps with as many as three semesters. The help that it gives to students comes from taking a developmental approach---this book\'s presentation emphasizes motivation and naturalness, driven home by a wide variety of examples and extensive, careful, exercises. The developmental approach is what sets this book apart, so some expansion of the term is appropriate here. Courses in the beginning of most mathematics programs reward students less for understanding the theory and more for correctly applying formulas and algorithms. Later courses ask for mathematical maturity: the ability to follow different types of arguments, a familiarity with the themes that underlie many mathematical investigations like elementary set and function facts, and a capacity for some independent reading and thinking. Linear algebra is an ideal spot to work on the transition between the two kinds of courses. It comes early in a program so that progress made here pays off later, but also comes late enough that students are often majors and minors. The material is coherent, accessible, and elegant. There are a variety of argument styles---proofs by contradiction, if and only if statements, and proofs by induction, for instance---and examples are plentiful. So, the aim of this book\'s exposition is to help students develop from being successful at their present level, in classes where a majority of the members are interested mainly in applications in science or engineering, to being successful at the next level, that of serious students of the subject of mathematics itself. Helping students make this transition means taking the mathematics seriously, so all of the results in this book are proved. On the other hand, we cannot assume that students have already arrived, and so in contrast with more abstract texts, we give many examples and they are often quite detailed. In the past, linear algebra texts commonly made this transition abruptly. They began with extensive computations of linear systems, matrix multiplications, and determinants. When the concepts---vector spaces and linear maps---finally appeared, and definitions and proofs started, often the change brought students to a stop. In this book, while we start with a computational topic, linear reduction, from the first we do more than compute. We do linear systems quickly but completely, including the proofs needed to justify what we are computing. Then, with the linear systems work as motivation and at a point where the study of linear combinations seems natural, the second chapter starts with the definition of a real vector space. This occurs by the end of the third week. Another example of our emphasis on motivation and naturalness is that the third chapter on linear maps does not begin with the definition of homomorphism, but with that of isomorphism. That\'s because this definition is easily motivated by the observation that some spaces are \"just like\" others. After that, the next section takes the reasonable step of defining homomorphism by isolating the operation-preservation idea. This approach loses mathematical slickness, but it is a good trade because it comes in return for a large gain in sensibility to students. One aim of a developmental approach is that students should feel throughout the presentation that they can see how the ideas arise, and perhaps picture themselves doing the same type of work. The clearest example of the developmental approach taken here---and the feature that most recommends this book---is the exercises. A student progresses most while doing the exercises, so they have been selected with great care. Each problem set ranges from simple checks to reasonably involved proofs. Since an instructor usually assigns about a dozen exercises after each lecture, each section ends with about twice that many, thereby providing a selection. There are even a few problems that are challenging puzzles taken from various journals, competitions, or problems collections. (These are marked with a \"**?**\" and as part of the fun, the original wording has been retained as much as possible.) In total, the exercises are aimed to both build an ability at, and help students experience the pleasure of, *doing* mathematics. ## Applications and Computers. The point of view taken here, that linear algebra is about vector spaces and linear maps, is not taken to the complete exclusion of others. Applications and the role of the computer are important and vital aspects of the subject. Consequently, each of this book\'s chapters closes with a few application or computer-related topics. Some are: network flows, the speed and accuracy of computer linear reductions, Leontief Input/Output analysis, dimensional analysis, Markov chains, voting paradoxes, analytic projective geometry, and difference equations. These topics are brief enough to be done in a day\'s class or to be given as independent projects for individuals or small groups. Most simply give the reader a taste of the subject, discuss how linear algebra comes in, point to some further reading, and give a few exercises. In short, these topics invite readers to see for themselves that linear algebra is a tool that a professional must have. ## For people reading this book on their own. This book\'s emphasis on motivation and development make it a good choice for self-study. But, while a professional instructor can judge what pace and topics suit a class, if you are an independent student then perhaps you would find some advice helpful. Here are two timetables for a semester. The first focuses on core material. ```{=html} <TABLE border=1px style="margin:auto;"> ``` ```{=html} <TR> ``` ```{=html} <TD style="border-bottom: 2px-black-solid"> ``` *week* ```{=html} <TD style="border-bottom: 2px-black-solid"> ``` *Monday* ```{=html} <TD style="border-bottom: 2px-black-solid"> ``` *Wednesday* ```{=html} <TD style="border-bottom: 2px-black-solid"> ``` *Friday* ```{=html} <TR> ``` ```{=html} <TD> ``` 1 ```{=html} <TD> ``` One.I.1 ```{=html} <TD> ``` One.I.1, 2 ```{=html} <TD> ``` One.I.2, 3 ```{=html} <TR> ``` ```{=html} <TD> ``` 2 ```{=html} <TD> ``` One.I.3 ```{=html} <TD> ``` One.II.1 ```{=html} <TD> ``` One.II.2 ```{=html} <TR> ``` ```{=html} <TD> ``` 3 ```{=html} <TD> ``` One.III.1, 2 ```{=html} <TD> ``` One.III.2 ```{=html} <TD> ``` Two.I.1 ```{=html} <TR> ``` ```{=html} <TD> ``` 4 ```{=html} <TD> ``` Two.I.2 ```{=html} <TD> ``` Two.II ```{=html} <TD> ``` Two.III.1 ```{=html} <TR> ``` ```{=html} <TD> ``` 5 ```{=html} <TD> ``` Two.III.1, 2 ```{=html} <TD> ``` Two.III.2 ```{=html} <TD> ``` Exam ```{=html} <TR> ``` ```{=html} <TD> ``` 6 ```{=html} <TD> ``` Two.III.2, 3 ```{=html} <TD> ``` Two.III.3 ```{=html} <TD> ``` Three.I.1 ```{=html} <TR> ``` ```{=html} <TD> ``` 7 ```{=html} <TD> ``` Three.I.2 ```{=html} <TD> ``` Three.II.1 ```{=html} <TD> ``` Three.II.2 ```{=html} <TR> ``` ```{=html} <TD> ``` 8 ```{=html} <TD> ``` Three.II.2 ```{=html} <TD> ``` Three.II.2 ```{=html} <TD> ``` Three.III.1 ```{=html} <TR> ``` ```{=html} <TD> ``` 9 ```{=html} <TD> ``` Three.III.1 ```{=html} <TD> ``` Three.III.2 ```{=html} <TD> ``` Three.IV.1, 2 ```{=html} <TR> ``` ```{=html} <TD> ``` 10 ```{=html} <TD> ``` Three.IV.2, 3, 4 ```{=html} <TD> ``` Three.IV.4 ```{=html} <TD> ``` Exam ```{=html} <TR> ``` ```{=html} <TD> ``` 11 ```{=html} <TD> ``` Three.IV.4, Three.V.1 ```{=html} <TD> ``` Three.V.1, 2 ```{=html} <TD> ``` Four.I.1, 2 ```{=html} <TR> ``` ```{=html} <TD> ``` 12 ```{=html} <TD> ``` Four.I.3 ```{=html} <TD> ``` Four.II ```{=html} <TD> ``` Four.II ```{=html} <TR> ``` ```{=html} <TD> ``` 13 ```{=html} <TD> ``` Four.III.1 ```{=html} <TD> ``` Five.I ```{=html} <TD> ``` Five.II.1 ```{=html} <TR> ``` ```{=html} <TD> ``` 14 ```{=html} <TD> ``` Five.II.2 ```{=html} <TD> ``` Five.II.3 ```{=html} <TD> ``` Review ```{=html} </TABLE> ``` The second timetable is more ambitious (it supposes that you know One.II, the elements of vectors, usually covered in third semester calculus). ```{=html} <TABLE border=1px style="margin:auto;"> ``` ```{=html} <TR> ``` ```{=html} <TD> ``` *week* ```{=html} <TD> ``` *Monday* ```{=html} <TD> ``` *Wednesday* ```{=html} <TD> ``` *Friday* ```{=html} <TR> ``` ```{=html} <TD> ``` 1 ```{=html} <TD> ``` One.I.1 ```{=html} <TD> ``` One.I.2 ```{=html} <TD> ``` One.I.3 ```{=html} <TR> ``` ```{=html} <TD> ``` 2 ```{=html} <TD> ``` One.I.3 ```{=html} <TD> ``` One.III.1, 2 ```{=html} <TD> ``` One.III.2 ```{=html} <TR> ``` ```{=html} <TD> ``` 3 ```{=html} <TD> ``` Two.I.1 ```{=html} <TD> ``` Two.I.2 ```{=html} <TD> ``` Two.II ```{=html} <TR> ``` ```{=html} <TD> ``` 4 ```{=html} <TD> ``` Two.III.1 ```{=html} <TD> ``` Two.III.2 ```{=html} <TD> ``` Two.III.3 ```{=html} <TR> ``` ```{=html} <TD> ``` 5 ```{=html} <TD> ``` Two.III.4 ```{=html} <TD> ``` Three.I.1 ```{=html} <TD> ``` Exam ```{=html} <TR> ``` ```{=html} <TD> ``` 6 ```{=html} <TD> ``` Three.I.2 ```{=html} <TD> ``` Three.II.1 ```{=html} <TD> ``` Three.II.2 ```{=html} <TR> ``` ```{=html} <TD> ``` 7 ```{=html} <TD> ``` Three.III.1 ```{=html} <TD> ``` Three.III.2 ```{=html} <TD> ``` Three.IV.1, 2 ```{=html} <TR> ``` ```{=html} <TD> ``` 8 ```{=html} <TD> ``` Three.IV.2 ```{=html} <TD> ``` Three.IV.3 ```{=html} <TD> ``` Three.IV.4 ```{=html} <TR> ``` ```{=html} <TD> ``` 9 ```{=html} <TD> ``` Three.V.1 ```{=html} <TD> ``` Three.V.2 ```{=html} <TD> ``` Three.VI.1 ```{=html} <TR> ``` ```{=html} <TD> ``` 10 ```{=html} <TD> ``` Three.VI.2 ```{=html} <TD> ``` Four.I.1 ```{=html} <TD> ``` Exam ```{=html} <TR> ``` ```{=html} <TD> ``` 11 ```{=html} <TD> ``` Four.I.2 ```{=html} <TD> ``` Four.I.3 ```{=html} <TD> ``` Four.I.4 ```{=html} <TR> ``` ```{=html} <TD> ``` 12 ```{=html} <TD> ``` Four.II ```{=html} <TD> ``` Four.II, Four.III.1 ```{=html} <TD> ``` Four.III.2, 3 ```{=html} <TR> ``` ```{=html} <TD> ``` 13 ```{=html} <TD> ``` Five.II.1, 2 ```{=html} <TD> ``` Five.II.3 ```{=html} <TD> ``` Five.III.1 ```{=html} <TR> ``` ```{=html} <TD> ``` 14 ```{=html} <TD> ``` Five.III.2 ```{=html} <TD> ``` Five.IV.1, 2 ```{=html} <TD> ``` Five.IV.2 ```{=html} </TABLE> ``` See the table of contents for the titles of these subsections. To help you make time trade-offs, in the table of contents I have marked subsections as optional if some instructors will pass over them in favor of spending more time elsewhere. You might also try picking one or two topics that appeal to you from the end of each chapter. You\'ll get more from these if you have access to computer software that can do the big calculations. The most important advice is: do many exercises. The recommended exercises are labeled throughout. (The answers are available.) You should be aware, however, that few inexperienced people can write correct proofs. Try to find a knowledgeable person to work with you on this. Finally, if I may, a caution for all students, independent or not: I cannot overemphasize how much the statement that I sometimes hear, \"I understand the material, but it\'s only that I have trouble with the problems\" reveals a lack of understanding of what we are up to. Being able to do things with the ideas is their point. The quotes below express this sentiment admirably. They state what I believe is the key to both the beauty and the power of mathematics and the sciences in general, and of linear algebra in particular (I took the liberty of formatting them as poems). *I know of no better tactic*\ * than the illustration of exciting principles*\ *by well-chosen particulars.*\         *\--Stephen Jay Gould* *If you really wish to learn*\ * then you must mount the machine*\ * and become acquainted with its tricks*\ *by actual trial.*\         *\--Wilbur Wright* Jim Hefferon\ Mathematics, Saint Michael\'s College\ Colchester, Vermont USA 05439\ `http://joshua.smcvt.edu`\ 2006-May-20 *Author\'s Note.* Inventing a good exercise, one that enlightens as well as tests, is a creative act, and hard work. The inventor deserves recognition. But for some reason texts have traditionally not given attributions for questions. I have changed that here where I was sure of the source. I would greatly appreciate hearing from anyone who can help me to correctly attribute others of the questions. ja:線型代数学/序論
# Linear Algebra/Gauss' Method |current=Gauss' Method |previous=Solving Linear Systems Finding the set of all solutions is **solving** the system. No guesswork or good fortune is needed to solve a linear system. There is an algorithm that always works. The next example introduces that algorithm, called **Gauss\' method**. It transforms the system, step by step, into one with a form that is easily solved. Most of this subsection and the next one consists of examples of solving linear systems by Gauss\' method. We will use it throughout this book. It is fast and easy. But, before we get to those examples, we will first show that this method is also safe in that it never loses solutions or picks up extraneous solutions. Each of those three operations has a restriction. Multiplying a row by $0$ is not allowed because obviously that can change the solution set of the system. Similarly, adding a multiple of a row to itself is not allowed because adding $-1$ times the row to itself has the effect of multiplying the row by $0$. Finally, swapping a row with itself is disallowed to make some results in the fourth chapter easier to state and remember (and besides, self-swapping doesn\'t accomplish anything). When writing out the calculations, we will abbreviate \"row $i$\" by \"$\rho_i$\". For instance, we will denote a pivot operation by $k\rho_i+\rho_j$, with the row that is changed written second. We will also, to save writing, often list pivot steps together when they use the same $\rho_i$. As these examples illustrate, Gauss\' method uses the elementary reduction operations to set up back-substitution. Strictly speaking, the operation of rescaling rows is not needed to solve linear systems. We have included it because we will use it later in this chapter as part of a variation on Gauss\' method, the Gauss-Jordan method. All of the systems seen so far have the same number of equations as unknowns. All of them have a solution, and for all of them there is only one solution. We finish this subsection by seeing for contrast some other things that can happen. That example\'s system has more equations than variables. Gauss\' method is also useful on systems with more variables than equations. Many examples are in the next subsection. Another way that linear systems can differ from the examples shown earlier is that some linear systems do not have a unique solution. This can happen in two ways. The first is that it can fail to have any solution at all. The other way that a linear system can fail to have a unique solution is to have many solutions. Don\'t be fooled by the \"$0=0$\" equation in that example. It is not the signal that a system has many solutions. We will finish this subsection with a summary of what we\'ve seen so far about Gauss\' method. Gauss\' method uses the three row operations to set a system up for back substitution. If any step shows a contradictory equation then we can stop with the conclusion that the system has no solutions. If we reach echelon form without a contradictory equation, and each variable is a leading variable in its row, then the system has a unique solution and we find it by back substitution. Finally, if we reach echelon form without a contradictory equation, and there is not a unique solution (at least one variable is not a leading variable) then the system has many solutions. The next subsection deals with the third case--- we will see how to describe the solution set of a system with many solutions. ## Exercises ## References - . - . - . - . - .
# Linear Algebra/Describing the Solution Set |current=Describing the Solution Set |previous=Gauss' Method A linear system with a unique solution has a solution set with one element. A linear system with no solution has a solution set that is empty. In these cases the solution set is easy to describe. Solution sets are a challenge to describe only when they contain many elements. In the echelon form system derived in the above example, $x$ and $y$ are leading variables and $z$ is free. We refer to a variable used to describe a family of solutions as a **parameter** and we say that the set above is **parametrized** with $y$ and $w$ . (The terms \"parameter\" and \"free variable\" do not mean the same thing. Above, $y$ and $w$ are free because in the echelon form system they do not lead any row. They are parameters because they are used in the solution set description. We could have instead parametrized with $y$ and $z$ by rewriting the second equation as $w=\frac23-\frac13z$ . In that case, the free variables are still $y$ and $w$ , but the parameters are $y$ and $z$ . Notice that we could not have parametrized with $x$ and $y$ , so there is sometimes a restriction on the choice of parameters. The terms \"parameter\" and \"free\" are related because, as we shall show later in this chapter, the solution set of a system can always be parametrized with the free variables. Consequently, we shall parametrize all of our descriptions in this way.) We finish this subsection by developing the notation for linear systems and their solution sets that we shall use in the rest of this book. Matrices are usually named by upper case roman letters, e.g. $A$ . Each entry is denoted by the corresponding lower-case letter, e.g. $a_{i,j}$ is the number in row $i$ and column $j$ of the array. For instance, $$A=\begin{pmatrix}1&2.2&5\\3&4&-7\end{pmatrix}$$ has two rows and three columns, and so is a $2\times3$ matrix. (Read that \"two-by-three\"; the number of rows is always stated first.) The entry in the second row and first column is $a_{2,1}=3$ . Note that the order of the subscripts matters: $a_{1,2}\ne a_{2,1}$ since $a_{1,2}=2.2$ . (The parentheses around the array are a typographic device so that when two matrices are side by side we can tell where one ends and the other starts.) Matrices occur throughout this book. We shall use $\mathcal{M}_{n\times m}$ to denote the collection of $n\times m$ matrices. We will also use the array notation to clarify the descriptions of solution sets. A description like $\{(2-2z+2w,-1+z-w,z,w)\big|z,w\in\R\}$ from Example 2.3 is hard to read. We will rewrite it to group all the constants together, all the coefficients of $z$ together, and all the coefficients of $w$ together. We will write them vertically, in one-column wide matrices. $$\left\{\begin{pmatrix}2\\-1\\0\\0\end{pmatrix}+\begin{pmatrix}-2\\1\\1\\0\end{pmatrix}z+\begin{pmatrix}2\\-1\\0\\1\end{pmatrix}w\Bigg|z,w\in\R\right\}$$ For instance, the top line says that $x=2-2z+2w$ . The next section gives a geometric interpretation that will help us picture the solution sets when they are written in this way. Vectors are an exception to the convention of representing matrices with capital roman letters. We use lower-case roman or greek letters overlined with an arrow: $\vec a,\vec b$ \... or $\vec{\alpha},\vec{\beta}$ \... (boldface is also common: $\mathbf{a}$ or $\boldsymbol{\alpha}$). For instance, this is a column vector with a third component of $7$ . $$\vec v=\begin{pmatrix}1\\3\\7\end{pmatrix}$$ The style of description of solution sets that we use involves adding the vectors, and also multiplying them by real numbers, such as the $z$ and $w$ . We need to define these operations. Scalar multiplication can be written in either order: $r\cdot\vec v$ or $\vec v\cdot r$ , or without the \"$\cdot$\" symbol: $r\vec v$ . (Do not refer to scalar multiplication as \"scalar product\" because that name is used for a different operation.) Notice that the definitions of vector addition and scalar multiplication agree where they overlap, for instance, $\vec v+\vec v=2\vec v$ . With the notation defined, we can now solve systems in the way that we will use throughout this book. Before the exercises, we pause to point out some things that we have yet to do. The first two subsections have been on the mechanics of Gauss\' method. Except for one result, Theorem 1.4 --- without which developing the method doesn\'t make sense since it says that the method gives the right answers--- we have not stopped to consider any of the interesting questions that arise. For example, can we always describe solution sets as above, with a particular solution vector added to an unrestricted linear combination of some other vectors? The solution sets we described with unrestricted parameters were easily seen to have infinitely many solutions so an answer to this question could tell us something about the size of solution sets. An answer to that question could also help us picture the solution sets, in $\mathbb{R}^2$, or in $\mathbb{R}^3$, etc. Many questions arise from the observation that Gauss\' method can be done in more than one way (for instance, when swapping rows, we may have a choice of which row to swap with). Theorem 1.4 says that we must get the same solution set no matter how we proceed, but if we do Gauss\' method in two different ways must we get the same number of free variables both times, so that any two solution set descriptions have the same number of parameters? Must those be the same variables (e.g., is it impossible to solve a problem one way and get $y$ and $w$ free or solve it another way and get $y$ and $z$ free)? In the rest of this chapter we answer these questions. The answer to each is \"yes\". The first question is answered in the last subsection of this section. In the second section we give a geometric description of solution sets. In the final section of this chapter we tackle the last set of questions. Consequently, by the end of the first chapter we will not only have a solid grounding in the practice of Gauss\' method, we will also have a solid grounding in the theory. We will be sure of what can and cannot happen in a reduction. ## Exercises ## References - *The USSR Mathematics Olympiad*, number 174. -
# Linear Algebra/General = Particular + Homogeneous |current=General = Particular + Homogeneous |previous=Describing the Solution Set ## Description of Solution Sets The prior subsection has many descriptions of solution sets. They all fit a pattern. They have a vector that is a particular solution of the system added to an unrestricted combination of some other vectors. The solution set from Example 2.13 illustrates. $$\left\{ \underbrace{ \begin{pmatrix} 0 \\ 4 \\ 0 \\ 0 \\ 0 \end{pmatrix}}_{\begin{array}{c}\\[-19pt]\scriptstyle\text{particular} \\[-5pt]\scriptstyle\text{solution}\end{array}}+ \underbrace{w\begin{pmatrix} 1 \\ -1 \\ 3 \\ 1 \\ 0 \end{pmatrix}+ u\begin{pmatrix} 1/2 \\ -1 \\ 1/2 \\ 0 \\ 1 \end{pmatrix}}_{\begin{array}{c}\\[-19pt]\scriptstyle\text{unrestricted}\\[-5pt]\scriptstyle\text{combination}\end{array}} \,\big|\, w,u\in\mathbb{R}\right\}$$ The combination is unrestricted in that $w$ and $u$ can be any real numbers--- there is no condition like \"such that $2w-u=0$\" that would restrict which pairs $w,u$ can be used to form combinations. That example shows an infinite solution set conforming to the pattern. We can think of the other two kinds of solution sets as also fitting the same pattern. A one-element solution set fits in that it has a particular solution, and the unrestricted combination part is a trivial sum (that is, instead of being a combination of two vectors, as above, or a combination of one vector, it is a combination of no vectors). A zero-element solution set fits the pattern since there is no particular solution, and so the set of sums of that form is empty. We will show that the examples from the prior subsection are representative, in that the description pattern discussed above holds for every solution set. This description has two parts, the particular solution $\vec{p}$ and also the unrestricted linear combination of the $\vec{\beta}$\'s. We shall prove the theorem in two corresponding parts, with two lemmas. ## Homogeneous Systems We will focus first on the unrestricted combination part. To do that, we consider systems that have the vector of zeroes as one of the particular solutions, so that $\vec{p}+c_1\vec{\beta}_1+\dots+c_k\vec{\beta}_k$ can be shortened to $c_1\vec{\beta}_1+\dots+c_k\vec{\beta}_k$. (These are \"homogeneous\" because all of the terms involve the same power of their variable--- the first power--- including a \"$0x_{0}$\" that we can imagine is on the right side.) Studying the associated homogeneous system has a great advantage over studying the original system. Nonhomogeneous systems can be inconsistent. But a homogeneous system must be consistent since there is always at least one solution, the vector of zeros. There are many different zero vectors, e.g., the one-tall zero vector, the two-tall zero vector, etc. Nonetheless, people often refer to \"the\" zero vector, expecting that the size of the one being discussed will be clear from the context. We now have the terminology to prove the two parts of Theorem 3.1 . The first lemma deals with unrestricted combinations. Before the proof, we will recall the back substitution calculations that were done in the prior subsection. Imagine that we have brought a system to this echelon form. $$\begin{array}{*{4}{rc}r} x &+ &2y &- &z &+ &2w &= &0 \\ & &-3y &+ &z & & &= &0 \\ & & & & & &-w &= &0 \end{array}$$ We next perform back-substitution to express each variable in terms of the free variable $z$. Working from the bottom up, we get first that $w$ is $0\cdot z$, next that $y$ is $(1/3)\cdot z$, and then substituting those two into the top equation $x+2((1/3)z)-z+2(0)=0$ gives $x=(1/3)\cdot z$. So, back substitution gives a parametrization of the solution set by starting at the bottom equation and using the free variables as the parameters to work row-by-row to the top. The proof below follows this pattern. *Comment:* That is, this proof just does a verification of the bookkeeping in back substitution to show that we haven\'t overlooked any obscure cases where this procedure fails, say, by leading to a division by zero. So this argument, while quite detailed, doesn\'t give us any new insights. Nevertheless, we have written it out for two reasons. The first reason is that we need the result--- the computational procedure that we employ must be verified to work as promised. The second reason is that the row-by-row nature of back substitution leads to a proof that uses the technique of mathematical induction.[^1] This is an important, and non-obvious, proof technique that we shall use a number of times in this book. Doing an induction argument here gives us a chance to see one in a setting where the proof material is easy to follow, and so the technique can be studied. Readers who are unfamiliar with induction arguments should be sure to master this one and the ones later in this chapter before going on to the second chapter. `</math>`{=html} and substitute its expression in terms of free variables. The result has the form $$a_{m-(t+1),\ell_{m-(t+1)}}x_{\ell_{m-(t+1)}}+ \text{sums of multiples of free variables}=0$$ where $a_{m-(t+1),\ell_{m-(t+1)}}\neq 0$. We move the free variables to the right-hand side and divide by $a_{m-(t+1),\ell_{m-(t+1)}}$, to end with $x_{\ell_{m-(t+1)}}$ expressed in terms of free variables. Because we have shown both the base step and the inductive step, by the principle of mathematical induction the proposition is true. }} We say that the set $\{c_1\vec{\beta}_1+\cdots+c_k\vec{\beta}_k \,\big|\, c_1,\ldots,c_k\in\mathbb{R}\}$ is **generated by** or **spanned by** the set of vectors $\{{\vec{\beta}_1},\ldots,{\vec{\beta}_k}\}$. There is a tricky point to this definition. If a homogeneous system has a unique solution, the zero vector, then we say the solution set is generated by the empty set of vectors. This fits with the pattern of the other solution sets: in the proof above the solution set is derived by taking the $c$\'s to be the free variables and if there is a unique solution then there are no free variables. This proof incidentally shows, as discussed after Example 2.4 , that solution sets can always be parametrized using the free variables. ## Nonhomogeneous Systems The next lemma finishes the proof of Theorem 3.1 by considering the particular solution part of the solution set\'s description. The two lemmas above together establish Theorem 3.1 . We remember that theorem with the slogan \"$\text{General} = \text{Particular} + \text{Homogeneous}$\". This table summarizes the factors affecting the size of a general solution. +---------------+-----------+---------------------------------+-------------------+ | | | *number of solutions of the*\ | | | | | *associated homogeneous system* | | +---------------+-----------+---------------------------------+-------------------+ | | | *one* | *infinitely many* | +---------------+-----------+---------------------------------+-------------------+ | *particular*\ | *yes* | unique\ | infinitely many\ | | *solution*\ | | solution | solutions | | *exists?* | | | | +---------------+-----------+---------------------------------+-------------------+ | *no* | no\ | no\ | | | | solutions | solutions | | +---------------+-----------+---------------------------------+-------------------+ The factor on the top of the table is the simpler one. When we perform Gauss\' method on a linear system, ignoring the constants on the right side and so paying attention only to the coefficients on the left-hand side, we either end with every variable leading some row or else we find that some variable does not lead a row, that is, that some variable is free. (Of course, \"ignoring the constants on the right\" is formalized by considering the associated homogeneous system. We are simply putting aside for the moment the possibility of a contradictory equation.) A nice insight into the factor on the top of this table at work comes from considering the case of a system having the same number of equations as variables. This system will have a solution, and the solution will be unique, if and only if it reduces to an echelon form system where every variable leads its row, which will happen if and only if the associated homogeneous system has a unique solution. Thus, the question of uniqueness of solution is especially interesting when the system has the same number of equations as variables. The above table has two factors. We have already considered the factor along the top: we can tell which column a given linear system goes in solely by considering the system\'s left-hand side--- the constants on the right-hand side play no role in this factor. The table\'s other factor, determining whether a particular solution exists, is tougher. Consider these two $$\begin{array}{*{2}{rc}r} 3x &+ &2y &= &5 \\ 3x &+ &2y &= &5 \end{array} \qquad \begin{array}{*{2}{rc}r} 3x &+ &2y &= &5 \\ 3x &+ &2y &= &4 \end{array}$$ with the same left sides but different right sides. Obviously, the first has a solution while the second does not, so here the constants on the right side decide if the system has a solution. We could conjecture that the left side of a linear system determines the number of solutions while the right side determines if solutions exist, but that guess is not correct. Compare these two systems $$\begin{array}{*{2}{rc}r} 3x &+ &2y &= &5 \\ 4x &+ &2y &= &4 \end{array} \qquad \begin{array}{*{2}{rc}r} 3x &+ &2y &= &5 \\ 3x &+ &2y &= &4 \end{array}$$ with the same right sides but different left sides. The first has a solution but the second does not. Thus the constants on the right side of a system don\'t decide alone whether a solution exists; rather, it depends on some interaction between the left and right sides. For some intuition about that interaction, consider this system with one of the coefficients left as the parameter $c$. $$\begin{array}{*{3}{rc}r} x &+ &2y &+ &3z &= &1 \\ x &+ &y &+ &z &= &1 \\ cx &+ &3y &+ &4z &= &0 \end{array}$$ If $c=2$ this system has no solution because the left-hand side has the third row as a sum of the first two, while the right-hand does not. If $c\neq 2$ this system has a unique solution (try it with $c=1$). For a system to have a solution, if one row of the matrix of coefficients on the left is a linear combination of other rows, then on the right the constant from that row must be the same combination of constants from the same rows. More intuition about the interaction comes from studying linear combinations. That will be our focus in the second chapter, after we finish the study of Gauss\' method itself in the rest of this chapter. ## Exercises ## Footnotes ```{=html} <references/> ``` |current=General = Particular + Homogeneous |previous=Describing the Solution Set |next=Comparing Set Descriptions}}`{=mediawiki} [^1]: More information on mathematical induction is in the appendix.
# Linear Algebra/Comparing Set Descriptions |current=Comparing Set Descriptions |previous=General = Particular + Homogeneous *This subsection is optional. Later material will not require the work here.* ## Comparing Set Descriptions A set can be described in many different ways. Here are two different descriptions of a single set: $$\{\begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix}z\,\big|\, z\in\mathbb{R}\} \quad\text{and}\quad \{\begin{pmatrix} 2 \\ 4 \\ 6 \end{pmatrix}w\,\big|\, w\in\mathbb{R}\}.$$ For instance, this set contains $$\begin{pmatrix} 5 \\ 10 \\ 15 \end{pmatrix}$$ (take $z=5$ and $w=5/2$) but does not contain $$\begin{pmatrix} 4 \\ 8 \\ 11 \end{pmatrix}$$ (the first component gives $z=4$ but that clashes with the third component, similarly the first component gives $w=4/5$ but the third component gives something different). Here is a third description of the same set: $$\{\begin{pmatrix} 3 \\ 6 \\ 9 \end{pmatrix}+\begin{pmatrix} -1 \\ -2 \\ -3 \end{pmatrix}y\,\big|\, y\in\mathbb{R}\}.$$ We need to decide when two descriptions are describing the same set. More pragmatically stated, how can a person tell when an answer to a homework question describes the same set as the one described in the back of the book? ## Set Equality Sets are equal if and only if they have the same members. A common way to show that two sets, $S_1$ and $S_2$, are equal is to show mutual inclusion: any member of $S_1$ is also in $S_2$, and any member of $S_2$ is also in $S_1$.[^1] ## Exercises ## Footnotes ```{=html} <references/> ``` |current=Comparing Set Descriptions |previous=General = Particular + Homogeneous |next=Automation}}`{=mediawiki} [^1]: More information on set equality is in the appendix.
# Linear Algebra/Automation |current=Automation |previous=Comparing Set Descriptions This is a PASCAL routine to do $k\rho_i+\rho_j$ to an augmented matrix. ``` pascal PROCEDURE Pivot(VAR LinSys : AugMat; k : REAL; i, j : INTEGER) VAR Col : INTEGER; BEGIN FOR Col:=1 TO NumVars+1 DO LinSys[j,Col]:=k*LinSys[i,Col]+LinSys[j,Col]; END; ``` Of course this is only one part of a whole program, but it makes the point that Gaussian reduction is ideal for computer coding. There are pitfalls, however. For example, some arise from the computer\'s use of finite-precision approximations of real numbers. These systems provide a simple example. ![](Linalg_singular_and_nonsingular_systems.png "Linalg_singular_and_nonsingular_systems.png") (The second two lines are hard to tell apart.) Both have $(1,1)$ as their unique solution. In the first system, some small change in the numbers will produce only a small change in the solution: $$\begin{array}{*{2}{rc}r} x &+ &2y &= &3 \\ 3x &- &2y &= &1.008 \end{array}$$ gives a solution of $(1.002,0.999)$. Geometrically, changing one of the lines by a small amount does not change the intersection point by very much. That\'s not true for the second system. A small change in the coefficients $$\begin{array}{*{2}{rc}r} x &+ &2y &= &3 \\ 1.000\,000\,01x &+ &2y &= &3.000\,000\,03 \end{array}$$ leads to a completely different answer: $(3,0)$. The solution of the second example varies wildly, depending on a $9$-th digit. That\'s bad news for a machine using $8$ digits to represent reals. In short, systems that are nearly singular may be hard to compute with. Another thing that can go wrong is error propagation. In a system with a large number of equations (say, 100 or more), small rounding errors early in the procedure can snowball to overwhelm the solution at the end. These issues, and many others like them, are outside the scope of this book, but remember that just because Gauss\' method always works in theory and just because a program correctly implements that method and just because the answer appears on green-bar paper, doesn\'t mean that answer is right. In practice, always use a package where experts have
# Linear Algebra/Linear Geometry of n-Space |current=Linear Geometry of n-Space |previous=Automation who have seen the elements of vectors before, in calculus or physics, this section is an optional review. However, later work will refer to this material so it is not optional if it is not a review.* In the first section, we had to do a bit of work to show that there are only three types of solution sets--- singleton, empty, and infinite. But in the special case of systems with two equations and two unknowns this is easy to see. Draw each two-unknowns equation as a line in the plane and then the two lines could have a unique intersection, be parallel, or be the same line. ```{=html} <TABLE border=0px cellpadding=20px style="text-align:center;margin:auto;"> ``` ```{=html} <TR> ``` ```{=html} <TD> ``` *Unique solution* ```{=html} <TD> ``` *No solutions* ```{=html} <TD> ``` *Infinitely many*\ *solutions* ```{=html} <TR> ``` ```{=html} <TD> ``` ![](Linalg_unique_solution.png "Linalg_unique_solution.png"){width="150"}\ $\begin{array}{*{2}{rc}r} \scriptstyle 3x &\scriptstyle + &\scriptstyle 2y &\scriptstyle = &\scriptstyle 7 \\[-5pt] \scriptstyle x &\scriptstyle - &\scriptstyle y &\scriptstyle = &\scriptstyle -1 \end{array}$ ```{=html} <TD> ``` ![](Linalg_no_solutions.png "Linalg_no_solutions.png"){width="150"}\ $\begin{array}{*{2}{rc}r} \scriptstyle 3x &\scriptstyle + &\scriptstyle 2y &\scriptstyle = &\scriptstyle 7 \\[-5pt] \scriptstyle 3x &\scriptstyle + &\scriptstyle 2y &\scriptstyle = &\scriptstyle 4 \end{array}$ ```{=html} <TD> ``` ![](Linalg_infinitely_many_solutions.png "Linalg_infinitely_many_solutions.png"){width="150"}\ $\scriptstyle \begin{array}{*{2}{rc}r} \scriptstyle 3x &\scriptstyle + &\scriptstyle 2y &\scriptstyle = &\scriptstyle 7 \\[-5pt] \scriptstyle 6x &\scriptstyle + &\scriptstyle 4y &\scriptstyle = &\scriptstyle 14 \end{array}$ ```{=html} </TABLE> ``` These pictures don\'t prove the results from the prior section, which apply to any number of linear equations and any number of unknowns, but nonetheless they do help us to understand those results. This section develops the ideas that we need to express our results from the prior section, and from some future sections, geometrically. In particular, while the two-dimensional case is familiar, to extend to systems with more than two unknowns we shall need some higher-dimensional geometry. |current=Linear Geometry of n-Space |previous=Automation |next=Vectors in Space}}`{=mediawiki}
# Linear Algebra/Vectors in Space |current=Vectors in Space |previous=Linear Geometry of n-Space \"Higher-dimensional geometry\" sounds exotic. It is exotic--- interesting and eye-opening. But it isn\'t distant or unreachable. We begin by defining one-dimensional space to be the set $\mathbb{R}^1$. To see that definition is reasonable, draw a one-dimensional space ![](Linalg_line.png "Linalg_line.png"){width="800"} and make the usual correspondence with $\mathbb{R}$: pick a point to label $0$ and another to label $1$. ![](Linalg_line_with_unit.png "Linalg_line_with_unit.png"){width="800"} Now, with a scale and a direction, finding the point corresponding to, say $+2.17$, is easy--- start at $0$ and head in the direction of $1$ (i.e., the positive direction), but don\'t stop there, go $2.17$ times as far. The basic idea here, combining magnitude with direction, is the key to extending to higher dimensions. An object comprised of a magnitude and a direction is a **vector** (we will use the same word as in the previous section because we shall show below how to describe such an object with a column vector). We can draw a vector as having some length, and pointing somewhere. ![](Linalg_vectors_1.png "Linalg_vectors_1.png") There is a subtlety here--- these vectors ![](Linalg_vectors_2.png "Linalg_vectors_2.png"){width="150"} are equal, even though they start in different places, because they have equal lengths and equal directions. Again: those vectors are not just alike, they are equal. How can things that are in different places be equal? Think of a vector as representing a displacement (\"vector\" is Latin for \"carrier\" or \"traveler\"). These squares undergo the same displacement, despite that those displacements start in different places. ![](Linalg_vectors_3.png "Linalg_vectors_3.png") Sometimes, to emphasize this property vectors have of not being anchored, they are referred to as **free** vectors. Thus, these free vectors are equal as each is a displacement of one over and two up. ![](Linalg_vectors_4.png "Linalg_vectors_4.png") More generally, vectors in the plane are the same if and only if they have the same change in first components and the same change in second components: the vector extending from $(a_1,a_2)$ to $(b_1,b_2)$ equals the vector from $(c_1,c_2)$ to $(d_1,d_2)$ if and only if $b_1-a_1=d_1-c_1$ and $b_2-a_2=d_2-c_2$. An expression like \"the vector that, were it to start at $(a_1,a_2)$, would extend to $(b_1,b_2)$\" is awkward. We instead describe such a vector as $$\begin{pmatrix} b_1-a_1 \\ b_2-a_2 \end{pmatrix}$$ so that, for instance, the \"one over and two up\" arrows shown above picture this vector. $$\begin{pmatrix} 1 \\ 2 \end{pmatrix}$$ We often draw the arrow as starting at the origin, and we then say it is in the **canonical position** (or **natural position**). When the vector $$\begin{pmatrix} b_1-a_1 \\ b_2-a_2 \end{pmatrix}$$ is in its canonical position then it extends to the endpoint $(b_1-a_1,b_2-a_2)$. We typically just refer to \"the point $$\begin{pmatrix} 1 \\ 2 \end{pmatrix}$$\" rather than \"the endpoint of the canonical position of\" that vector. Thus, we will call both of these sets $\mathbb{R}^2$. $$\{(x_1,x_2)\,\big|\, x_1,x_2\in\mathbb{R}\} \qquad \{\begin{pmatrix} x_1 \\ x_2 \end{pmatrix}\,\big|\, x_1,x_2\in\mathbb{R}\}$$ In the prior section we defined vectors and vector operations with an algebraic motivation; $$r\cdot\begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = \begin{pmatrix} rv_1 \\ rv_2 \end{pmatrix} \qquad \begin{pmatrix} v_1 \\ v_2 \end{pmatrix} + \begin{pmatrix} w_1 \\ w_2 \end{pmatrix} = \begin{pmatrix} v_1+w_1 \\ v_2+w_2 \end{pmatrix}$$ we can now interpret those operations geometrically. For instance, if $\vec{v}$ represents a displacement then $3\vec{v}\,$ represents a displacement in the same direction but three times as far, and $-1\vec{v}\,$ represents a displacement of the same distance as $\vec{v}\,$ but in the opposite direction. ![](Linalg_scaled_vectors.png "Linalg_scaled_vectors.png") And, where $\vec{v}$ and $\vec{w}$ represent displacements, $\vec{v}+\vec{w}$ represents those displacements combined. ![](Linalg_vector_addition.png "Linalg_vector_addition.png") The long arrow is the combined displacement in this sense: if, in one minute, a ship\'s motion gives it the displacement relative to the earth of $\vec{v}$ and a passenger\'s motion gives a displacement relative to the ship\'s deck of $\vec{w}$, then $\vec{v}+\vec{w}$ is the displacement of the passenger relative to the earth. Another way to understand the vector sum is with the **parallelogram rule**. Draw the parallelogram formed by the vectors $\vec{v}_1,\vec{v}_2$ and then the sum $\vec{v}_1+\vec{v}_2$ extends along the diagonal to the far corner. ![](Linalg_vector_addition_2.png "Linalg_vector_addition_2.png") The above drawings show how vectors and vector operations behave in $\mathbb{R}^2$. We can extend to $\mathbb{R}^3$, or to even higher-dimensional spaces where we have no pictures, with the obvious generalization: the free vector that, if it starts at $(a_1,\ldots,a_n)$, ends at $(b_1,\ldots,b_n)$, is represented by this column $$\begin{pmatrix} b_1-a_1 \\ \vdots \\ b_n-a_n \end{pmatrix}$$ (vectors are equal if they have the same representation), we aren\'t too careful to distinguish between a point and the vector whose canonical representation ends at that point, $$\mathbb{R}^n= \{\begin{pmatrix} v_1 \\ \vdots \\ v_n \end{pmatrix}\,\big|\, v_1,\ldots,v_n\in\mathbb{R}\}$$ and addition and scalar multiplication are component-wise. Having considered points, we now turn to the lines. In $\mathbb{R}^2$, the line through $(1,2)$ and $(3,1)$ s comprised of (the endpoints of) the vectors in this set $$\{ \begin{pmatrix} 1 \\ 2 \end{pmatrix}+t\cdot\begin{pmatrix} 2 \\ -1 \end{pmatrix}\,\big|\, t\in\mathbb{R}\}$$ That description expresses this picture. ![](Linalg_vector_subtraction.png "Linalg_vector_subtraction.png") The vector associated with the parameter $t$ has its whole body in the line--- it is a **direction vector** for the line. Note that points on the line to the left of $x=1$ are described using negative values of $t$. In $\mathbb{R}^3$, the line through $(1,2,1)$ and $(2,3,2)$ is the set of (endpoints of) vectors of this form ![](Linalg_line_in_R3.png "Linalg_line_in_R3.png") and lines in even higher-dimensional spaces work in the same way. If a line uses one parameter, so that there is freedom to move back and forth in one dimension, then a plane must involve two. For example, the plane through the points $(1,0,5)$, $(2,1,-3)$, and $(-2,4,0.5)$ consists of (endpoints of) the vectors in $$\{ \begin{pmatrix} 1 \\ 0 \\ 5 \end{pmatrix} +t\cdot\begin{pmatrix} 1 \\ 1 \\ -8 \end{pmatrix} +s\cdot\begin{pmatrix} -3 \\ 4 \\ -4.5 \end{pmatrix} \,\big|\, t,s\in\mathbb{R} \}$$ (the column vectors associated with the parameters $$\begin{pmatrix} 1 \\ 1 \\ -8 \end{pmatrix} = \begin{pmatrix} 2 \\ 1 \\ -3 \end{pmatrix} - \begin{pmatrix} 1 \\ 0 \\ 5 \end{pmatrix} \qquad \begin{pmatrix} -3 \\ 4 \\ -4.5 \end{pmatrix} = \begin{pmatrix} -2 \\ 4 \\ 0.5 \end{pmatrix} - \begin{pmatrix} 1 \\ 0 \\ 5 \end{pmatrix}$$ are two vectors whose whole bodies lie in the plane). As with the line, note that some points in this plane are described with negative $t$\'s or negative $s$\'s or both. A description of planes that is often encountered in algebra and calculus uses a single equation as the condition that describes the relationship among the first, second, and third coordinates of points in a plane. ![](Linalg_plane.png "Linalg_plane.png") The translation from such a description to the vector description that we favor in this book is to think of the condition as a one-equation linear system and parametrize $x=(1/2)(4-y-z)$. ![](Linalg_plane_with_basis.png "Linalg_plane_with_basis.png") Generalizing from lines and planes, we define a **$k$-dimensional linear surface** (or **$k$-flat**) in $\mathbb{R}^n$ to be $\{\vec{p}+t_1\vec{v}_1+t_2\vec{v}_2+\cdots+t_k\vec{v}_k \,\big|\, t_1,\ldots ,t_k\in\mathbb{R}\}$ where $\vec{v}_1,\ldots,\vec{v}_k\in\mathbb{R}^n$. For example, in $\mathbb{R}^4$, $$\{\begin{pmatrix} 2 \\ \pi \\ 3 \\ -0.5 \end{pmatrix} +t\begin{pmatrix} 1 \\ 0 \\ 0 \\ 0 \end{pmatrix} \,\big|\, t\in\mathbb{R}\}$$ is a line, $$\{ \begin{pmatrix} 0 \\ 0 \\ 0 \\ 0 \end{pmatrix} +t\begin{pmatrix} 1 \\ 1 \\ 0 \\ -1 \end{pmatrix} +s\begin{pmatrix} 2 \\ 0 \\ 1 \\ 0 \end{pmatrix} \,\big|\, t,s\in\mathbb{R}\}$$ is a plane, and $$\{ \begin{pmatrix} 3 \\ 1 \\ -2 \\ 0.5 \end{pmatrix} +r\begin{pmatrix} 0 \\ 0 \\ 0 \\ -1 \end{pmatrix} +s\begin{pmatrix} 1 \\ 0 \\ 1 \\ 0 \end{pmatrix} +t\begin{pmatrix} 2 \\ 0 \\ 1 \\ 0 \end{pmatrix} \,\big|\, r,s,t\in\mathbb{R}\}$$ is a three-dimensional linear surface. Again, the intuition is that a line permits motion in one direction, a plane permits motion in combinations of two directions, etc. A linear surface description can be misleading about the dimension--- this $$L=\{ \begin{pmatrix} 1 \\ 0 \\ -1 \\ -2 \end{pmatrix} +t\begin{pmatrix} 1 \\ 1 \\ 0 \\ -1 \end{pmatrix} +s\begin{pmatrix} 2 \\ 2 \\ 0 \\ -2 \end{pmatrix} \,\big|\, t,s\in\mathbb{R}\}$$ is a **degenerate** plane because it is actually a line. $$L=\{ \begin{pmatrix} 1 \\ 0 \\ -1 \\ -2 \end{pmatrix} +r\begin{pmatrix} 1 \\ 1 \\ 0 \\ -1 \end{pmatrix} \,\big|\, r\in\mathbb{R}\}$$ We shall see in the Linear Independence section of Chapter Two what relationships among vectors causes the linear surface they generate to be degenerate. We finish this subsection by restating our conclusions from the first section in geometric terms. First, the solution set of a linear system with $n$ unknowns is a linear surface in $\mathbb{R}^n$. Specifically, it is a $k$-dimensional linear surface, where $k$ is the number of free variables in an echelon form version of the system. Second, the solution set of a homogeneous linear system is a linear surface passing through the origin. Finally, we can view the general solution set of any linear system as being the solution set of its associated homogeneous system offset from the origin by a vector, namely by any particular solution. ## Exercises ## References - . - .
# Linear Algebra/Length and Angle Measures |current=Length and Angle Measures |previous=Vectors in Space translated the first section\'s results about solution sets into geometric terms for insight into how those sets look. But we must watch out not to be mislead by our own terms; labeling subsets of $\mathbb{R}^k$ of the forms $\{\vec{p}+t\vec{v}\,\big|\, t\in\mathbb{R}\}$ and $\{\vec{p}+t\vec{v}+s\vec{w}\,\big|\, t,s\in\mathbb{R}\}$ as \"lines\" and \"planes\" doesn\'t make them act like the lines and planes of our prior experience. Rather, we must ensure that the names suit the sets. While we can\'t prove that the sets satisfy our intuition--- we can\'t prove anything about intuition--- in this subsection we\'ll observe that a result familiar from $\mathbb{R}^2$ and $\mathbb{R}^3$, when generalized to arbitrary $\mathbb{R}^k$, supports the idea that a line is straight and a plane is flat. Specifically, we\'ll see how to do Euclidean geometry in a \"plane\" by giving a definition of the angle between two $\mathbb{R}^n$ vectors in the plane that they generate. We can use that definition to derive a formula for the angle between two vectors. For a model of what to do, consider two vectors in $\mathbb{R}^3$. ```{=html} <center> ``` ![](Linalg_two_vectors_in_R3.png "Linalg_two_vectors_in_R3.png"){width="" height="200"} ```{=html} </center> ``` Put them in canonical position and, in the plane that they determine, consider the triangle formed by $\vec{u}$, $\vec{v}$, and $\vec{u}-\vec{v}$. ```{=html} <center> ``` ![](Linalg_triangle_formed_by_two_vectors.png "Linalg_triangle_formed_by_two_vectors.png"){width="" height="200"} ```{=html} </center> ``` Apply the Law of Cosines, $|\vec{u}-\vec{v}\,|^2 = |\vec{u}\,|^2+|\vec{v}\,|^2- 2\,|\vec{u}\,|\,|\vec{v}\,|\cos\theta$, where $\theta$ is the angle between the vectors. Expand both sides $$(u_1-v_1)^2+(u_2-v_2)^2+(u_3-v_3)^2$$ $$=(u_1^2+u_2^2+u_3^2)+(v_1^2+v_2^2+v_3^2)- 2\,|\vec{u}\,|\,|\vec{v}\,|\cos\theta$$ and simplify. $$\theta = \arccos(\,\frac{u_1v_1+u_2v_2+u_3v_3}{ |\vec{u}\,|\,|\vec{v}\,| }\,)$$ In higher dimensions no picture suffices but we can make the same argument analytically. First, the form of the numerator is clear--- it comes from the middle terms of the squares $(u_1-v_1)^2$, $(u_2-v_2)^2$, etc. Note that the dot product of two vectors is a real number, not a vector, and that the dot product of a vector from $\mathbb{R}^n$ with a vector from $\mathbb{R}^m$ is defined only when $n$ equals $m$. Note also this relationship between dot product and length: dotting a vector with itself gives its length squared $\vec{u}\cdot\vec{u}=u_1u_1+\cdots+u_nu_n=|\vec{u}\,|^2$. Still reasoning with letters, but guided by the pictures, we use the next theorem to argue that the triangle formed by $\vec{u}$, $\vec{v}$, and $\vec{u}-\vec{v}$ in $\mathbb{R}^n$ lies in the planar subset of $\mathbb{R}^n$ generated by $\vec{u}$ and $\vec{v}$. This inequality is the source of the familiar saying, \"The shortest distance between two points is in a straight line.\" ```{=html} <center> ``` ![](Linalg_triangle_inequality.png "Linalg_triangle_inequality.png"){width="" height="150"} ```{=html} </center> ``` This result supports the intuition that even in higher-dimensional spaces, lines are straight and planes are flat. For any two points in a linear surface, the line segment connecting them is contained in that surface (this is easily checked from the definition). But if the surface has a bend then that would allow for a shortcut (shown here grayed, while the segment from $P$ to $Q$ that is contained in the surface is solid). ```{=html} <center> ``` ![](Linalg_shortest_path_on_surface.png "Linalg_shortest_path_on_surface.png"){width="" height="150"} ```{=html} </center> ``` Because the Triangle Inequality says that in any $\mathbb{R}^n$, the shortest cut between two endpoints is simply the line segment connecting them, linear surfaces have no such bends. Back to the definition of angle measure. The heart of the Triangle Inequality\'s proof is the \"$\vec{u}\cdot\vec{v}\leq |\vec{u}\,|\,|\vec{v}\,|$\" line. At first glance, a reader might wonder if some pairs of vectors satisfy the inequality in this way: while $\vec{u}\cdot\vec{v}$ is a large number, with absolute value bigger than the right-hand side, it is a negative large number. The next result says that no such pair of vectors exists. The Cauchy-Schwarz inequality assures us that the next definition makes sense because the fraction has absolute value less than or equal to one. { \|\\vec{u}\\,\|\\,\|\\vec{v}\\,\| }\\,) `</math>`{=html} (the angle between the zero vector and any other vector is defined to be a right angle). }} Thus vectors from $\mathbb{R}^n$ are orthogonal (or perpendicular) if and only if their dot product is zero. ) =\\arccos(\\frac{3}{\\sqrt{2}\\sqrt{13}}) `</math>`{=html} approximately $0.94 \text{radians}$. Notice that these vectors are not orthogonal. Although the $yz$-plane may appear to be perpendicular to the $xy$-plane, in fact the two planes are that way only in the weak sense that there are vectors in each orthogonal to all vectors in the other. Not every vector in each is orthogonal to all vectors in the other. }} ## Exercises {\|\\vec{u}\\,\| }+\\frac{\\vec{v}}{\|\\vec{v}\\,\| } `</math>`{=html} bisects the angle between them. Illustrate in $\mathbb{R}^2$. }} `{{TextBox|1= ;Problem 27: Verify that the definition of angle is dimensionally correct: (1) if <math> k>0 </math> then the cosine of the angle between <math> k\vec{u} </math> and <math> \vec{v} </math> equals the cosine of the angle between <math> \vec{u} </math> and <math> \vec{v} </math>, and (2) if <math> k<0 </math> then the cosine of the angle between <math> k\vec{u} </math> and <math> \vec{v} </math> is the negative of the cosine of the angle between <math> \vec{u} </math> and <math> \vec{v} </math>. }}`{=mediawiki} `{{TextBox|1= ;Problem 28: Show that the inner product operation is '''linear''': for <math> \vec{u},\vec{v},\vec{w}\in\mathbb{R}^n </math> and <math> k,m\in\mathbb{R} </math>, <math>\vec{u}\cdot(k\vec{v}+m\vec{w})= k(\vec{u}\cdot\vec{v})+m(\vec{u}\cdot\vec{w})</math>. }}`{=mediawiki} `{{TextBox|1= ;Problem 29{{anchor|arithmetic geometric mean inequality}}: The '''geometric mean''' of two positive reals <math> x, y </math> is <math> \sqrt{xy} </math>. It is analogous to the '''arithmetic mean''' <math> (x+y)/2 </math>. Use the Cauchy-Schwarz inequality to show that the geometric mean of any <math> x,y\in\mathbb{R} </math> is less than or equal to the arithmetic mean. }}`{=mediawiki} `{{TextBox|1= ;? Problem 30: A ship is sailing with speed and direction <math> \vec{v}_1 </math>; the wind blows apparently (judging by the vane on the mast) in the direction of a vector <math> \vec{a} </math>; on changing the direction and speed of the ship from <math> \vec{v}_1 </math> to <math> \vec{v}_2 </math> the apparent wind is in the direction of a vector <math> \vec{b} </math>. Find the vector velocity of the wind {{harv|Ivanoff|Esty|1933}}. }}`{=mediawiki} `{{TextBox|1= ;Problem 31: Verify the Cauchy-Schwarz inequality by first proving Lagrange's identity: :<math> \left(\sum_{1\leq j\leq n} a_jb_j \right)^2 = \left(\sum_{1\leq j\leq n}a_j^2\right) \left(\sum_{1\leq j\leq n}b_j^2\right) - \sum_{1\leq k < j\leq n}(a_kb_j-a_jb_k)^2 </math> and then noting that the final term is positive. (Recall the meaning :<math> \sum_{1\leq j\leq n}a_jb_j= a_1b_1+a_2b_2+\cdots+a_nb_n </math> and :<math> \sum_{1\leq j\leq n}{a_j}^2= {a_1}^2+{a_2}^2+\cdots+{a_n}^2 </math> of the <math> \Sigma </math> notation.) This result is an improvement over Cauchy-Schwarz because it gives a formula for the difference between the two sides. Interpret that difference in <math> \mathbb{R}^2 </math>. /Solutions/ ## References - - -
# Linear Algebra/Reduced Echelon Form |current=Reduced Echelon Form |previous=Length and Angle Measures developing the mechanics of Gauss\' method, we observed that it can be done in more than one way. One example is that we sometimes have to swap rows and there can be more than one row to choose from. Another example is that from this matrix $$\begin{pmatrix} 2 &2 \\ 4 &3 \end{pmatrix}$$ Gauss\' method could derive any of these echelon form matrices. $$\begin{pmatrix} 2 &2 \\ 0 &-1 \end{pmatrix} \qquad \begin{pmatrix} 1 &1 \\ 0 &-1 \end{pmatrix} \qquad \begin{pmatrix} 2 &0 \\ 0 &-1 \end{pmatrix}$$ The first results from $-2\rho_1+\rho_2$. The second comes from following $(1/2)\rho_1$ with $-4\rho_1+\rho_2$. The third comes from $-2\rho_1+\rho_2$ followed by $2\rho_2+\rho_1$ (after the first pivot the matrix is already in echelon form so the second one is extra work but it is nonetheless a legal row operation). The fact that the echelon form outcome of Gauss\' method is not unique leaves us with some questions. Will any two echelon form versions of a system have the same number of free variables? Will they in fact have exactly the same variables free? In this section we will answer both questions \"yes\". We will do more than answer the questions. We will give a way to decide if one linear system can be derived from another by row operations. The answers to the two questions will follow from this |current=Reduced Echelon Form |previous=Length and Angle Measures |next=Gauss-Jordan Reduction}}`{=mediawiki}
# Linear Algebra/Gauss-Jordan Reduction |current=Gauss-Jordan Reduction |previous=Reduced Echelon Form elimination coupled with back-substitution solves linear systems, but it\'s not the only method possible. Here is an extension of Gauss\' method that has some advantages. Note that the pivot operations in the first stage proceed from column one to column three while the pivot operations in the third stage proceed from column three to column one. This extension of Gauss\' method is **Gauss-Jordan reduction**. It goes past echelon form to a more refined, more specialized, matrix form. The disadvantage of using Gauss-Jordan reduction to solve a system is that the additional row operations mean additional arithmetic. The advantage is that the solution set can just be read off. In any echelon form, plain or reduced, we can read off when a system has an empty solution set because there is a contradictory equation, we can read off when a system has a one-element solution set because there is no contradiction and every variable is the leading variable in some row, and we can read off when a system has an infinite solution set because there is no contradiction and at least one variable is free. In reduced echelon form we can read off not just what kind of solution set the system has, but also its description. Whether or not the echelon form is reduced, we have no trouble describing the solution set when it is empty, of course. The two examples above show that when the system has a single solution then the solution can be read off from the right-hand column. In the case when the solution set is infinite, its parametrization can also be read off of the reduced echelon form. Consider, for example, this system that is shown brought to echelon form and then to reduced echelon form. $$\left(\begin{array}{cccc|c} 2 &6 &1 &2 &5 \\ 0 &3 &1 &4 &1 \\ 0 &3 &1 &2 &5 \end{array}\right) \xrightarrow[]{-\rho_2+\rho_3} \left(\begin{array}{cccc|c} 2 &6 &1 &2 &5 \\ 0 &3 &1 &4 &1 \\ 0 &0 &0 &-2 &4 \end{array}\right)$$ $$\xrightarrow[\begin{array}{c}\\[-19pt]\scriptstyle (1/3)\rho_2 \\[-5pt]\scriptstyle -(1/2)\rho_3\end{array}]{(1/2)\rho_1} \;\xrightarrow[-\rho_3+\rho_1]{(4/3)\rho_3+\rho_2} \;\xrightarrow[]{-3\rho_2+\rho_1} \left(\begin{array}{cccc|c} 1 &0 &-1/2 &0 &-9/2 \\ 0 &1 &1/3 &0 &3 \\ 0 &0 &0 &1 &-2 \end{array}\right)$$ Starting with the middle matrix, the echelon form version, back substitution produces $-2x_4=4$ so that $x_4=-2$, then another back substitution gives $3x_2+x_3+4(-2)=1$ implying that $x_2=3-(1/3)x_3$, and then the final back substitution gives $2x_1+6(3-(1/3)x_3)+x_3+2(-2)=5$ implying that $x_1=-(9/2)+(1/2)x_3$. Thus the solution set is this. $$S=\{\begin{pmatrix} x_1 \\ x_2 \\ x_3 \\ x_4 \end{pmatrix} =\begin{pmatrix} -9/2 \\ 3 \\ 0 \\ -2 \end{pmatrix} +\begin{pmatrix} 1/2 \\ -1/3 \\ 1 \\ 0 \end{pmatrix}x_3 \,\big|\, x_3\in\mathbb{R}\}$$ Now, considering the final matrix, the reduced echelon form version, note that adjusting the parametrization by moving the $x_3$ terms to the other side does indeed give the description of this infinite solution set. Part of the reason that this works is straightforward. While a set can have many parametrizations that describe it, e.g., both of these also describe the above set $S$ (take $t$ to be $x_3/6$ and $s$ to be $x_3-1$) $$\{\begin{pmatrix} -9/2 \\ 3 \\ 0 \\ -2 \end{pmatrix} +\begin{pmatrix} 3 \\ -2 \\ 6 \\ 0 \end{pmatrix}t \,\big|\, t\in\mathbb{R}\} \qquad \{\begin{pmatrix} -4 \\ 8/3 \\ 1 \\ -2 \end{pmatrix} +\begin{pmatrix} 1/2 \\ -1/3 \\ 1 \\ 0 \end{pmatrix}s \,\big|\, s\in\mathbb{R}\}$$ nonetheless we have in this book stuck to a convention of parametrizing using the unmodified free variables (that is, $x_3=x_3$ instead of $x_3=6t$). We can easily see that a reduced echelon form version of a system is equivalent to a parametrization in terms of unmodified free variables. For instance, $$\begin{array}{rl} x_1 &=4-2x_3 \\ x_2 &=3-x_3 \end{array} \quad\Longleftrightarrow\quad \left(\begin{array}{ccc|c} 1 &0 &2 &4 \\ 0 &1 &1 &3 \\ 0 &0 &0 &0 \end{array}\right)$$ (to move from left to right we also need to know how many equations are in the system). So, the convention of parametrizing with the free variables by solving each equation for its leading variable and then eliminating that leading variable from every other equation is exactly equivalent to the reduced echelon form conditions that each leading entry must be a one and must be the only nonzero entry in its column. Not as straightforward is the other part of the reason that the reduced echelon form version allows us to read off the parametrization that we would have gotten had we stopped at echelon form and then done back substitution. The prior paragraph shows that reduced echelon form corresponds to some parametrization, but why the same parametrization? A solution set can be parametrized in many ways, and Gauss\' method or the Gauss-Jordan method can be done in many ways, so a first guess might be that we could derive many different reduced echelon form versions of the same starting system and many different parametrizations. But we never do. Experience shows that starting with the same system and proceeding with row operations in many different ways always yields the same reduced echelon form and the same parametrization (using the unmodified free variables). In the rest of this section we will show that the reduced echelon form version of a matrix is unique. It follows that the parametrization of a linear system in terms of its unmodified free variables is unique because two different ones would give two different reduced echelon forms. We shall use this result, and the ones that lead up to it, in the rest of the book but perhaps a restatement in a way that makes it seem more immediately useful may be encouraging. Imagine that we solve a linear system, parametrize, and check in the back of the book for the answer. But the parametrization there appears different. Have we made a mistake, or could these be different-looking descriptions of the same set, as with the three descriptions above of $S$? The prior paragraph notes that we will show here that different-looking parametrizations (using the unmodified free variables) describe genuinely different sets. Here is an informal argument that the reduced echelon form version of a matrix is unique. Consider again the example that started this section of a matrix that reduces to three different echelon form matrices. The first matrix of the three is the natural echelon form version. The second matrix is the same as the first except that a row has been halved. The third matrix, too, is just a cosmetic variant of the first. The definition of reduced echelon form outlaws this kind of fooling around. In reduced echelon form, halving a row is not possible because that would change the row\'s leading entry away from one, and neither is combining rows possible, because then a leading entry would no longer be alone in its column. This informal justification is not a proof; we have argued that no two different reduced echelon form matrices are related by a single row operation step, but we have not ruled out the possibility that multiple steps might do. Before we go to that proof, we finish this subsection by rephrasing our work in a terminology that will be enlightening. Many different matrices yield the same reduced echelon form matrix. The three echelon form matrices from the start of this section, and the matrix they were derived from, all give this reduced echelon form matrix. $$\begin{pmatrix} 1 &0 \\ 0 &1 \end{pmatrix}$$ We think of these matrices as related to each other. The next result speaks to this relationship. This lemma suggests that \"reduces to\" is misleading--- where $A\longrightarrow B$, we shouldn\'t think of $B$ as \"after\" $A$ or \"simpler than\" $A$. Instead we should think of them as interreducible or interrelated. Below is a picture of the idea. The matrices from the start of this section and their reduced echelon form version are shown in a cluster. They are all interreducible; these relationships are shown also. ```{=html} <center> ``` ![](Linalg_interreducible_matrices.png "Linalg_interreducible_matrices.png"){width="" height="200"} ```{=html} </center> ``` We say that matrices that reduce to each other are \"equivalent with respect to the relationship of row reducibility\". The next result verifies this statement using the definition of an equivalence.[^1] The diagram below shows the collection of all matrices as a box. Inside that box, each matrix lies in some class. Matrices are in the same class if and only if they are interreducible. The classes are disjoint--- no matrix is in two distinct classes. The collection of matrices has been partitioned into **row equivalence classes**.[^2] ```{=html} <center> ``` ![](Linalg_row_equiv_classes.png "Linalg_row_equiv_classes.png"){width="" height="200"} ```{=html} </center> ``` One of the classes in this partition is the cluster of matrices shown above, expanded to include all of the nonsingular $2 \! \times \! 2$ matrices. The next subsection proves that the reduced echelon form of a matrix is unique; that every matrix reduces to one and only one reduced echelon form matrix. Rephrased in terms of the row-equivalence relationship, we shall prove that every matrix is row equivalent to one and only one reduced echelon form matrix. In terms of the partition what we shall prove is: every equivalence class contains one and only one reduced echelon form matrix. So each reduced echelon form matrix serves as a representative of its class. After that proof we shall, as mentioned in the introduction to this section, have a way to decide if one matrix can be derived from another by row reduction. We just apply the Gauss-Jordan procedure to both and see whether or not they come to the same reduced echelon form. ## Exercises ## Footnotes ```{=html} <references/> ``` |current=Gauss-Jordan Reduction |previous=Reduced Echelon Form |next=Row Equivalence}}`{=mediawiki} [^1]: More information on equivalence relations is in the appendix. [^2]: More information on partitions and class representatives is in the appendix.
# Linear Algebra/Row Equivalence |current=Row Equivalence |previous=Gauss-Jordan Reduction We will close this section and this chapter by proving that every matrix is row equivalent to one and only one reduced echelon form matrix. The ideas that appear here will reappear, and be further developed, in the next chapter. The underlying theme here is that one way to understand a mathematical situation is by being able to classify the cases that can happen. We have met this theme several times already. We have classified solution sets of linear systems into the no-elements, one-element, and infinitely-many elements cases. We have also classified linear systems with the same number of equations as unknowns into the nonsingular and singular cases. We adopted these classifications because they give us a way to understand the situations that we were investigating. Here, where we are investigating row equivalence, we know that the set of all matrices breaks into the row equivalence classes. When we finish the proof here, we will have a way to understand each of those classes--- its matrices can be thought of as derived by row operations from the unique reduced echelon form matrix in that class. To understand how row operations act to transform one matrix into another, we consider the effect that they have on the parts of a matrix. The crucial observation is that row operations combine the rows linearly. (We have already used the phrase \"linear combination\" in this book. The meaning is unchanged, but the next result\'s statement makes a more formal definition in order.) In this subsection we will use the convention that, where a matrix is named with an upper case roman letter, the matching lower-case greek letter names the rows. $$A= \begin{pmatrix} \cdots \alpha_1 \cdots \\ \cdots \alpha_2 \cdots \\ \vdots \\ \cdots \alpha_m \cdots \end{pmatrix} \qquad B= \begin{pmatrix} \cdots \beta_1 \cdots \\ \cdots \beta_2 \cdots \\ \vdots \\ \cdots \beta_m\cdots \end{pmatrix}$$ The proof below uses induction on the number of row operations used to reduce one matrix to the other. Before we proceed, here is an outline of the argument (readers unfamiliar with induction may want to compare this argument with the one used in the \"$\text{General}=\text{Particular}+\text{Homogeneous}$\" proof).[^1] First, for the base step of the argument, we will verify that the proposition is true when reduction can be done in zero row operations. Second, for the inductive step, we will argue that if being able to reduce the first matrix to the second in some number $t\geq 0$ of operations implies that each row of the second is a linear combination of the rows of the first, then being able to reduce the first to the second in $t+1$ operations implies the same thing. Together, this base step and induction step prove this result because by the base step the proposition is true in the zero operations case, and by the inductive step the fact that it is true in the zero operations case implies that it is true in the one operation case, and the inductive step applied again gives that it is therefore true in the two operations case, etc. The prior result gives us the insight that Gauss\' method works by taking linear combinations of the rows. But to what end; why do we go to echelon form as a particularly simple, or basic, version of a linear system? The answer, of course, is that echelon form is suitable for back substitution, because we have isolated the variables. For instance, in this matrix $$R=\begin{pmatrix} 2 &3 &7 &8 &0 &0 \\ 0 &0 &1 &5 &1 &1 \\ 0 &0 &0 &3 &3 &0 \\ 0 &0 &0 &0 &2 &1 \end{pmatrix}$$ $x_1$ has been removed from $x_5$\'s equation. That is, Gauss\' method has made $x_5$\'s row independent of $x_1$\'s row. Independence of a collection of row vectors, or of any kind of vectors, will be precisely defined and explored in the next chapter. But a first take on it is that we can show that, say, the third row above is not comprised of the other rows, that $\rho_3\neq c_1\rho_1+c_2\rho_2+c_4\rho_4$. For, suppose that there are scalars $c_1$, $c_2$, and $c_4$ such that this relationship holds. $$\begin{array}{rl} \begin{pmatrix} 0 &0 &0 &3 &3 &0 \end{pmatrix} &=c_1\begin{pmatrix} 2 &3 &7 &8 &0 &0 \end{pmatrix} \\ &\quad+c_2\begin{pmatrix} 0 &0 &1 &5 &1 &1 \end{pmatrix} \\ &\quad+c_4\begin{pmatrix} 0 &0 &0 &0 &2 &1 \end{pmatrix} \end{array}$$ The first row\'s leading entry is in the first column and narrowing our consideration of the above relationship to consideration only of the entries from the first column $0=2c_1+0c_2+0c_4$ gives that $c_1=0$. The second row\'s leading entry is in the third column and the equation of entries in that column $0=7c_1+1c_2+0c_4$, along with the knowledge that $c_1=0$, gives that $c_2=0$. Now, to finish, the third row\'s leading entry is in the fourth column and the equation of entries in that column $3=8c_1+5c_2+0c_4$, along with $c_1=0$ and $c_2=0$, gives an impossibility. The following result shows that this effect always holds. It shows that what Gauss\' linear elimination method eliminates is linear relationships among the rows. We can now prove that each matrix is row equivalent to one and only one reduced echelon form matrix. We will find it convenient to break the first half of the argument off as a preliminary lemma. For one thing, it holds for any echelon form whatever, not just reduced echelon form. For the proof we rephrase the result in more technical terms. Define the **form** of an $m \! \times \! n$ matrix to be the sequence $\langle \ell_1,\ell_2,\ldots\,,\ell_m \rangle$ where $\ell_i$ is the column number of the leading entry in row $i$ and $\ell_i=\infty$ if there is no leading entry in that row. The lemma says that if two echelon form matrices are row equivalent then their forms are equal sequences. That lemma answers two of the questions that we have posed: (i) any two echelon form versions of a matrix have the same free variables, and consequently, and (ii) any two echelon form versions have the same number of free variables. There is no linear system and no combination of row operations such that, say, we could solve the system one way and get $y$ and $z$ free but solve it another way and get $y$ and $w$ free, or solve it one way and get two free variables while solving it another way yields three. We finish now by specializing to the case of reduced echelon form matrices. We end with a recap. In Gauss\' method we start with a matrix and then derive a sequence of other matrices. We defined two matrices to be related if one can be derived from the other. That relation is an equivalence relation, called row equivalence, and so partitions the set of all matrices into row equivalence classes. ```{=html} <center> ``` ![](Linalg_reduced_echelon_form_equiv_classes.png "Linalg_reduced_echelon_form_equiv_classes.png"){width="" height="200"} ```{=html} </center> ``` (There are infinitely many matrices in the pictured class, but we\'ve only got room to show two.) We have proved there is one and only one reduced echelon form matrix in each row equivalence class. So the reduced echelon form is a *canonical form*[^2] for row equivalence: the reduced echelon form matrices are representatives of the classes. ```{=html} <center> ``` ![](Linalg_reduced_echelon_form_equiv_classes_2.png "Linalg_reduced_echelon_form_equiv_classes_2.png"){width="" height="200"} ```{=html} </center> ``` We can answer questions about the classes by translating them into questions about the representatives. ## Exercises ## Footnotes ```{=html} <references/> ``` ## References - - [^1]: More information on mathematical induction is in the appendix. [^2]: More information on canonical representatives is in the appendix.
# Linear Algebra/Topic: Computer Algebra Systems |current=Topic: Computer Algebra Systems |previous=Row Equivalence The linear systems in this chapter are small enough that their solution by hand is easy. But large systems are easiest, and safest, to do on a computer. There are special purpose programs such as LINPACK for this job. Another popular tool is a general purpose computer algebra system, including both commercial packages such as Maple, Mathematica, or MATLAB, or free packages such as SciLab, Sage, or Octave. For example, in the Topic on Networks, we need to solve this. $$\begin{array}{*{7}{rc}r} i_0 &- &i_1 &- &i_2 & & & & & & & & &= &0 \\ & &i_1 & & &- &i_3 & & &- &i_5 & & &= &0 \\ & & & &i_2 & & &- &i_4 &+ &i_5 & & &= &0 \\ & & & & & &i_3 &+ &i_4 & & &- &i_6 &= &0 \\ & &5i_1 & & &+ &10i_3 & & & & & & &= &10 \\ & & & &2i_2 & & &+ &4i_4 & & & & &= &10 \\ & &5i_1 &- &2i_2 & & & & &+ &50i_5 && &= &0 \end{array}$$ It can be done by hand, but it would take a while and be error-prone. Using a computer is better. We illustrate by solving that system under Maple (for another system, a user\'s manual would obviously detail the exact syntax needed). The array of coefficients can be entered in this way \ `> A:=array( [[1,-1,-1,0,0,0,0],`\ `[0,1,0,-1,0,-1,0],`\ `[0,0,1,0,-1,1,0],`\ `[0,0,0,1,1,0,-1],`\ `[0,5,0,10,0,0,0],`\ `[0,0,2,0,4,0,0],`\ `[0,5,-2,0,0,50,0]] );`\ \ (putting the rows on separate lines is not necessary, but is done for clarity). The vector of constants is entered similarly. \ `> u:=array( [0,0,0,0,10,10,0] );`\ \ Then the system is solved, like magic. \ `> linsolve(A,u);`\ `7 2 5 2 5 7`\ `[ -, -, -, -, -, 0, - ]`\ `3 3 3 3 3 3`\ \ Mathematica can solve this with ``` mathematica RowReduce[({{1, -1, -1, 0, 0, 0, 0, 0}, {0, 1, 0, -1, 0, -1, 0, 0}, {0, 0, 1, 0, -1, 1, 0, 0}, {0, 0, 0, 1, 1, 0, -1, 0}, {0, 5, 0, 10, 0, 0, 0, 10}, {0, 0, 2, 0, 4, 0, 0, 10}, {0, 5, -2, 0, 0, 50, 0, 0}})] ``` This returns the following output: ``` mathematica {{1, 0, 0, 0, 0, 0, 0, 7/3}, {0, 1, 0, 0, 0, 0, 0, 2/3}, {0, 0, 1, 0, 0, 0, 0, 5/3}, {0, 0, 0, 1, 0, 0, 0, 2/3}, {0, 0, 0, 0, 1, 0, 0, 5/ 3}, {0, 0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 7/3}} ``` Systems with infinitely many solutions are solved in the same way--- the computer simply returns a parametrization. ## Exercises *Answers for this Topic use Maple as the computer algebra system. In particular, all of these were tested on Maple V running under MS-DOS NT version 4.0. (On all of them, the preliminary command to load the linear algebra package along with Maple\'s responses to the Enter key, have been omitted.) Other systems have similar commands.* `{{TextBox|1= ;Problem 1: Use the computer to solve the two problems that opened this chapter. <ol type=1 start=1> <li> This is the Statics problem. :<math>\begin{array}{rl} 40h+15c &= 100 \\ 25c &= 50+50h \end{array}</math> <li> This is the Chemistry problem. :<math>\begin{array}{rl} 7h &= 7j \\ 8h +1i &= 5j+2k \\ 1i &= 3j \\ 3i &= 6j+1k \end{array}</math> </ol> }}`{=mediawiki} `{{TextBox|1= ;Problem 2: Use the computer to solve these systems from the first subsection, or conclude "many solutions" or "no solutions". <ol type=1 start=1> <li> <math> \begin{array}{*{2}{rc}r} 2x &+ &2y &= &5 \\ x &- &4y &= &0 \end{array} </math> <li> <math> \begin{array}{*{2}{rc}r} -x &+ &y &= &1 \\ x &+ &y &= &2 \end{array} </math> <li> <math> \begin{array}{*{3}{rc}r} x &- &3y &+ &z &= &1 \\ x &+ &y &+ &2z &= &14 \end{array} </math> <li> <math> \begin{array}{*{2}{rc}r} -x &- &y &= &1 \\ -3x &- &3y &= &2 \end{array} </math> <li> <math> \begin{array}{*{3}{rc}r} & &4y &+ &z &= &20 \\ 2x &- &2y &+ &z &= &0 \\ x & & &+ &z &= &5 \\ x &+ &y &- &z &= &10 \end{array} </math> <li> <math> \begin{array}{*{4}{rc}r} 2x & & &+ &z &+ &w &= &5 \\ & &y & & &- &w &= &-1 \\ 3x & & &- &z &- &w &= &0 \\ 4x &+ &y &+ &2z &+ &w &= &9 \end{array} </math> </ol> }}`{=mediawiki} `{{TextBox|1= ;Problem 3: Use the computer to solve these systems from the second subsection. <ol type=1 start=1> <li> <math> \begin{array}{*{2}{rc}r} 3x &+ &6y &= &18 \\ x &+ &2y &= &6 \end{array} </math> <li> <math> \begin{array}{*{2}{rc}r} x &+ &y &= &1 \\ x &- &y &= &-1 \end{array} </math> <li> <math> \begin{array}{*{3}{rc}r} x_1 & & &+ &x_3 &= &4 \\ x_1 &- &x_2 &+ &2x_3 &= &5 \\ 4x_1 &- &x_2 &+ &5x_3 &= &17 \end{array} </math> <li> <math> \begin{array}{*{3}{rc}r} 2a &+ &b &- &c &= &2 \\ 2a & & &+ &c &= &3 \\ a &- &b & & &= &0 \end{array} </math> <li> <math> \begin{array}{*{4}{rc}r} x &+ &2y &- &z & & &= &3 \\ 2x &+ &y & & &+ &w &= &4 \\ x &- &y &+ &z &+ &w &= &1 \end{array} </math> <li> <math> \begin{array}{*{4}{rc}r} x & & &+ &z &+ &w &= &4 \\ 2x &+ &y & & &- &w &= &2 \\ 3x &+ &y &+ &z & & &= &7 \end{array} </math> </ol> }}`{=mediawiki} `{{TextBox|1= ;Problem 4: What does the computer give for the solution of the general <math>2 \! \times \! 2</math> system? :<math> \begin{array}{*{2}{rc}r} ax &+ &cy &= &p \\ bx &+ &dy &= &q \end{array} </math> /Solutions/
# Linear Algebra/Topic: Input-Output Analysis |current=Topic: Input-Output Analysis |previous=Topic: Computer Algebra Systems An economy is an immensely complicated network of interdependences. Changes in one part can ripple out to affect other parts. Economists have struggled to be able to describe, and to make predictions about, such a complicated object. Mathematical models using systems of linear equations have emerged as a key tool. One is Input-Output Analysis, pioneered by W. Leontief, who won the 1973 Nobel Prize in Economics. Consider an economy with many parts, two of which are the steel industry and the auto industry. As they work to meet the demand for their product from other parts of the economy, that is, from users external to the steel and auto sectors, these two interact tightly. For instance, should the external demand for autos go up, that would lead to an increase in the auto industry\'s usage of steel. Or, should the external demand for steel fall, then it would lead to a fall in steel\'s purchase of autos. The type of Input-Output model we will consider takes in the external demands and then predicts how the two interact to meet those demands. We start with a listing of production and consumption statistics. (These numbers, giving dollar values in millions, are excerpted from , describing the 1958 U.S. economy. Today\'s statistics would be quite different, both because of inflation and because of technical changes in the industries.) ```{=html} <center> ``` +-----------------+----------------+----------------+----------------+-------------+ | |   *used by*  \ |   *used by*  \ |   *used by*  \ |   *total*   | | |   *steel*   |   *auto*   |   *others*   | | +-----------------+----------------+----------------+----------------+-------------+ |   *value of*  \ |   5 395   |   2 664   | |   25 448   | |   *steel*   | | | | | +-----------------+----------------+----------------+----------------+-------------+ |   *value of*  \ |   48   |   9 030   | |   30 346   | |   *auto*   | | | | | +-----------------+----------------+----------------+----------------+-------------+ ```{=html} </center> ``` For instance, the dollar value of steel used by the auto industry in this year is $2,664$ million. Note that industries may consume some of their own output. We can fill in the blanks for the external demand. This year\'s value of the steel used by others this year is $17,389$ and this year\'s value of the auto used by others is $21,268$. With that, we have a complete description of the external demands and of how auto and steel interact, this year, to meet them. Now, imagine that the external demand for steel has recently been going up by $200$ per year and so we estimate that next year it will be $17,589$. Imagine also that for similar reasons we estimate that next year\'s external demand for autos will be down $25$ to $21,243$. We wish to predict next year\'s total outputs. That prediction isn\'t as simple as adding $200$ to this year\'s steel total and subtracting $25$ from this year\'s auto total. For one thing, a rise in steel will cause that industry to have an increased demand for autos, which will mitigate, to some extent, the loss in external demand for autos. On the other hand, the drop in external demand for autos will cause the auto industry to use less steel, and so lessen somewhat the upswing in steel\'s business. In short, these two industries form a system, and we need to predict the totals at which the system as a whole will settle. For that prediction, let $s$ be next years total production of steel and let $a$ be next year\'s total output of autos. We form these equations. $$\begin{array}{rl} \text{next year}\textrm{'}\text{s production of steel} &=\text{next year}\textrm{'}\text{s use of steel by steel} \\ &\quad+\text{next year}\textrm{'}\text{s use of steel by auto} \\ &\quad+\text{next year}\textrm{'}\text{s use of steel by others} \\ \text{next year}\textrm{'}\text{s production of autos} &=\text{next year}\textrm{'}\text{s use of autos by steel} \\ &\quad+\text{next year}\textrm{'}\text{s use of autos by auto} \\ &\quad+\text{next year}\textrm{'}\text{s use of autos by others} \end{array}$$ On the left side of those equations go the unknowns $s$ and $a$. At the ends of the right sides go our external demand estimates for next year $17,589$ and $21,243$. For the remaining four terms, we look to the table of this year\'s information about how the industries interact. For instance, for next year\'s use of steel by steel, we note that this year the steel industry used $5395$ units of steel input to produce $25,448$ units of steel output. So next year, when the steel industry will produce $s$ units out, we expect that doing so will take $s\cdot (5395)/(25\,448)$ units of steel input--- this is simply the assumption that input is proportional to output. (We are assuming that the ratio of input to output remains constant over time; in practice, models may try to take account of trends of change in the ratios.) Next year\'s use of steel by the auto industry is similar. This year, the auto industry uses $2664$ units of steel input to produce $30346$ units of auto output. So next year, when the auto industry\'s total output is $a$, we expect it to consume $a\cdot (2664)/(30346)$ units of steel. Filling in the other equation in the same way, we get this system of linear equation. $$\begin{array}{*{3}{rc}r} {\displaystyle\frac{5\,395}{25\,448}}\cdot s &+ &{\displaystyle\frac{2\,664}{30\,346}}\cdot a &+ &17\,589 &= &s \\[1em] {\displaystyle\frac{48}{25\,448}}\cdot s &+ &{\displaystyle\frac{9\,030}{30\,346}}\cdot a &+ &21\,243 &= &a \end{array}$$ Gauss\' method on this system. $$\begin{array}{*{2}{rc}r} (20\,053/25\,448)s &- &(2\,664/30\,346)a &= &17\,589 \\ -(48/25\,448)s &+ &(21\,316/30\,346)a &= &21\,243 \end{array}$$ gives $s=25\,698$ and $a=30\,311$. Looking back, recall that above we described why the prediction of next year\'s totals isn\'t as simple as adding $200$ to last year\'s steel total and subtracting $25$ from last year\'s auto total. In fact, comparing these totals for next year to the ones given at the start for the current year shows that, despite the drop in external demand, the total production of the auto industry is predicted to rise. The increase in internal demand for autos caused by steel\'s sharp rise in business more than makes up for the loss in external demand for autos. One of the advantages of having a mathematical model is that we can ask \"What if \...?\" questions. For instance, we can ask \"What if the estimates for next year\'s external demands are somewhat off?\" To try to understand how much the model\'s predictions change in reaction to changes in our estimates, we can try revising our estimate of next year\'s external steel demand from $17,589$ down to $17,489$, while keeping the assumption of next year\'s external demand for autos fixed at $21,243$. The resulting system $$\begin{array}{*{2}{rc}r} (20\,053/25\,448)s &- &(2\,664/30\,346)a &= &17\,489 \\ -(48/25\,448)s &+ &(21\,316/30\,346)a &= &21\,243 \end{array}$$ when solved gives $s=25\,571$ and $a=30\,311$. This kind of exploration of the model is **sensitivity analysis**. We are seeing how sensitive the predictions of our model are to the accuracy of the assumptions. Obviously, we can consider larger models that detail the interactions among more sectors of an economy. These models are typically solved on a computer, using the techniques of matrix algebra that we will develop in Chapter Three. Some examples are given in the exercises. Obviously also, a single model does not suit every case; expert judgment is needed to see if the assumptions underlying the model are reasonable for a particular case. With those caveats, however, this model has proven in practice to be a useful and accurate tool for economic analysis. For further reading, try and . ## Exercises *Hint: these systems are easiest to solve on a computer.* `{{TextBox|1= ;Problem 3: This table gives the numbers for the auto-steel system from a different year, 1947 (see {{harvnb|Leontief|1951}}). The units here are billions of 1947 dollars. <center> <TABLE style="text-align:center;" border=0px cellpadding=0px cellspacing=0px> <TR> <TD style="border-right:2px solid black; border-bottom:2px solid black;"> <TD style="border-bottom:2px solid black;">&nbsp;&nbsp;''used by''&nbsp;&nbsp;<br>&nbsp;&nbsp;''steel''&nbsp;&nbsp; <TD style="border-bottom:2px solid black;">&nbsp;&nbsp;''used by''&nbsp;&nbsp; <br>&nbsp;&nbsp;''auto''&nbsp;&nbsp; <TD style="border-bottom:2px solid black;">&nbsp;&nbsp;''used by''&nbsp;&nbsp;<br>&nbsp;&nbsp;''others''&nbsp;&nbsp; <TD style="border-bottom:2px solid black;">&nbsp;&nbsp;''total''&nbsp;&nbsp; <TR> <TD style="border-right:2px solid black;"> &nbsp;&nbsp;''value of''&nbsp;&nbsp;<br>&nbsp;&nbsp;''steel''&nbsp;&nbsp; <TD>&nbsp;&nbsp;6.90&nbsp;&nbsp; <TD>&nbsp;&nbsp;1.28&nbsp;&nbsp; <TD> <TD>&nbsp;&nbsp;18.69&nbsp;&nbsp; <TR> <TD style="border-right:2px solid black;">&nbsp;&nbsp;''value of''&nbsp;&nbsp;<br>&nbsp;&nbsp;''auto''&nbsp;&nbsp; <TD>&nbsp;&nbsp;0&nbsp;&nbsp; <TD>&nbsp;&nbsp;4.40&nbsp;&nbsp; <TD> <TD>&nbsp;&nbsp;14.27&nbsp;&nbsp; </TABLE> </center> <ol type=1 start=1> <li> Solve for total output if next year's external demands are: steel's demand up 10% and auto's demand up 15%. <li> How do the ratios compare to those given above in the discussion for the 1958 economy? <li> Solve the 1947 equations with the 1958 external demands (note the difference in units; a 1947 dollar buys about what $1.30 in 1958 dollars buys). How far off are the predictions for total output? </ol> }}`{=mediawiki} `{{TextBox|1= ;Problem 5: This table gives the interrelationships among three segments of an economy (see {{harvnb|Clark|Coupe|1967}}). <center> <TABLE style="text-align:center;" border=0px cellpadding=0px cellspacing=0px> <TR> <TD style="border-right:2px solid black; border-bottom:2px solid black;"> <TD style="border-bottom:2px solid black;">&nbsp;&nbsp;''used by''&nbsp;&nbsp;<br>&nbsp;&nbsp;''food''&nbsp;&nbsp; <TD style="border-bottom:2px solid black;">&nbsp;&nbsp;''used by''&nbsp;&nbsp; <br>&nbsp;&nbsp;''wholesale''&nbsp;&nbsp; <TD style="border-bottom:2px solid black;">&nbsp;&nbsp;''used by''&nbsp;&nbsp; <br>&nbsp;&nbsp;''retail''&nbsp;&nbsp; <TD style="border-bottom:2px solid black;">&nbsp;&nbsp;''used by''&nbsp;&nbsp;<br>&nbsp;&nbsp;''others''&nbsp;&nbsp; <TD style="border-bottom:2px solid black;">&nbsp;&nbsp;''total''&nbsp;&nbsp; <TR> <TD style="border-right:2px solid black;"> &nbsp;&nbsp;''value of''&nbsp;&nbsp;<br>&nbsp;&nbsp;''food''&nbsp;&nbsp; <TD>&nbsp;&nbsp;0&nbsp;&nbsp; <TD>&nbsp;&nbsp;2&thinsp;318&nbsp;&nbsp; <TD>&nbsp;&nbsp;4&thinsp;679&nbsp;&nbsp; <TD> <TD>&nbsp;&nbsp;11&thinsp;869&nbsp;&nbsp; <TR> <TD style="border-right:2px solid black;">&nbsp;&nbsp;''value of''&nbsp;&nbsp;<br>&nbsp;&nbsp;''wholesale''&nbsp;&nbsp; <TD>&nbsp;&nbsp;393&nbsp;&nbsp; <TD>&nbsp;&nbsp;1&thinsp;089&nbsp;&nbsp; <TD>&nbsp;&nbsp;22&thinsp;459&nbsp;&nbsp; <TD> <TD>&nbsp;&nbsp;122&thinsp;242&nbsp;&nbsp; <TR> <TD style="border-right:2px solid black;">&nbsp;&nbsp;''value of''&nbsp;&nbsp;<br>&nbsp;&nbsp;''retail''&nbsp;&nbsp; <TD>&nbsp;&nbsp;3&nbsp;&nbsp; <TD>&nbsp;&nbsp;53&nbsp;&nbsp; <TD>&nbsp;&nbsp;75&nbsp;&nbsp; <TD> <TD>&nbsp;&nbsp;116&thinsp;041&nbsp;&nbsp; </TABLE> </center> We will do an Input-Output analysis on this system. <ol type=1 start=1> <li> Fill in the numbers for this year's external demands. <li> Set up the linear system, leaving next year's external demands blank. <li> Solve the system where next year's external demands are calculated by taking this year's external demands and inflating them 10%. Do all three sectors increase their total business by 10%? Do they all even increase at the same rate? <li> Solve the system where next year's external demands are calculated by taking this year's external demands and reducing them 7%. (The study from which these numbers are taken concluded that because of the closing of a local military facility, overall personal income in the area would fall 7%, so this might be a first guess at what would actually happen.) /Solutions/ ## References - . - . - .
# Linear Algebra/Input-Output Analysis M File |current=Input-Output Analysis M File |previous=Topic: Input-Output Analysis ``` matlab # Octave commands for _Linear Algebra_ by Jim Hefferon, # Topic: leontif.tex a=[(25448-5395)/25448 -2664/30346; -48/25448 (30346-9030)/30346]; b=[17589; 21243]; ans=a \ b; printf("The answer to the first system is s=%0.0f and a=%0.0f\n",ans(1),ans(2)); b=[17489; 21243]; ans=a \ b; printf("The answer to the second system is s=%0.0f and a=%0.0f\n",ans(1),ans(2)); # question 1 b=[17789; 21243]; ans=a \ b; printf("The answer to question (1a) is s=%0.0f and a=%0.0f\n",ans(1),ans(2)); b=[17689; 21443]; ans=a \ b; printf("The answer to question (1b) is s=%0.0f and a=%0.0f\n",ans(1),ans(2)); b=[17789; 21443]; ans=a \ b; printf("The answer to question (1c) is s=%0.0f and a=%0.0f\n",ans(1),ans(2)); # question 2 printf("Current ratio for use of steel by auto is %0.4f\n",2664/30346); a=[(25448-5395)/25448 -0.0500; -48/25448 (30346-9030)/30346]; b=[17589; 21243]; ans=a \ b; printf("The answer to 2(a) is s=%0.0f and a=%0.0f\n",ans(1),ans(2)); b=[17589; 21500]; ans=a \ b; printf("The answer to 2(b) is s=%0.0f and a=%0.0f\n",ans(1),ans(2)); # question 3 printf("The value of steel used by others is %0.2f\n",18.69-(6.90+1.28)); printf("The value of autos used by others is %0.2f\n",14.27-(0+4.40)); a=[(18.69-6.90)/18.69 -1.28/14.27; -0/18.69 (14.27-4.40)/14.27]; b=[1.10*(18.69-(6.90+1.28)); 1.15*(14.27-(0+4.40))]; ans=a \ b; printf("The answer to 3(a) is s=%0.2f and a=%0.2f\n",ans(1),ans(2)); printf("The 1947 ratio of steel used by steel is %0.2f\n",(18.69-6.90)/18.69); printf("The 1947 ratio of steel used by autos is %0.2f\n",1.28/14.27); printf("The 1947 ratio of autos used by steel is %0.2f\n",0/18.69); printf("The 1947 ratio of autos used by autos is %0.2f\n",(14.27-4.40)/14.27); printf("The 1958 ratio of steel used by steel is %0.2f\n",(25448-5395)/25448); printf("The 1958 ratio of steel used by autos is %0.2f\n",2664/30346); printf("The 1958 ratio of autos used by steel is %0.2f\n",48/25448); printf("The 1958 ratio of autos used by autos is %0.2f\n",(30346-9030)/30346); b=[17.598/1.30; 21.243/1.30]; ans=a \ b; newans=1.30 * ans; printf("The answer to 3(c) is (in billions of 1947 dollars) s=%0.2f and a=%0.2f\n and in billions of 1958 dollars it is s=%0.2f and a=%0.2f\n",ans(1),ans(2),newans(1),newans(2)); ``` |current=Input-Output Analysis M File |previous=Topic: Input-Output Analysis |next=Topic: Accuracy of Computations}}`{=mediawiki}
# Linear Algebra/Topic: Accuracy of Computations |current=Topic: Accuracy of Computations |previous=Input-Output Analysis M File Gauss\' method lends itself nicely to computerization. The code below illustrates. It operates on an $n \! \times \! n$ matrix `a`, pivoting with the first row, then with the second row, etc. ``` C for (pivot_row = 1; pivot_row <= n - 1; pivot_row++) { for (row_below = pivot_row + 1; row_below <= n; row_below++) { multiplier = a[row_below, pivot_row] / a[pivot_row, pivot_row]; for (col = pivot_row; col <= n; col++) { a[row_below, col] -= multiplier * a[pivot_row, col]; } } } ``` (This code is in the C language. Here is a brief translation. The loop construct `for (pivot_row = 1; pivot_row <= n - 1; pivot_row++) { ... }` sets `pivot_row` to 1 and then iterates while `pivot_row` is less than or equal to $n-1$, each time through incrementing `pivot_row` by one with the \"`++`\" operation. The other non-obvious construct is that the \"`-=`\" in the innermost loop amounts to the `a[row_below, col] =- multiplier * a[pivot_row, col] + a[row_below, col]}` operation.) While this code provides a quick take on how Gauss\' method can be mechanized, it is not ready to use. It is naive in many ways. The most glaring way is that it assumes that a nonzero number is always found in the `pivot_row, pivot_row` position for use as the pivot entry. To make it practical, one way in which this code needs to be reworked is to cover the case where finding a zero in that location leads to a row swap, or to the conclusion that the matrix is singular. Adding some `if`$\cdots$ statements to cover those cases is not hard, but we will instead consider some more subtle ways in which the code is naive. There are pitfalls arising from the computer\'s reliance on finite-precision floating point arithmetic. For example, we have seen above that we must handle as a separate case a system that is singular. But systems that are nearly singular also require care. Consider this one. $$\begin{array}{*{2}{rc}r} x &+ &2y &= &3 \\ 1.000\,000\,01x &+ &2y &= &3.000\,000\,01 \end{array}$$ By eye we get the solution $x=1$ and $y=1$. But a computer has more trouble. A computer that represents real numbers to eight significant places (as is common, usually called **single precision**) will represent the second equation internally as $1.000\,000\,0x+2y=3.000\,000\,0$, losing the digits in the ninth place. Instead of reporting the correct solution, this computer will report something that is not even close--- this computer thinks that the system is singular because the two equations are represented internally as equal. For some intuition about how the computer could come up with something that far off, we can graph the system. ```{=html} <center> ``` ![](Linalg_singular_system.png "Linalg_singular_system.png"){width="" height="200"} ```{=html} </center> ``` At the scale of this graph, the two lines cannot be resolved apart. This system is nearly singular in the sense that the two lines are nearly the same line. Near-singularity gives this system the property that a small change in the system can cause a large change in its solution; for instance, changing the $3.000\,000\,01$ to $3.000\,000\,03$ changes the intersection point from $(1,1)$ to $(3,0)$. This system changes radically depending on a ninth digit, which explains why the eight-place computer has trouble. A problem that is very sensitive to inaccuracy or uncertainties in the input values is **ill-conditioned**. The above example gives one way in which a system can be difficult to solve on a computer. It has the advantage that the picture of nearly-equal lines gives a memorable insight into one way that numerical difficulties can arise. Unfortunately this insight isn\'t very useful when we wish to solve some large system. We cannot, typically, hope to understand the geometry of an arbitrary large system. In addition, there are ways that a computer\'s results may be unreliable other than that the angle between some of the linear surfaces is quite small. For an example, consider the system below, from . $$\begin{array}{*{2}{rc}r} 0.001x &+ &y &= &1 \\ x &- &y &= &0 \end{array} \qquad(*)$$ The second equation gives $x=y$, so $x=y=1/1.001$ and thus both variables have values that are just less than $1$. A computer using two digits represents the system internally in this way (we will do this example in two-digit floating point arithmetic, but a similar one with eight digits is easy to invent). $$\begin{array}{*{2}{rc}r} (1.0\times 10^{-3})x &+ &(1.0\times 10^{0})y &= &1.0\times 10^{0} \\ (1.0\times 10^{0})x &- &(1.0\times 10^{0})y &= &0.0\times 10^{0} \end{array}$$ The computer\'s row reduction step $-1000\rho_1+\rho_2$ produces a second equation $-1001y=-999$, which the computer rounds to two places as $(-1.0\times 10^{3})y=-1.0\times 10^{3}$. Then the computer decides from the second equation that $y=1$ and from the first equation that $x=0$. This $y$ value is fairly good, but the $x$ is quite bad. Thus, another cause of unreliable output is a mixture of floating point arithmetic and a reliance on pivots that are small. An experienced programmer may respond that we should go to **double precision** where sixteen significant digits are retained. This will indeed solve many problems. However, there are some difficulties with it as a general approach. For one thing, double precision takes longer than single precision (on a \'486 chip, multiplication takes eleven ticks in single precision but fourteen in double precision ) and has twice the memory requirements. So attempting to do all calculations in double precision is just not practical. And besides, the above systems can obviously be tweaked to give the same trouble in the seventeenth digit, so double precision won\'t fix all problems. What we need is a strategy to minimize the numerical trouble arising from solving systems on a computer, and some guidance as to how far the reported solutions can be trusted. Mathematicians have made a careful study of how to get the most reliable results. A basic improvement on the naive code above is to not simply take the entry in the *pivot_row*, *pivot_row* position for the pivot, but rather to look at all of the entries in the *pivot_row* column below the *pivot_row* row, and take the one that is most likely to give reliable results (e.g., take one that is not too small). This strategy is **partial pivoting**. For example, to solve the troublesome system ($*$) above, we start by looking at both equations for a best first pivot, and taking the $1$ in the second equation as more likely to give good results. Then, the pivot step of $-.001\rho_2+\rho_1$ gives a first equation of $1.001y=1$, which the computer will represent as $(1.0\times 10^{0})y=1.0\times 10^{0}$, leading to the conclusion that $y=1$ and, after back-substitution, $x=1$, both of which are close to right. The code from above can be adapted to this purpose. ``` C for (pivot_row = 1; pivot_row <= n - 1; pivot_row++) { /* Find the largest pivot in this column (in row max). */ max = pivot_row; for (row_below = pivot_row + 1; pivot_row <= n; row_below++) { if (abs(a[row_below, pivot_row]) > abs(a[max, row_below])) max = row_below; } /* Swap rows to move that pivot entry up. */ for (col = pivot_row; col <= n; col++) { temp = a[pivot_row, col]; a[pivot_row, col] = a[max, col]; a[max, col] = temp; } /* Proceed as before. */ for (row_below = pivot_row + 1; row_below <= n; row_below++) { multiplier = a[row_below, pivot_row] / a[pivot_row, pivot_row]; for (col = pivot_row; col <= n; col++) { a[row_below, col] -= multiplier * a[pivot_row, col]; } } } ``` A full analysis of the best way to implement Gauss\' method is outside the scope of the book (see ), but the method recommended by most experts is a variation on the code above that first finds the best pivot among the candidates, and then scales it to a number that is less likely to give trouble. This is **scaled partial pivoting**. In addition to returning a result that is likely to be reliable, most well-done code will return a number, called the **condition number** that describes the factor by which uncertainties in the input numbers could be magnified to become inaccuracies in the results returned (see ). The lesson of this discussion is that just because Gauss\' method always works in theory, and just because computer code correctly implements that method, and just because the answer appears on green-bar paper, doesn\'t mean that the answer is reliable. In practice, always use a package where experts have worked hard to counter what can go wrong. ## Exercises ## References - . - . - . - .
# Linear Algebra/Topic: Analyzing Networks |current=Topic: Analyzing Networks |previous=Topic: Accuracy of Computations The diagram below shows some of a car\'s electrical network. The battery is on the left, drawn as stacked line segments. The wires are drawn as lines, shown straight and with sharp right angles for neatness. Each light is a circle enclosing a loop. ```{=html} <center> ``` ![](Linalg_car_circuit.png "Linalg_car_circuit.png"){width="" height="200"} ```{=html} </center> ``` The designer of such a network needs to answer questions like: How much electricity flows when both the hi-beam headlights and the brake lights are on? Below, we will use linear systems to analyze simpler versions of electrical networks. For the analysis we need two facts about electricity and two facts about electrical networks. The first fact about electricity is that a battery is like a pump: it provides a force impelling the electricity to flow through the circuits connecting the battery\'s ends, if there are any such circuits. We say that the battery provides a **potential** to flow. Of course, this network accomplishes its function when, as the electricity flows through a circuit, it goes through a light. For instance, when the driver steps on the brake then the switch makes contact and a circuit is formed on the left side of the diagram, and the electrical current flowing through that circuit will make the brake lights go on, warning drivers behind. The second electrical fact is that in some kinds of network components the amount of flow is proportional to the force provided by the battery. That is, for each such component there is a number, its **resistance**, such that the potential is equal to the flow times the resistance. The units of measurement are: potential is described in **volts**, the rate of flow is in **amperes**, and resistance to the flow is in **ohms**. These units are defined so that $\mbox{volts}=\mbox{amperes}\cdot\mbox{ohms}$. Components with this property, that the voltage-amperage response curve is a line through the origin, are called **resistors**. (Light bulbs such as the ones shown above are not this kind of component, because their ohmage changes as they heat up.) For example, if a resistor measures $2$ ohms then wiring it to a $12$ volt battery results in a flow of $6$ amperes. Conversely, if we have electrical current of $2$ amperes through it then there must be a $4$ volt potential difference between its ends. This is the **voltage drop** across the resistor. One way to think of a electrical circuits like the one above is that the battery provides a voltage rise while the other components are voltage drops. The two facts that we need about networks are Kirchhoff\'s Laws. - *Current Law.* For any point in a network, the flow in equals the flow out. - *Voltage Law.* Around any circuit the total drop equals the total rise. In the above network there is only one voltage rise, at the battery, but some networks have more than one. For a start we can consider the network below. It has a battery that provides the potential to flow and three resistors (resistors are drawn as zig-zags). When components are wired one after another, as here, they are said to be in **series**. ```{=html} <center> ``` ![](Linalg_resisters_in_series.png "Linalg_resisters_in_series.png"){width="" height="200"} ```{=html} </center> ``` By Kirchhoff\'s Voltage Law, because the voltage rise is $20$ volts, the total voltage drop must also be $20$ volts. Since the resistance from start to finish is $10$ ohms (the resistance of the wires is negligible), we get that the current is $(20/10)=2$ amperes. Now, by Kirchhoff\'s Current Law, there are $2$ amperes through each resistor. (And therefore the voltage drops are: $4$ volts across the $2$ oh m resistor, $10$ volts across the $5$ ohm resistor, and $6$ volts across the $3$ ohm resistor.) The prior network is so simple that we didn\'t use a linear system, but the next network is more complicated. In this one, the resistors are in **parallel**. This network is more like the car lighting diagram shown earlier. ```{=html} <center> ``` ![](Linalg_resisters_in_parallel.png "Linalg_resisters_in_parallel.png"){width="" height="200"} ```{=html} </center> ``` We begin by labeling the branches, shown below. Let the current through the left branch of the parallel portion be $i_1$ and that through the right branch be $i_2$, and also let the current through the battery be $i_0$. (We are following Kirchoff\'s Current Law; for instance, all points in the right branch have the same current, which we call $i_2$. Note that we don\'t need to know the actual direction of flow--- if current flows in the direction opposite to our arrow then we will simply get a negative number in the solution.) ```{=html} <center> ``` ![](Linalg_resisters_in_parallel_2.png "Linalg_resisters_in_parallel_2.png"){width="" height="200"} ```{=html} </center> ``` The Current Law, applied to the point in the upper right where the flow $i_0$ meets $i_1$ and $i_2$, gives that $i_0=i_1+i_2$. Applied to the lower right it gives $i_1+i_2=i_0$. In the circuit that loops out of the top of the battery, down the left branch of the parallel portion, and back into the bottom of the battery, the voltage rise is $20$ while the voltage drop is $i_1\cdot 12$, so the Voltage Law gives that $12i_1=20$. Similarly, the circuit from the battery to the right branch and back to the battery gives that $8i_2=20$. And, in the circuit that simply loops around in the left and right branches of the parallel portion (arbitrarily taken clockwise), there is a voltage rise of $0$ and a voltage drop of $8i_2-12i_1$ so the Voltage Law gives that $8i_2-12i_1=0$. $$\begin{array}{*{3}{rc}r} i_0&- &i_1 &- &i_2 &= &0 \\ -i_0&+ &i_1 &+ &i_2 &= &0 \\ & &12i_1 & & &= &20 \\ & & & &8i_2 &= &20 \\ & &-12i_1 &+ &8i_2 &= &0 \end{array}$$ The solution is $i_0=25/6$, $i_1=5/3$, and $i_2=5/2$, all in amperes. (Incidentally, this illustrates that redundant equations do indeed arise in practice.) Kirchhoff\'s laws can be used to establish the electrical properties of networks of great complexity. The next diagram shows five resistors, wired in a **series-parallel** way. ```{=html} <center> ``` ![](Linalg_wheatstone_bridge.png "Linalg_wheatstone_bridge.png"){width="" height="200"} ```{=html} </center> ``` This network is a **Wheatstone bridge** (see Problem 4 ). To analyze it, we can place the arrows in this way. ```{=html} <center> ``` ![](Linalg_wheatstone_bridge_2.png "Linalg_wheatstone_bridge_2.png"){width="" height="200"} ```{=html} </center> ``` Kirchoff\'s Current Law, applied to the top node, the left node, the right node, and the bottom node gives these. $$\begin{array}{rl} i_0 &= i_1+i_2 \\ i_1 &= i_3+i_5 \\ i_2+i_5 &= i_4 \\ i_3+i_4 &= i_0 \end{array}$$ Kirchhoff\'s Voltage Law, applied to the inside loop (the $i_0$ to $i_1$ to $i_3$ to $i_0$ loop), the outside loop, and the upper loop not involving the battery, gives these. $$\begin{array}{rl} 5i_1+10i_3 &= 10 \\ 2i_2+4i_4 &= 10 \\ 5i_1+50i_5-2i_2 &= 0 \end{array}$$ Those suffice to determine the solution $i_0=7/3$, $i_1=2/3$, $i_2=5/3$, $i_3=2/3$, $i_4=5/3$, and $i_5=0$. Networks of other kinds, not just electrical ones, can also be analyzed in this way. For instance, networks of streets are given in the exercises. ## Exercises *Many of the systems for these problems are mostly easily solved on a computer.* *There are networks other than electrical ones, and we can ask how well Kirchoff\'s laws apply to them. The remaining questions consider an extension to networks of streets.*
# Linear Algebra/Topic: Speed of Gauss' Method |current=Topic: Speed of Gauss' Method |previous=Topic: Analyzing Networks Gauss\' Method to solve the linear systems in this book because it is easy to understand, easily shown to give the right answers, and fast. It is fast in that, in all the by-hand calculations we have needed, we have gotten the answers in only a few steps, taking only a few minutes. However, scientists and engineers who solve linear systems in practice must have a method that is fast enough for large systems, with 1000 equations or 10,000 equations or even 100,000 equations. These systems are solved on a computer, so the speed of the machine helps, but nonetheless the speed of the method used is a major consideration, and is sometimes the factor limiting which problems can be solved. The speed of an algorithm is usually measured by finding how the time taken to solve problems grows as the size of the input data set grows. That is, how much longer will the algorithm take if we increase the size of the input data by a factor of ten, say from a 1000-equation system to a 10,000-equation system, or from 10,000 to 100,000? Does the time taken grow ten times, or a hundred times, or a thousand times? Is the time taken by the algorithm proportional to the size of the data set, or to the square of that size, or to the cube of that size, etc.? Here is a fragment of Gauss\' Method code, implemented in the computer language FORTRAN. The coefficients of the linear system are stored in the $N \! \times \! N$ array *A*, and the constants are stored in the $N \! \times \! 1$ array *B*. For each *ROW* between $1$ and $N$ this program has already found the pivot entry $A(ROW,COL)$. Now it will pivot. $$-PIVINV\cdot \rho_{ROW} +\rho_{i}$$ (This code fragment is for illustration only, and is incomplete. For example, see the later topic on the Accuracy of Gauss\' Method. Nonetheless, this fragment will do for our purposes because analysis of finished versions, including all the tests and sub-cases, is messier but gives essentially the same result.) ``` fortran PIVINV=1./A(ROW,COL) DO 10 I=ROW+1, N DO 20 J=I, N A(I,J)=A(I,J)-PIVINV*A(ROW,J) 20 CONTINUE B(J)=B(J)-PIVINV*B(ROW) 10 CONTINUE ``` The outermost loop (not shown) runs through $N-1$ rows. For each of these rows, the shown loops perform arithmetic on the entries in *A* that are below and to the right of the pivot entry (and also on the entries in *B*, but to simplify the analysis we will not count those operations\-\--see Exercise ). We will assume the pivot is found in the usual place, that is, that $COL=ROW$ (as above, analysis of the general case is messier but gives essentially the same result). That means there are $(N-ROW)^2$ entries to perform arithmetic on. On average, ROW will be $N/2$. Thus we estimate the nested loops above will run something like $(N/2)^2$ times, that is, will run in a time proportional to the square of the number of equations. Taking into account the outer loop that is not shown, we get the estimate that the running time of the algorithm is proportional to the cube of the number of equations. Algorithms that run in time directly proportional to the size of the data set are fast, algorithms that run in time proportional to the square of the size of the data set are less fast, but typically quite usable, and algorithms that run in time proportional to the cube of the size of the data set are still reasonable in speed. Speed estimates like these are a good way of understanding how quickly or slowly an algorithm can be expected to run on average. There are special cases, however, of systems on which the above Gauss\' method code is especially fast, so there may be factors about a problem that make it especially suitable for this kind of solution. In practice, the code found in computer algebra systems, or in the standard packages, implements a variant on Gauss\' method, called triangular factorization. To state this method requires the language of matrix algebra, which we will not see until Chapter Three. Nonetheless, the above code is conceptually quite close to that usually used in applications. There have been some theoretical speed-ups in the running time required to solve linear systems. Algorithms other than Gauss\' method have been invented that take a time proportional not to the cube of the size of the data set, but instead to the (approximately) $2.7$ power (this is still under active research, so this exponent may come down somewhat over time). However, these theoretical improvements have not come into widespread use, in part because the new methods take a quite large data set before they overtake Gauss\' method (although they will outperform Gauss\' method on very large sets, there is some startup overhead that keeps them from being faster on the systems that have, so far, been solved in practice). ## Exercises
# Linear Algebra/Appendix |current=Appendix |previous=Topic: Linear Recurrences made of arguments (reasoned discourse that is, not crockery-throwing). This section is a reference to the most used techniques. A reader having trouble with, say, proof by contradiction, can turn here for an outline of that method. But this section gives only a sketch. For more, these are classics: *Methods of Logic* by Quine, *Induction and Analogy in Mathematics* by Pólya, and *Naive Set Theory* by Halmos. Reader can also read the wikibook Mathematical Proof. |current=Appendix |previous=Topic: Linear Recurrences |next=Propositions}}`{=mediawiki}
# Linear Algebra/Propositions |current=Propositions |previous=Appendix The point at issue in an argument is the **proposition**. Mathematicians usually write the point in full before the proof and label it either **Theorem** for major points, **Corollary** for points that follow immediately from a prior one, or **Lemma** for results chiefly used to prove other results. The statements expressing propositions can be complex, with many subparts. The truth or falsity of the entire proposition depends both on the truth value of the parts, and on the words used to assemble the statement from its parts. ### Not For example, where $P$ is a proposition, \"it is not the case that $P$\" is true provided that $P$ is false. Thus, \"$n$ is not prime\" is true only when $n$ is the product of smaller integers. We can picture the \"not\" operation with a **Venn diagram**. ```{=html} <center> ``` ![](Linalg_venn_not.png "Linalg_venn_not.png"){width="" height="200"} ```{=html} </center> ``` Where the box encloses all natural numbers, and inside the circle are the primes, the shaded area holds numbers satisfying \"not $P$\". To prove that a \"not $P$\" statement holds, show that $P$ is false. ### And Consider the statement form \"$P$ and $Q$\". For the statement to be true both halves must hold: \"$7$ is prime and so is $3$\" is true, while \"$7$ is prime and $3$ is not\" is false. Here is the Venn diagram for \"$P$ and $Q$\". ```{=html} <center> ``` ![](Linalg_venn_and.png "Linalg_venn_and.png"){width="" height="200"} ```{=html} </center> ``` To prove \"$P$ and $Q$\", prove that each half holds. ### Or A \"$P$ or $Q$\" is true when either half holds: \"$7$ is prime or $4$ is prime\" is true, while \"$7$ is not prime or $4$ is prime\" is false. We take \"or\" inclusively so that if both halves are true \"$7$ is prime or $4$ is not\" then the statement as a whole is true. (In everyday speech, sometimes \"or\" is meant in an exclusive way--- \"Eat your vegetables or no dessert\" does not intend both halves to hold--- but we will not use \"or\" in that way.) The Venn diagram for \"or\" includes all of both circles. ```{=html} <center> ``` ![](Linalg_venn_and.png "Linalg_venn_and.png"){width="" height="200"} ```{=html} </center> ``` To prove \"$P$ or $Q$\", show that in all cases at least one half holds (perhaps sometimes one half and sometimes the other, but always at least one). ### If-then An \"if $P$ then $Q$\" statement (sometimes written \"$P$ materially implies $Q$\" or just \"$P$ implies $Q$\" or \"$P\implies Q$\") is true unless $P$ is true while $Q$ is false. Thus \"if $7$ is prime then $4$ is not\" is true while \"if $7$ is prime then $4$ is also prime\" is false. (Contrary to its use in casual speech, in mathematics \"if $P$ then $Q$\" does not connote that $P$ precedes $Q$ or causes $Q$.) More subtly, in mathematics \"if $P$ then $Q$\" is true when $P$ is false: \"if $4$ is prime then $7$ is prime\" and \"if $4$ is prime then $7$ is not\" are both true statements, sometimes said to be **vacuously true**. We adopt this convention because we want statements like \"if a number is a perfect square then it is not prime\" to be true, for instance when the number is $5$ or when the number is $6$. The diagram ```{=html} <center> ``` ![](Linalg_venn_ifthen.png "Linalg_venn_ifthen.png"){width="" height="200"} ```{=html} </center> ``` shows that $Q$ holds whenever $P$ does (another phrasing is \"$P$ is sufficient to give $Q$\"). Notice again that if $P$ does not hold, $Q$ may or may not be in force. There are two main ways to establish an implication. The first way is direct: assume that $P$ is true and, using that assumption, prove $Q$. For instance, to show \"if a number is divisible by 5 then twice that number is divisible by 10\", assume that the number is $5n$ and deduce that $2(5n)=10n$. The second way is indirect: prove the **contrapositive** statement: \"if $Q$ is false then $P$ is false\" (rephrased, \"$Q$ can only be false when $P$ is also false\"). As an example, to show \"if a number is prime then it is not a perfect square\", argue that if it were a square $p=n^2$ then it could be factored $p=n\cdot n$ where $n<p$ and so wouldn\'t be prime (of course $p=0$ or $p=1$ don\'t give $n<p$ but they are nonprime by definition). Note two things about this statement form. First, an \"if $P$ then $Q$\" result can sometimes be improved by weakening $P$ or strengthening $Q$. Thus, \"if a number is divisible by $p^2$ then its square is also divisible by $p^2$\" could be upgraded either by relaxing its hypothesis: \"if a number is divisible by $p$ then its square is divisible by $p^2$\", or by tightening its conclusion: \"if a number is divisible by $p^2$ then its square is divisible by $p^4$\". Second, after showing \"if $P$ then $Q$\", a good next step is to look into whether there are cases where $Q$ holds but $P$ does not. The idea is to better understand the relationship between $P$ and $Q$, with an eye toward strengthening the proposition. ### Equivalence An if-then statement cannot be improved when not only does $P$ imply $Q$, but also $Q$ implies $P$. Some ways to say this are: \"$P$ if and only if $Q$\", \"$P$ iff $Q$\", \"$P$ and $Q$ are logically equivalent\", \"$P$ is necessary and sufficient to give $Q$\", \"$P\iff Q$\". For example, \"a number is divisible by a prime if and only if that number squared is divisible by the prime squared\". The picture here shows that $P$ and $Q$ hold in exactly the same cases. ```{=html} <center> ``` ![](Linalg_venn_equiv.png "Linalg_venn_equiv.png"){width="" height="200"} ```{=html} </center> ``` Although in simple arguments a chain like \"$P$ if and only if $R$, which holds if and only if $S$ \...\" may be practical, typically we show equivalence by showing the \"if $P$ then $Q$\" and \"if $Q$ then
# Linear Algebra/Quantifiers |current=Quantifiers |previous=Propositions Compare these two statements about natural numbers: \"there is an $x$ such that $x$ is divisible by $x^2$\" is true, while \"for all numbers $x$, that $x$ is divisible by $x^2$\" is false. We call the \"there is\" and \"for all\" prefixes **quantifiers**. ### For all The \"for all\" prefix is the **universal quantifier**, symbolized $\forall$. Venn diagrams aren\'t very helpful with quantifiers, but in a sense the box we draw to border the diagram shows the universal quantifier since it delineates the universe of possible members. ```{=html} <center> ``` ![](Linalg_venn_forall.png "Linalg_venn_forall.png"){width="" height="200"} ```{=html} </center> ``` To prove that a statement holds in all cases, we must show that it holds in each case. Thus, to prove \"every number divisible by $p$ has its square divisible by $p^2$\", take a single number of the form $pn$ and square it $(pn)^2=p^2n^2$. This is a \"typical element\" or \"generic element\" proof. This kind of argument requires that we are careful to not assume properties for that element other than those in the hypothesis--- for instance, this type of wrong argument is a common mistake: \"if $n$ is divisible by a prime, say $2$, so that $n=2k$ then $n^2=(2k)^2=4k^2$ and the square of the number is divisible by the square of the prime\". That is an argument about the case $p=2$, but it isn\'t a proof for general $p$. ### There exists We will also use the **existential quantifier**, symbolized $\exists$ and read \"there exists\". As noted above, Venn diagrams are not much help with quantifiers, but a picture of \"there is a number such that $P$\" would show both that there can be more than one and that not all numbers need satisfy $P$. ```{=html} <center> ``` ![](Linalg_venn_thereexists.png "Linalg_venn_thereexists.png"){width="" height="200"} ```{=html} </center> ``` An existence proposition can be proved by producing something satisfying the property: once, to settle the question of primality of $2^{2^5}+1$, Euler produced its divisor $641$. But there are proofs showing that something exists without saying how to find it; Euclid\'s argument given in the next subsection shows there are infinitely many primes without naming them. In general, while demonstrating existence is better than nothing, giving an example is better, and an exhaustive list of all instances is great. Still, mathematicians take what they can get. Finally, along with \"Are there any?\" we often ask \"How many?\" That is why the issue of uniqueness often arises in conjunction with questions of existence. Many times the two arguments are simpler if separated, so note that just as proving something exists does not show it is unique, neither does proving something is unique show that it exists. (Obviously \"the natural number with more factors than any other\" would be unique, but in fact no such number exists.) |current=Quantifiers |previous=Propositions |next=Techniques of Proof}}`{=mediawiki}
# Linear Algebra/Techniques of Proof |current=Techniques of Proof |previous=Quantifiers ### Induction Many proofs are iterative, \"Here\'s why the statement is true for for the case of the number $1$, it then follows for $2$, and from there to $3$, and so on \...\". These are called proofs by **induction**. Such a proof has two steps. In the **base step** the proposition is established for some first number, often $0$ or $1$. Then in the **inductive step** we assume that the proposition holds for numbers up to some $k$ and deduce that it then holds for the next number $k+1$. Here is an example. > We will prove that $1+2+3+\dots+n=n(n+1)/2$. > > For the base step we must show that the formula holds when $n=1$. > That\'s easy, the sum of the first $1$ number does indeed equal > $1(1+1)/2$. > > For the inductive step, assume that the formula holds for the numbers > $1,2,\ldots,k$. That is, assume all of these instances of the formula. > > $$\begin{array}{rl} > 1 > &=1(1+1)/2 \\ > \text{and}\quad 1+2 > &=2(2+1)/2 \\ > \text{and}\quad 1+2+3 > &=3(3+1)/2 \\ > &\vdots \\ > \text{and}\quad 1+\dots+k > &=k(k+1)/2 > \end{array}$$ > > From this assumption we will deduce that the formula therefore also > holds in the $k+1$ next case. The deduction is straightforward > algebra. > > $$1+2+\cdots+k+(k+1) > = > \frac{k(k+1)}{2}+(k+1) > = > \frac{(k+1)(k+2)}{2}$$ We\'ve shown in the base case that the above proposition holds for $1$. We\'ve shown in the inductive step that if it holds for the case of $1$ then it also holds for $2$; therefore it does hold for $2$. We\'ve also shown in the inductive step that if the statement holds for the cases of $1$ and $2$ then it also holds for the next case $3$, etc. Thus it holds for any natural number greater than or equal to $1$. Here is another example. > We will prove that every integer greater than $1$ is a product of > primes. > > The base step is easy: $2$ is the product of a single prime. > > For the inductive step assume that each of $2, 3,\ldots ,k$ is a > product of primes, aiming to show $k+1$ is also a product of primes. > There are two possibilities: (i) if $k+1$ is not divisible by a number > smaller than itself then it is a prime and so is the product of > primes, and (ii) if $k+1$ is divisible then its factors can be written > as a product of primes (by the inductive hypothesis) and so $k+1$ can > be rewritten as a product of primes. That ends the proof. > > (*Remark.* The Prime Factorization Theorem of Number Theory says that > not only does a factorization exist, but that it is unique. We\'ve > shown the easy half.) There are two things to note about the \"next number\" in an induction argument. For one thing, while induction works on the integers, it\'s no good on the reals. There is no \"next\" real. The other thing is that we sometimes use induction to go down, say, from $10$ to $9$ to $8$, etc., down to $0$. So \"next number\" could mean \"next lowest number\". Of course, at the end we have not shown the fact for all natural numbers, only for those less than or equal to $10$. ### Contradiction Another technique of proof is to show something is true by showing it can\'t be false. > The classic example is Euclid\'s, that there are infinitely many > primes. > > Suppose there are only finitely many primes $p_1,\dots,p_k$. Consider > $p_1\cdot p_2\dots p_k +1$. None of the primes on this supposedly > exhaustive list divides that number evenly, each leaves a remainder of > $1$. But every number is a product of primes so this can\'t be. Thus > there cannot be only finitely many primes. Every proof by contradiction has the same form: **assume** that **the false** proposition **is** **true** and **derive** some **contradiction** to known facts. This kind of logic is known as Aristotelian Logic, or Term Logic > Another example is this proof that $\sqrt{2}$ is not a rational > number. > > Suppose that $\sqrt{2}=m/n$. > > $$2n^2=m^2$$ > > Factor out the $2$\'s: $n=2^{k_n}\cdot \hat{n}$ and > $m=2^{k_m}\cdot \hat{m}$ and rewrite. > > $$2\cdot (2^{k_n}\cdot \hat{n})^2 > = > (2^{k_m}\cdot \hat{m})^2$$ > > The Prime Factorization Theorem says that there must be the same > number of factors of $2$ on both sides, but there are an odd number > $1+2k_n$ on the left and an even number $2k_m$ on the right. That\'s a > contradiction, so a rational with a square of $2$ cannot be. Both of these examples aimed to prove something doesn\'t exist. A negative proposition often suggests a proof by contradiction. |current=Techniques of Proof |previous=Quantifiers |next=Sets, Functions, Relations}}`{=mediawiki}
# Linear Algebra/Sets, Functions, Relations |current=Sets, Functions, Relations |previous=Techniques of Proof ### Sets Mathematicians work with collections called **sets**. A set can be given as a listing between curly braces as in $\{ 1,4,9,16 \}$, or, if that\'s unwieldy, by using set-builder notation as in $\{x\,\big|\, x^5-3x^3+2=0 \}$ (read \"the set of all $x$ such that \\ldots\"). We name sets with capital roman letters as with the primes $P=\{2,3,5,7,11,\ldots\,\}$, except for a few special sets such as the real numbers $\mathbb{R}$, and the complex numbers $\mathbb{C}$. To denote that something is an **element** (or **member**) of a set we use \"${}\in {}$\", so that $7\in\{3,5,7\}$ while $8\not\in\{3,5,7\}$. What distinguishes a set from any other type of collection is the Principle of Extensionality, that two sets with the same elements are equal. Because of this principle, in a set repeats collapse $\{7,7\}=\{7\}$ and order doesn\'t matter $\{2,\pi\}=\{\pi,2\}$. We use \"$\subset$\" for the subset relationship: $\{2,\pi\}\subset\{2,\pi,7\}$ and \"$\subseteq$\" for subset or equality (if $A$ is a subset of $B$ but $A\neq B$ then $A$ is a **proper subset** of $B$). These symbols may be flipped, for instance $\{ 2,\pi,5\}\supset\{2,5\}$. Because of Extensionality, to prove that two sets are equal $A=B$, just show that they have the same members. Usually we show mutual inclusion, that both $A\subseteq B$ and $A\supseteq B$. ### Set operations Venn diagrams are handy here. For instance, $x\in P$ can be pictured ```{=html} <center> ``` ![](Linalg_venn_xinP.png "Linalg_venn_xinP.png"){width="" height="200"} ```{=html} </center> ``` and \"$P\subseteq Q$\" looks like this. ```{=html} <center> ``` ![](Linalg_venn_ifthen.png "Linalg_venn_ifthen.png"){width="" height="200"} ```{=html} </center> ``` Note that this is a repeat of the diagram for \"if \\ldots then \...\" propositions. That\'s because \"$P\subseteq Q$\" means \"if $x\in P$ then $x\in Q$\". In general, for every propositional logic operator there is an associated set operator. For instance, the **complement** of $P$ is $P^{\text{comp}}=\{x\,\big|\, \text{not }(x\in P)\}$ ```{=html} <center> ``` ![](Linalg_venn_not.png "Linalg_venn_not.png"){width="" height="200"} ```{=html} </center> ``` the **union** is $P\cup Q=\{x\,\big|\,(x\in P) \text{ or }(x\in Q)\}$ ```{=html} <center> ``` ![](Linalg_venn_or.png "Linalg_venn_or.png"){width="" height="200"} ```{=html} </center> ``` and the **intersection** is $P\cap Q=\{x\,\big|\, (x\in P)\text{ and }(x\in Q)\}.$ ```{=html} <center> ``` ![](Linalg_venn_and.png "Linalg_venn_and.png"){width="" height="200"} ```{=html} </center> ``` }}When two sets share no members their intersection is the **empty set** $\{\}$, symbolized $\varnothing$. Any set has the empty set for a subset, by the \"vacuously true\" property of the definition of implication. ### Sequences We shall also use collections where order does matter and where repeats do not collapse. These are **sequences**, denoted with angle brackets: $\langle 2,3,7 \rangle \neq\langle 2,7,3 \rangle$. A sequence of length $2$ is sometimes called an **ordered pair** and written with parentheses: $(\pi,3)$. We also sometimes say \"ordered triple\", \"ordered $4$-tuple\", etc. The set of ordered $n$-tuples of elements of a set $A$ is denoted $A^n$. Thus the set of pairs of reals is $\mathbb{R}^2$. ### Functions We first see functions in elementary Algebra, where they are presented as formulas (e.g., $f(x)=16x^2-100$), but progressing to more advanced Mathematics reveals more general functions--- trigonometric ones, exponential and logarithmic ones, and even constructs like absolute value that involve piecing together parts--- and we see that functions aren\'t formulas, instead the key idea is that a function associates with its input $x$ a single output $f(x)$. Consequently, a **function** or **map** is defined to be a set of ordered pairs $(x,f(x)\,)$ such that $x$ suffices to determine $f(x)$, that is: if $x_1=x_2$ then $f(x_1)=f(x_2)$ (this requirement is referred to by saying a function is **well-defined**).\\footnote{More on this is in the section on isomorphisms} Each input $x$ is one of the function\'s **arguments** and each output $f(x)$ is a **value**. The set of all arguments is $f$\'s **domain** and the set of output values is its **range**. Usually we don\'t need know what is and is not in the range and we instead work with a superset of the range, the **codomain**. The notation for a function $f$ with domain $X$ and codomain $Y$ is $f:X\to Y$. ```{=html} <center> ``` ![](Linalg_domain_range_codomain.png "Linalg_domain_range_codomain.png"){width="" height="200"} ```{=html} </center> ``` We sometimes instead use the notation $x\stackrel{f}{\longmapsto} 16x^2-100$, read \"$x$ maps under $f$ to $16x^2-100$\", or \"$16x^2-100$ is the \"*image*\' of $x$\'. Some maps, like $x\mapsto \sin(1/x)$, can be thought of as combinations of simple maps, here, $g(y)=\sin(y)$ applied to the image of $f(x)=1/x$. The **composition** of $g:Y\to Z$ with $f:X\to Y$, is the map sending $x\in X$ to $g(\, f(x)\,)\in Z$. It is denoted $g\circ f:X\to Z$. This definition only makes sense if the range of $f$ is a subset of the domain of $g$. Observe that the **identity map** $\mbox{id}:Y\to Y$ defined by $\mbox{id}(y)=y$ has the property that for any $f:X\to Y$, the composition $\mbox{id}\circ f$ is equal to $f$. So an identity map plays the same role with respect to function composition that the number $0$ plays in real number addition, or that the number $1$ plays in multiplication. In line with that analogy, define a **left inverse** of a map $f:X\to Y$ to be a function $g:\text{range}(f)\to X$ such that $g\circ f$ is the identity map on $X$. Of course, a **right inverse** of $f$ is a $h:Y\to X$ such that $f\circ h$ is the identity. A map that is both a left and right inverse of $f$ is called simply an **inverse**. An inverse, if one exists, is unique because if both $g_1$ and $g_2$ are inverses of $f$ then $g_1(x)=g_1\circ (f\circ g_2) (x) = (g_1\circ f) \circ g_2(x) =g_2(x)$ (the middle equality comes from the associativity of function composition), so we often call it \"the\" inverse, written $f^{-1}$. For instance, the inverse of the function $f:\mathbb{R}\to \mathbb{R}$ given by $f(x)=2x-3$ is the function $f^{-1}:\mathbb{R}\to \mathbb{R}$ given by $f^{-1}(x)=(x+3)/2$. The superscript \"$f^{-1}$\" notation for function inverse can be confusing--- it doesn\'t mean $1/f(x)$. It is used because it fits into a larger scheme. Functions that have the same codomain as domain can be iterated, so that where $f:X\to X$, we can consider the composition of $f$ with itself: $f\circ f$, and $f\circ f\circ f$, etc. Naturally enough, we write $f\circ f$ as $f^2$ and $f\circ f\circ f$ as $f^3$, etc. Note that the familiar exponent rules for real numbers obviously hold: $f^i\circ f^j=f^{i+j}$ and $(f^i)^j=f^{i\cdot j}$. The relationship with the prior paragraph is that, where $f$ is invertible, writing $f^{-1}$ for the inverse and $f^{-2}$ for the inverse of $f^2$, etc., gives that these familiar exponent rules continue to hold, once $f^0$ is defined to be the identity map. If the codomain $Y$ equals the range of $f$ then we say that the function is **onto** (or **surjective**). A function has a right inverse if and only if it is onto (this is not hard to check). If no two arguments share an image, if $x_1\neq x_2$ implies that $f(x_1)\neq f(x_2)$, then the function is **one-to-one** (or **injective**). A function has a left inverse if and only if it is one-to-one (this is also not hard to check). By the prior paragraph, a map has an inverse if and only if it is both onto and one-to-one; such a function is a **correspondence**. It associates one and only one element of the domain with each element of the range (for example, finite sets must have the same number of elements to be matched up in this way). Because a composition of one-to-one maps is one-to-one, and a composition of onto maps is onto, a composition of correspondences is a correspondence. We sometimes want to shrink the domain of a function. For instance, we may take the function $f:\mathbb{R}\to \mathbb{R}$ given by $f(x)=x^2$ and, in order to have an inverse, limit input arguments to nonnegative reals $\hat{f}:\mathbb{R}^+\to \mathbb{R}$. Technically, $\hat{f}$ is a different function than $f$; we call it the **restriction** of $f$ to the smaller domain. A final point on functions: neither $x$ nor $f(x)$ need be a number. As an example, we can think of $f(x,y)=x+y$ as a function that takes the ordered pair $(x,y)$ as its argument. ### Relations Some familiar operations are obviously functions: addition maps $(5,3)$ to $8$. But what of \"$<$\" or \"$=$\"? We here take the approach of rephrasing \"$3<5$\" to \"$(3,5)$ is in the relation $<$\". That is, define a **binary relation** on a set $A$ to be a set of ordered pairs of elements of $A$. For example, the $<$ relation is the set $\{(a,b)\,\big|\, a<b\}$; some elements of that set are $(3,5)$, $(3,7)$, and $(1,100)$. Another binary relation on the natural numbers is equality; this relation is formally written as the set $\{\ldots,(-1,-1),(0,0),(1,1),\ldots\}$. Still another example is \"closer than $10$\", the set $\{(x,y)\,\big|\, |x-y|<10 \}$. Some members of that relation are $(1,10)$, $(10,1)$, and $(42,44)$. Neither $(11,1)$ nor $(1,11)$ is a member. Those examples illustrate the generality of the definition. All kinds of relationships (e.g., \"both numbers even\" or \"first number is the second with the digits reversed\") are covered under the definition. ### Equivalence Relations We shall need to say, formally, that two objects are alike in some way. While these alike things aren\'t identical, they are related (e.g., two integers that \"give the same remainder when divided by $2$\"). A binary relation $\{(a,b),\ldots \}$ is an **equivalence relation**when it satisfies 1. **reflexivity**: any object is related to itself; 2. **symmetry**: if $a$ is related to $b$ then $b$ is related to $a$; 3. **transitivity**: if $a$ is related to $b$ and $b$ is related to $c$ then $a$ is related to $c$. (To see that these conditions formalize being the same, read them again, replacing \"is related to\" with \"is like\".) Some examples (on the integers): \"$=$\" is an equivalence relation, \"$<$\" does not satisfy symmetry, \"same sign\" is a equivalence, while \"nearer than $10$\" fails transitivity. ### Partitions In \"same sign\" $\{ (1,3),(-5,-7),(-1,-1),\ldots\}$ there are two kinds of pairs, the first with both numbers positive and the second with both negative. So integers fall into exactly one of two classes, positive or negative. A **partition** of a set $S$ is a collection of subsets $\{S_1,S_2,\ldots\}$ such that every element of $S$ is in one and only one $S_i$: $S_1\cup S_2\cup \ldots{} = S$, and if $i$ is not equal to $j$ then $S_i\cap S_j=\varnothing$. Picture $S$ being decomposed into distinct parts. ```{=html} <center> ``` ![](Linalg_partition.png "Linalg_partition.png"){width="" height="200"} ```{=html} </center> ``` Thus, the first paragraph says \"same sign\" partitions the integers into the positives and the negatives. Similarly, the equivalence relation \"=\" partitions the integers into one-element sets. Another example is the fractions. Of course, $2/3$ and $4/6$ are equivalent fractions. That is, for the set $S=\{n/d\,\big|\, n,d\in\mathbb{Z}\text{ and }d\neq 0\}$, we define two elements $n_1/d_1$ and $n_2/d_2$ to be equivalent if $n_1d_2=n_2d_1$. We can check that this is an equivalence relation, that is, that it satisfies the above three conditions. With that, $S$ is divided up into parts. ```{=html} <center> ``` ![](Linalg_partition_2.png "Linalg_partition_2.png"){width="" height="200"} ```{=html} </center> ``` Before we show that equivalence relations always give rise to partitions, we first illustrate the argument. Consider the relationship between two integers of \"same parity\", the set $\{ (-1,3),(2,4),(0,0),\ldots\}$ (i.e., \"give the same remainder when divided by $2$\"). We want to say that the natural numbers split into two pieces, the evens and the odds, and inside a piece each member has the same parity as each other. So for each $x$ we define the set of numbers associated with it: $S_x=\{y\,\big|\, (x,y)\in\text{same parity}\}$. Some examples are $S_1=\{\ldots,-3,-1,1,3,\ldots\}$, and $S_4=\{\ldots,-2,0,2,4,\ldots\}$, and $S_{-1}=\{\ldots,-3,-1,1,3,\ldots\}$. These are the parts, e.g., $S_1$ is the odds. }}`<b>`{=html}Theorem`</b>`{=html} An equivalence relation induces a partition on the underlying set. }}We call each part of a partition an **equivalence class** (or informally, \"part\"). We somtimes pick a single element of each equivalence class to be the **class representative**. ```{=html} <center> ``` ![](Linalg_partition_3.png "Linalg_partition_3.png"){width="" height="200"} ```{=html} </center> ``` Usually when we pick representatives we have some natural scheme in mind. In that case we call them the **canonical** representatives. An example is the simplest form of a fraction. We\'ve defined $3/5$ and $9/15$ to be equivalent fractions. In everyday work we often use the \"simplest form\" or \"reduced form\" fraction as the class representatives. ```{=html} <center> ``` ![](Linalg_partition_4.png "Linalg_partition_4.png"){width="" height="200"} ```{=html} </center> ``` |current=Sets, Functions, Relations |previous=Techniques of Proof |next=Licensing And History}}`{=mediawiki}
# Circuit Theory/All Chapters \ This wikibook is going to be an introductory text about electric circuits. It will cover some the basics of electric circuit theory, circuit analysis, and will touch on circuit design. This book will serve as a companion reference for a 1st year of an Electrical Engineering undergraduate curriculum. Topics covered include AC and DC circuits, passive circuit components, phasors, and RLC circuits. The focus is on students of an electrical engineering undergraduate program. Hobbyists would benefit more from reading Electronics instead. *This book is not nearly completed, and could still be improved. People with knowledge of the subject are encouraged to contribute.* The main editable text of this book is located at <http://en.wikibooks.org/wiki/Circuit_Theory>. The wikibooks version of this text is considered the most up-to-date version, and is the best place to edit this book and contribute to it.
# Circuit Theory/Circuit Theory Introduction ## Who is This Book For? This is designed for a first course in Circuit Analysis which is usually accompanied by a set of labs. It is assumed that students are in a Differential Equations class at the same time. Phasors are used to avoid the Laplace transform of driving functions while maintaining a complex impedance transform of the physical circuit that is identical in both. 1st and 2nd order differential equations can be solved using phasors and calculus if the driving functions are sinusoidal. The sinusoidal is then replaced by the more simple step function and then the convolution integral is used to find an analytical solution to any driving function. This leaves time for a more intuitive understanding of poles, zeros, transfer functions, and Bode plot interpretation. For those who have already had differential equations, the Laplace transform equivalent will be presented as an alternative while focusing on phasors and calculus. This book will expect the reader to have a firm understanding of Calculus specifically, and will not stop to explain the fundamental topics in Calculus. For information on Calculus, see the wikibook: Calculus. ## What Will This Book Cover? This book will cover linear circuits, and linear circuit elements. The goal is to emphasize Kirchhoff and symbolic algebra systems such as MuPAD, Mathematica or Sage; at the expense of analysis methods such as node, mesh, and Norton equivalent. A phasor/calculus based approach starts at the very beginning and ends with the convolution integral to handle all the various types of forcing functions. The result is a linear analysis experience that is general in nature but skips Laplace and Fourier transforms. Kirchhoff\'s laws receive normal focus, but the other circuit analysis/simplification techniques receive less than a normal attention. The class ends with application of these concepts in Power Analysis, Filters, Control systems. The goal is set the ground work for a transition to the digital version of these concepts from a firm basis in the physical world. The next course would be one focused on modeling linear systems and analyzing them digitally in preparation for a digital signal (DSP) processing course. ## Where to Go From Here - For a technician version of this course which focuses on the practical rather than the idea, expertise rather than theory, and on algebra rather than calculus, see the **Electronics** wikibook. - Take **Ordinary Differential Equations** now that you have a practical reason to do so. This math class should ideally feel like an \"art\" class and be enjoyable. - To begin a course of study in Computer Engineering, see the **Digital Circuits** wikibook. - For a traditional \"next\" course, see the **Signals and Systems** wikibook. There should be an overlap with this wikibook. - The intended next course would have a name such as **A New Sequence in Signals and Linear Systems** or **Elements of Discrete Signal Analysis**.
# Circuit Theory/Terminology ## Basic Terminology There are a few key terms that need to be understood at the beginning of this book, before we can continue. This is only a partial list of all terms that will be used throughout this book, but these key words are important to know before we begin the main narrative of this text. Time domain : The **time domain** is described by graphs of power, voltage and current that depend upon time. This is simply another way of saying that our circuits change with time, and that the major variable used to describe the system is time. Another name is \"temporal\". ```{=html} <!-- --> ``` Frequency domain: The **frequency domain** are graphs of power, voltage and/or current that depend upon frequency such as Bode plots. Variable frequencies in wireless communication can represent changing channels or data on a channel. Another name is the \"Fourier domain\". Other domains that an engineer might encounter are the \"Laplace domain\" (or the \"s domain\" or \"complex frequency domain\"), and the \"Z domain\". When combined with the time, it is called a \"spectral\" or \"waterfall.\" ```{=html} <!-- --> ``` Circuit response : Circuits generally have inputs and outputs. In fact, it is safe to say that a circuit isn\'t useful if it doesn\'t have one or the other (usually both). **Circuit response** is the relationship between the circuit\'s input to the circuit\'s output. The circuit response may be a measure of either current or voltage. ```{=html} <!-- --> ``` Non-homogeneous : Circuits are described by equations that capture the component characteristics and how they are wired together. These equations are **non-homogeneous** in nature. Solving these equations requires splitting the single problem into two problems: a *steady-state solution* (particular solution) and a *transient solution* (homogeneous solution). ```{=html} <!-- --> ``` Steady-state solution : The final value, when all circuit elements have a constant or periodic behavior, is also known as the steady-state value of the circuit. The circuit response at steady-state (when voltages and currents have stopped changing due to a disturbance) is also known as the \"steady-state response\". The **steady-state solution** to the particular integral is called the *particular solution*. ```{=html} <!-- --> ``` Transient : A **transient** event is a short-lived burst of energy in a system caused by a sudden change of state. ```{=html} <!-- --> ``` : Transient "wikilink") means momentary, or a short period of time. Transient means that the energy in a circuit suddenly changes which causes the energy storage elements to react. The circuit\'s energy state is forced to change. When a car goes over a bump, it can fly apart, feel like a rock, or cushion the impact in a designed manner. The goal of most circuit design is to plan for transients, whether intended or not. ```{=html} <!-- --> ``` : Transient solutions are determined by assuming the driving function(s) is zero which creates a homogeneous equation, which has a **homogeneous solution**. ## Summary When something changes in a circuit, there is a certain transition period before a circuit \"settles down\", and reaches its final value. The response that a circuit has before settling into its *steady-state response* is known as the *transient response*. Using **Euler\'s formula**, **complex numbers**, **phasors** and the **s-plane**, a **homogeneous solution** technique will be developed that captures the transient response by assuming the final state has no energy. In addition, a **particular solution** technique will be developed that finds the final energy state. Added together, they predict the *circuit response*. The related **Differential equation** development of homogeneous and particular solutions will be avoided.
# Circuit Theory/Variables and Units ## Electric Charge (Coulombs) **Electric charge** is a physical property of matter that causes it to experience a force when near other electrically charged matter. Electric Charge (symbol q) is measured in SI units called **\"Coulombs\"**, which are abbreviated with the letter capital C. We know that q=n\*e, where n = number of electrons and e= 1.6\*10^−19^. Hence n=1/e coulombs. A Coulomb is the total charge of 6.24150962915265×10^18^ electrons, thus a single electron has a charge of −1.602 × 10^−19^ C. It is important to understand that this concept of \"charge\" is associated with static electricity. Charge, as a concept, has a physical boundary that is related to counting a group of electrons. \"Flowing\" electricity is an **entirely different situation**. \"Charge\" and electrons separate. Charge moves at the speed of light while electrons move at the speed of **1 meter/hour**. Thus in most circuit analysis, \"charge\" is an abstract concept unrelated to energy or an electron and more related to the flow of **information**. Electric charge is the subject of many fundamental laws, such as **Coulomb\'s Law** and **Gauss\' Law** (static electricity) but is not used much in circuit theory. ## Voltage (Volts) **Voltage** is a measure of the work required to move a charge from one point to another in a electric field. Thus the unit \"volt\" is defined as a Joules (J) per Coulomb (C). $$V = \frac{W}{q}$$ W represents work, q represents an amount of charge. Charge is a static electricity concept. The definition of a volt is shared between static and \"flowing\" electronics. Voltage is sometimes called \"electric potential\", because voltage represents the a difference in Electro Motive Force (EMF) that can produce current in a circuit. More voltage means more potential for current. Voltage also can be called \"Electric Pressure\", although this is far less common. Voltage is not measured in absolutes but in *relative* terms. The English language tradition obscures this. For example we say \"What is the distance to New York?\" Clearly implied is the relative distance from where we are standing to New York. But if we say \"What is the voltage at \_\_\_\_\_\_?\" What is the starting point? Voltage is defined between two points. Voltage is relative to where 0 is defined. We say \"The voltage from point A to B is 5 volts.\" It is important to understand EMF and voltage are two different things. When the question is asked \"What is the voltage at \_\_\_\_\_\_?\", look for the ground symbol on a circuit diagram. Measure voltage from ground to \_\_\_\_\_. If the question is asked \"What is the voltage from A to B?\" then put the red probe on A and the black probe on B (not ground). The absolute is referred to as \"EMF\" or Electro Motive Force. The difference between the two EMF\'s is a voltage. ## Current (Amperes) **Current** is a measurement of the flow of electricity. Current is measured in units called **Amperes** (or \"Amps\"). An ampere is \"charge volume velocity\" in the same way water current could be measured in \"cubic feet of water per second.\" But current is a **base SI unit**, a fundamental dimension of reality like space, time and mass. A coulomb or charge is not. A coulomb is actually defined in terms of the ampere. \"Charge or Coulomb\" is a **derived SI Unit**. The coulomb is a fictitious entity left over from the **one fluid /two fluid** philosophies of the 18th century. This course is about flowing electrical energy that is found in all modern electronics. Charge volume velocity (defined by current) is a useful concept, but understand it has no practical use in engineering. Do not think of current as a bundle electrons carrying energy through a wire. Special relativity and quantum mechanics concepts are necessary to understand how electrons move at **1 meter/hour** through copper, yet electromagnetic energy moves at near the speed of light. Amperes are abbreviated with an \"A\" (upper-case A), and the variable most often associated with current is the letter \"i\" (lower-case I). In terms of coulombs, an ampere is: $$i = \frac{dq}{dt}$$ Because of the widespread use of complex numbers in Electrical Engineering, it is common for electrical engineering texts to use the letter \"j\" (lower-case J) as the imaginary number, instead of the \"i\" (lower-case I) commonly used in math texts. This wikibook will adopt the \"j\" as the imaginary number, to avoid confusion. ## Energy and Power Electrical theory is about energy storage and the flow of energy in circuits. Energy is chopped up arbitrarily into something that doesn\'t exist but can be counted called a coulomb. Energy per coulomb is voltage. The velocity of a coulomb is current. Multiplied together, the units are energy velocity or power \... and the unreal \"coulomb\" disappears. ### Energy Energy is measured most commonly in Joules, which are abbreviated with a \"J\" (upper-case J). The variable most commonly used with energy is \"w\" (lower-case W). The energy symbol is w which stands for work. From a thermodynamics point of view, all energy consumed by a circuit is work \... all the heat is turned into work. Practically speaking, this can not be true. If it were true, computers would never consume any energy and never heat up. The reason that all the energy going into a circuit and leaving a circuit is considered \"work\" is because from a thermodynamic point of view, electrical energy is ideal. All of it can be used. Ideally all of it can be turned into work. Most introduction to thermodynamics courses assume that electrical energy is completely organized (and has entropy of 0). ### Power A corollary to the concept of energy being work, is that all the energy/power of a circuit (ideally) can be accounted for. The sum of all the power entering and leaving a circuit should add up to zero. No energy should be accumulated (theoretically). Of course capacitors will charge up and may hold onto their energy when the circuit is turned off. Inductors will create a magnetic field containing energy that will instantly disappear back into the source through the switch that turns the circuit off. This course uses what is called the \"passive\" sign convention for power. Energy put into a circuit by a power supply is negative, energy leaving a circuit is positive. Power (the flow of energy) computations are an important part of this course. The symbol for power is w (for work) and the units are Watts or W.
# Circuit Theory/Circuit Basics ## Circuits **Circuits** (also known as \"networks\") are collections of circuit elements and wires. Wires are designated on a schematic as being straight lines. Nodes are locations on a schematic where 2 or more wires connect, and are usually marked with a dark black dot. Circuit Elements are \"everything else\" in a sense. Most basic circuit elements have their own symbols so as to be easily recognizable, although some will be drawn as a simple box image, with the specifications of the box written somewhere that is easy to find. We will discuss several types of basic circuit components in this book. ## Ideal Wires For the purposes of this book, we will assume that an ideal wire has zero total resistance, no capacitance, and no inductance. A consequence of these assumptions is that these ideal wires have infinite bandwidth, are immune to interference, and are --- in essence --- completely uncomplicated. This is not the case in real wires, because all wires have at least some amount of associated resistance. Also, placing multiple real wires together, or bending real wires in certain patterns will produce small amounts of capacitance and inductance, which can play a role in circuit design and analysis. This book will assume that all wires are ideal. ## Ideal Junctions or Nodes !Nodes are areas where the Electromotive Force is the same. Nodes are also called \"junctions\" in this book in order to make a distinction between Node analysis, Kirchhoff\'s current law and discussions about a physical node itself. Here a physical node is discussed. A junction is a group of wires that share the same electromotive force (not voltage). Wires ideally have no resistance, thus all wires that touch wire to wire somewhere are part of the same node. The diagram on the right shows two big blue nodes, two smaller green nodes and two trivial (one wire touching another) red nodes. Sometimes a node is described as where two or more wires touch and students circle where wires intersect and call this a node. This only works on simple circuits. One node has to be labeled ground in any circuit drawn before voltage can be computed or the circuit simulated. Typically this is the node having the most components connected to it. Logically it is normally placed at the bottom of the circuit logic diagram. Ground is not always needed physically. Some circuits are floated on purpose. Node Quiz ## Measuring instruments **Voltmeters and Ammeters** are devices that are used to measure the voltage across an element, and the current flowing through a wire, respectively. ### Ideal Voltmeters An ideal voltmeter has an infinite resistance (in reality, several megaohms), and acts like an open circuit. A voltmeter is placed across the terminals of a circuit element, to determine the voltage across that element. In practice the voltmeter siphons enough energy to move a needle, cause thin strips of metal to separate or turn on a transistor so a number is displayed. ### Ideal Ammeters An ideal ammeter has zero resistance and acts like a short circuit. Ammeters require cutting a wire and plugging the two ends into the Ammeter. In practice an ammeter places a tiny resistor in a wire and measures the tiny voltage across it or the ammeter measures the magnetic field strength generated by current flowing through a wire. Ammeters are not used that much because of the wire cutting, or wire disconnecting they require. ## Active, Passive & ReActive The elements which are capable of delivering energy or which are capable to amplify the signal are called \"Active elements\". All power supplies fit into this category. The elements which will receive the energy and dissipate it are called \"Passive elements\". Resistors model these devices. Reactive elements store and release energy into a circuit. Ideally they don\'t either consume or generate energy. Capacitors, and inductors fall into this category. ## Open and Short Circuits ### Open No current flows through an open. Normally an **open** is created by a bad connector. Dust, bad solder joints, bad crimping, cracks in circuit board traces, create an **open**. Capacitors respond to DC by turning into **opens** after charging up. Uncharged inductors appear as **opens** immediately after powering up a circuit. The word **open** can refer to a problem description. The word **open** can also help develop an intuition about circuits. Typically the circuit stops working with opens because 99% of all circuits are driven by voltage power sources. Voltage sources respond to an open with no current. Opens are the equivalent of clogs in plumbing .. which stop water from flowing. On one side of the open, EMF will build up, just like water pressure will build up on one side of a clogged pipe. Typically a voltage will appear across the open. ### Short A voltage source responds to a **short** by delivering as much current as possible. An extreme example of this can be seen in this ball bearing motor video. The motor appears as a short to the battery. Notice he only completes the short for a short time because he is worried about the car battery exploding. Maximum current flows through a **short**. Normally a **short** is created by a wire, a nail, or some loose screw touching parts of the circuit unintentionally. Most component failures start with heat build up. The heat destroys varnish, paint, or thin insulation creating a **short**. The **short** causes more current to flow which causes more heat. This cycle repeats faster and faster until there is a puff of smoke and everything breaks creating an **open**. Most component failures start with a **short** and end in an **open** as they burn up. Feel the air temperature above each circuit component after power on. Build a memory of what normal operating temperatures are. Cold can indicate a short that has already turned into an open. An uncharged capacitor initially appears as a **short** immediately after powering on a circuit. An inductor appears as a **short** to DC after charging up. The **short** concept also helps build our intuition, provides an opportunity to talk about electrical safety and helps describe component failure modes. A **closed** switch can be thought of as short. Switches are surprisingly complicated. It is in a study of switches that the term **closed** begins to dominate that of **short**.
# Circuit Theory/Resistors ## Resistors Mechanical engineers seem to model everything with a spring. Electrical engineers compare everything to a **Resistor**. Resistors are circuit elements that resist the flow of current. When this is done a voltage appears across the resistor\'s two wires. A pure resistor turns electrical energy into heat. Devices similar to resistors turn this energy into light, motion, heat, and other forms of energy. ![](Resistor_schema.png "Resistor_schema.png") Current in the drawing above is shown entering the + side of the resistor. Resistors don\'t care which leg is connected to positive or negative. The + means where the positive or red probe of the volt meter is to be placed in order to get a positive reading. This is called the \"positive charge\" flow sign convention. Some circuit theory classes (often within a physics oriented curriculum) are taught with an \"electron flow\" sign convention. In this case, current entering the + side of the resistor means that the resistor is removing energy from the circuit. This is good. The goal of most circuits is to send energy out into the world in the form of motion, light, sound, etc. ## Resistance **Resistance** is measured in terms of units called \"Ohms\" (volts per ampere), which is commonly abbreviated with the Greek letter Ω (\"Omega\"). Ohms are also used to measure the quantities of *impedance* and *reactance*, as described in a later chapter. The variable most commonly used to represent resistance is \"r\" or \"R\". Resistance is defined as: $$r = {\rho L \over A}$$ where ρ is the resistivity of the material, L is the length of the resistor, and A is the cross-sectional area of the resistor. ## Conductance **Conductance** is the inverse of resistance. Conductance has units of \"Siemens\" (S), sometimes referred to as mhos (ohms backwards, abbreviated as an upside-down Ω). The associated variable is \"G\": $$G = \frac{1}{r}$$ Before calculators and computers, conductance helped reduce the number of hand calculations that had to be done. Now conductance and it\'s related concepts of admittance and susceptance can be skipped with matlab, octave, wolfram alpha and other computing tools. Learning one or more these computing tools is now absolutely necessary in order to get through this text. ## Resistor terminal relation right\|framed\|A simple circuit diagram relating current, voltage, and resistance The drawing on the right is of a battery and a resistor. Current is leaving the + terminal of the battery. This means this battery is turning chemical potential energy into electromagnetic potential energy and dumping this energy into the circuit. The flow of this energy or power is negative. Current is entering the positive side of the resistor even though a + has not been put on the resistor. This means electromagnetic potential energy is being converted into heat, motion, light, or sound depending upon the nature of the resistor. Power flowing out of the circuit is given a positive sign. The relationship of the voltage across the resistor V, the current through the resistor I and the value of the resistor R is related by ohm\'s law: $$V=R*I$$ A resistor, capacitor and inductor all have only two wires attached to them. Sometimes it is hard to tell them apart. In the real world, all three have a bit of resistance, capacitance and inductance in them. In this unknown context, they are called two terminal devices. In more complicated devices, the wires are grouped into ports. A two terminal device that expresses Ohm\'s law when current and voltage are applied to it, is called a resistor. ## Resistor Safety Resistors come in all forms. Most have a maximum power rating in watts. If you put too much through them, they can melt, catch fire, etc. Resistance is an electrical passive element which oppose the flow of electricity. Air can be considered as one of the resistances. Air is used as a resistance in Lightning Arrestors. Also vacuum also is used as a resistor. ## Example Suppose the voltage across a resistor\'s two terminals is 10 volts and the measured current through it is 2 amps. What is the resistance? If $v=iR$ then $R = v/i = 10V/2A = 5 ohms$
# Circuit Theory/Capacitors **Capacitors** are passive circuit elements that can be used to store energy in the form of an electric field. In the simplest case, a capacitor is a set of parallel metal plates separated by a *dielectric* substance. Dielectric used can be air or any other substance. ![](Capacitor.svg "Capacitor.svg"){width="200"} Electric charges build up on the opposite plates as a voltage is applied to the capacitor. With a constant voltage across the capacitor there will be no change in electric charge and thus the steady-state current becomes zero. Stored energy can be discharged from a capacitor by connecting its terminals with a wire. Big capacitors can create lightening bolts, so tape the wire to the end of a long wooden stick. ### Capacitance **Capacitance** is defined as the capability of a capacitor to store the charge of a voltage. Capacitance is measured in units called \"Farads,\" abbreviated by an \"F\". The ratio of charge over voltage gives a value of capacitance $$C = \frac{q}{v}$$ ### Capacitor Terminal Relation The relationship between the current and the voltage of a capacitor is: $$i = C\frac{dv}{dt}$$ The real world disturbs a capacitor by changing the voltage across it rapidly. This instantly turns the capacitor into a short. The capacitor eventually catches up to the changed condition, the voltage stops changing, the current drops to zero and the capacitor acts like an open. ### Capacitor Safety The bigger a capacitor is, the more dangerous it is. A capacitor can continue storing its energy after the circuit is turned off. A capacitor the size of a soda bottle can throw a person across the room and/or damage nerves. Touching a capacitor the size of a kitchen trash destroyed a persons arms to the point they were cut off at the shoulders. Touching a capacitor the size of an oil drum has killed people. Super capacitors are packing more power into smaller, lighter objects. If capacitor is connected to a circuit wrong, it can explode youtube video. A leyden jar is a capacitor. Aluminum foil of about 200 mm by 450 mm placed on either side of glass can store charge. If charged with a static electricity generator such as a Wimshurst machine can cause the glass, at the edges of the aluminum foil to shatter into little shards like a grenade exploding. ### Example Problem: Given a current of 10 amps flowing through a 1uF capacitor for 2 us, what is the voltage across the capacitor? Solution: The problem appears to be a capacitor hit by a pulse of current: $i(t) = \begin{cases} 0, & \text{for } t {\leq} 0\\ 10, & \text{for } 0 < t {\leq} .000002\\ 0, & \text{for } .000002 < t \end{cases}$ The initial voltage across the capacitor is not given. Assume it is zero for time less than 0. While current is flowing into the capacitor it is going to charge. When the current stops, the capacitor will hold it\'s charge and the voltage will remain constant. The charging period requires transforming\ $i = C\frac{dv}{dt}$\ into the integral\ $v(t) = \frac{\int\limits_{0}^{t}i({\tau})\,d{\tau}}{C}$ The solution involves an integral: $v(t) = \begin{cases} 0, & \text{for } t {\leq} 0\\ \frac{\int\limits_{0}^{t}10\,d{\tau}}{.000001}, & \text{for } 0 < t {\leq} .000002\\ v(.000002), & \text{for } .000002 < t \end{cases}$ To calculate the answer, the integral needs to be evaluated twice (links are to wolfram alpha): - once with the limits 0,t - second with the limits 0,0.000002 This results in the solution$$v(t) = \begin{cases} 0 \text{ volts}, & \text{for } t {\leq} 0 \text{ seconds}\\ 10^7t \text{ volts}, & \text{for } 0 < t {\leq} .000002 \text{ seconds}\\ 20 \text{ volts}, & \text{for } .000002 < t \text{ seconds} \end{cases}$$
# Circuit Theory/Inductors An **inductor** is a coil of wire that stores energy in the form of a magnetic field. The magnetic field depends on current flowing to \"store energy.\" If the current stops, the magnetic field collapses and creates a spark in the device that is opening the circuit. The large generators found in electricity generation can create huge currents. Turning them off can be dangerous MIT EMF Youtube video. There are no dangers storing them. ![](Inductor_diagram.svg "Inductor_diagram.svg") ### Inductance **Inductance** is the capacity of an inductor to store energy in the form of a magnetic field. Inductance is measured by units called \"Henries\" which is abbreviated with a capital \"H,\" and the variable associated with inductance is \"L\". Inductance is the ratio of magnetic flux (symbol $\Phi_B$) to current: $L = \Phi_B/i$ $\Phi_B$ measures the strength of a magnetic field just like charge measures the strength of an electric field. ### Inductor Terminal Relation The relationship between inductance, current, and voltage through an inductor is given by the formula: $$v = L\frac{di}{dt}$$ ### Inductor Safety Inductors found in power plants can store energy, but inductors found at room temperature will not store energy. An isolated inductor in storage can not kill someone like a capacitor can. Inductors do cause problems. The first is economic. A good inductor is much more expensive than a capacitor. In some situations, a collection of other components can replace an inductor at less cost. Typical inductors are built with copper which increases in cost as supply on earth dwindles. Inductors can create spikes and sparks video when turning off that can destroy other electrical components. They can destroy switches. They can vaporize metal. The biggest inductors at room temperature are found in electric motors. When motors are turned on or off they create what is called a \"back EMF.\" Ideally Back EMF is a voltage spike of infinite voltage. Diodes, capacitors and resistors are used to turn the back EMF into heat on discharge may make starting up the motor a problem. Some electronic speed controlers (ESCs) in UAVs and quadcopters pulse the motor to deliberately and measure the back EMF to figure out what direction the motor is going to spin in. This reduces the need of hall-effect probes and thus reduces the cost of the motor. ### Inductor Example Question: Given the current through a 10mH inductor is $i(t) = 5t*e^{-1000t}$ amps, what is the voltage? Solution: No need to know the initial conditions because the solution is a derivative: $v(t) = L di/dt$. Using Wolfram Alpha, the solution is $v(t) = .01*e^{-1000t}(5-5000t)$ volts.
# Circuit Theory/Power supplies ## Sources All sources can be alternating current (AC) or direct current (DC). ### Voltage Sources Many power sources or supplies such as batteries or wall outlets are voltage sources. This means they vary the current to keep the voltage constant. AAA and AA batteries ideally put out 1.5 volts at all times. Most of the time they are open (not connected to anything). Eventually they are connected to a circuit that draws current from them. An ideal AAA or AA battery could deliver infinite amount of current. A real world battery tries to deliver infinite current if shorted, but usually heats up, catches on fire or explodes. ### Current Sources Most consumers have never had an first hand experience with a current source. Neither will most students in the first semester of Circuit Theory course\'s lab section. Current sources are the opposite of voltage sources: they keep the current constant by varying the voltage. This makes them very dangerous. Current sources would require a wire shorting them at all times. If the shorting wire were removed, the ideal currents source would create the biggest, scariest lightning bolt instantaneously. Current sources are important conceptually in order to understand ideal transistors and op amps. This is why they are part of circuit theory from the very beginning. Working with current sources inside op amps and transistors has few safety risks. ### Power Supply Terminal Relation There is no relationship between the current voltage through a power supply. A 5 volt DC power supply will vary it\'s current based upon the circuit attached. A 5 Amp DC power supply will vary it\'s voltage based upon the circuit attached. A power supply is a dependent device \... dependent upon the independent resistors, capacitors, inductors that are arranged in a circuit and attached to it. ### Power/Energy Equations At any given instant, the power flowing through a two terminal device is: $p(t) = v(t)i(t)$ The average power being consumed during time t is: $p_{avg}(t)= 1/t * \int\limits_{0}^{t}{\tau}*p({\tau})\, d{\tau}$\ If p(t) is Sinusoidal, then the upper limit is one time period.\ Remember that the period of $sin(wt+{\theta})$ is $2{\pi}/w$ The energy consumed or work done during time t is similar: $w(t)= \int\limits_{0}^{t}p({\tau})\, d{\tau}$ All other power concepts derive from the above. For example: - If the voltage and current are constant (DC), then $p(t) = p_{avg}(t) = iv = i^2R = v^2/R$ - If the voltage and current are Sinusoidal (AC) and enough time has passed that the circuit is steady state, then math can be simplified, but first have to learn phasors. However there are peak power, average power and power factor concepts that need to be understood to develop an intuition about circuits and understand the fictitious \"flux capacitor\". - If the voltage and current are in any pattern and are steady state, then the above math can be simplified. ### Power Supply Safety There are many different types of power supplies that each have different safety concerns. LiPo batteries can explode/catch on fire if over charged. Here is a video of someone exploring 244 dead 9 volt batteries creating a 2000 volt power supply. If shorted, voltage supplies can do the same. If opened, current sources (very rare) can do the same. In most labs, the power supplies are protected by a fuse like a home is. Shorts cause a circuit breaker to trip, fuse to burn out, relay to cut off the circuit, etc. But batteries are typically not protected. Most power supplies just stop working. ### Example 1 Find the average power consumed by a 20 ohm resistor when a current $i(t) = \frac{4}{3}sin(3t)$ is applied. Solution: Assume the initial average power is 0. Actually this makes no rational sense. But every time an integral is computed, consider the possibility. $v(t) = i(t)*r$ \...\... from resistor terminal relation\ $p(t) = i(t)*v(t)=i(t)*i(t)*r = i(t)^2*r$ \..... from definition of power\ $p_{avg}=\frac{1}{t}\int\limits_{0}^{t}{\tau}*i({\tau})^2*r\, d{\tau}$ \...\... average power definition\ $t=\frac{2\pi}{3}$ \.... definition of period\ $p_{avg} = \frac{20*3}{2\pi}\int\limits_{0}^{\frac{2\pi}{3}}{\tau}*(\frac{4}{3}sin(3{\tau}))^2\, d{\tau} = 8.36 watts$ \... using wolfram ### Example 2 Given the two graphs of voltage and current, find and graph the power and energy for t=0 to t=8. !created with desmos !created with desmos !created with desmos Solution: #### Turn the Question into Math convert the voltage and current graphs to equations: $v(t) \text{, } i(t) = \begin{cases} v=0 \text{, } i=0, & \text{for } t {\leq} 0\\ v=2 \text{, } i=2, & \text{for } 0 < t {\leq} 2\\ v=2-2*(t-2) \text{, } i=-2, & \text{for } 2 < t {\leq} 4\\ v=-2 \text{, } i=2, & \text{for } 4 < t {\leq} 5\\ v=2*(t-5)-2 \text{, } i=2, & \text{for } 5 < t {\leq} 6\\ v=2*(t-5)-2 \text{, } i=-2, & \text{for } 6 < t {\leq} 7\\ v=2 \text{, } i=-2, & \text{for } 7 < t {\leq} 8\\ \end{cases}$ #### Find the Power by Multiplying Now do the math $p(t)=v(t)i(t)$ to find the power: $p(t) = \begin{cases} 0, & \text{for } t {\leq} 0\\ 4, & \text{for } 0 < t {\leq} 2\\ 4*(t-2)-4, & \text{for } 2 < t {\leq} 4\\ -4, & \text{for } 4 < t {\leq} 5\\ 4*(t-5)-4, & \text{for } 5 < t {\leq} 6\\ 4-4*(t-5), & \text{for } 6 < t {\leq} 7\\ -4, & \text{for } 7 < t {\leq} 8\\ \end{cases}$ #### Find the Energy by Integrating Now comes the more difficult part. Energy $w(t)= \int\limits_{0}^{t}{\tau}*p({\tau})\, d{\tau}$. Integrate from the initial condition to t rather than a specific value. Evaluate the integrals using wolfram alpha. $w(t) = \begin{cases} 0, & \text{for } t {\leq} 0\\ \int\limits_{0}^{t}4\, d{\tau}= 4t, & \text{for } 0 < t {\leq} 2\\ \int\limits_{2}^{t}(4*({\tau}-2)-4)\, d{\tau}=2(t^2-6t+8), & \text{for } 2 < t {\leq} 4\\ \int\limits_{4}^{t}(-4)\, d{\tau}=-4(t-4), & \text{for } 4 < t {\leq} 5\\ \int\limits_{5}^{t}(4*({\tau}-5)-4)\, d{\tau}=2(t^2-12t+35), & \text{for } 5 < t {\leq} 6\\ \int\limits_{6}^{t}(4-({\tau}-5)*4)\, d{\tau}=-2(t-6)^2, & \text{for } 6 < t {\leq} 7\\ \int\limits_{7}^{t}(-4)\, d{\tau}=-4(t-7), & \text{for } 7 < t {\leq} 8\\ \end{cases}$ #### Find the integration constant and next initial condition Find the first initial condition from the problem statement. Setting beginning t to the initial condition and find the integration constant. Find the next initial condition by setting the t to the end value of the defined segment. The goal is to find the cumulative energy, not the change in energy of each segment. This is done by making sure that the end point of the previous segment matches the value at the beginning of the next segment. When graphed, there should be no vertical jumps. $w(t) = \begin{cases} 0 \text{ the assumed initial condition}, & \text{for } t {\leq} 0\\ 2(0)^2 + C = 0 \Rightarrow C=0 \text{ and } 4*2+0 = 8, & \text{for } 0 < t {\leq} 2\\ 2(2^2-6*2+8) + C = 8 \Rightarrow C=8 \text{ and } 2(4^2-6*4+8) + 8 = 8, & \text{for } 2 < t {\leq} 4\\ -4*(4-4) + C = 8 \Rightarrow C=8 \text{ and } -4*(5-4)+8 = 4, & \text{for } 4 < t {\leq} 5\\ 2*(5^2-12*5+35) + C = 4 \Rightarrow C=4 \text{ and } 2(6^2-12*6+35)+4 = 2, & \text{for } 5 < t {\leq} 6\\ -2(6-6)^2 + C = 2 \Rightarrow C= 2 \text{ and } -2(7-6)^2 + 2 = 0, & \text{for } 6 < t {\leq} 7\\ -4(7-7) + C = 0 \Rightarrow C=0 \text{ and } -4(8-7) +0 = -4, & \text{for } 7 < t {\leq} 8\\ \end{cases}$ #### Graphing and Checking the Solution !energy in joules versus time in seconds desmos Graphing is a form of checking your work. Without graphing, the intuitive process can not kick in. $w(t) = \begin{cases} 0, & \text{for } t {\leq} 0\\ 4t, & \text{for } 0 < t {\leq} 2\\ 2(t^2-6t+8)+8, & \text{for } 2 < t {\leq} 4\\ -4(t-4)+8, & \text{for } 4 < t {\leq} 5\\ 2(t^2-12t+35)+4, & \text{for } 5 < t {\leq} 6\\ -2(t-6)^2+2, & \text{for } 6 < t {\leq} 7\\ -4(t-7), & \text{for } 7 < t {\leq} 8\\ \end{cases}$ #### Building Intuition When doing a long problem like this one, it is important to build one\'s intuition. There are two basic ways to do this: - Think about power supply experiences and ask \"What does this imply?\" - Add expectation feelings and emotion. Think of experiences, the emotion, the happening, not the end product of things you like. Attach the emotion associated with them to the problem at hand. Mix the doing them with solving the problem. - Tell a story, then check the story against the graphs. What kind of device are we looking at? Has to be an element that both consumes and generates electricity. The current is switching back and forth every two seconds, thus it is most likely a motor driving some kind of back and forth motion. Motors are essentially an inductor. An inductor is going to vary the voltage all over the place to try and keep the current constant \... like a current source. The motor is working as planned (consuming energy) for the first four seconds sort of. During the second four seconds, something else is happening. It looks like a 2 year old has grabbed the fan that is trying to oscillate back and forth and is forcing it in the opposite direction. This could cause the motor to turn into a generator, hence the voltage variations, the negative energy and power.
# Circuit Theory/TR A terminal is a place where a wire comes out of an electrical component. Terminal relations for the 2 wire devices studied so far (resistors, capacitors and inductors), describe the voltage across the two terminals and the current entering and leaving the terminals (which is always the same). The terminal relations for a resistor are $v = i * R$ (called ohms law) The terminal relations for a capacitor are $i = C * dv/dt$ The terminal relations for an inductor are $v = L * di/dt$ A power supply doesn\'t have a terminal relationship or equation relating current and voltage. Either the current is constant (current supply) or voltage is constant (voltage supply). The power is varied depending upon what the circuit asks for. One of the best places to build up your intuition or build your own animated circuit simulations is at falstad
# Circuit Theory/IV curves !The current--voltage characteristics of four devices: 100K ohm, 10 ohm, a P--N junction diode, and a battery with real world internal resistance. The horizontal axis is voltage drop, the vertical axis is current.{width="450"} These curves reflect that most circuits are designed with voltage as the independent variable; with voltage sources and currents being dependent variables. What this means is that the slopes of the IV curves are 1/R. So normally whereas normally horizontal is a slope of 0, it is now a slope of infinity. Ideally, a diode would turn on at 0 volts and go from horizontal to vertical instantly. Ideally, a voltage source would be a vertical line. Ideally, resistance does not change due to voltage or current and are thus straight lines. !transistor curves{width="400"} A transistor is understood through the above type of graph. The horizontal lines represent current source behavior. Notice how the current stays constant while the voltage changes. The angled straight lines coming out of the origin represent \"linear\" behavior where the transistor is operating like an amplifier. The horizontal lines are where the \"linear\" behavior stops and the current source behavior begins. Understanding what is controlling this and why the many blue lines starts with understanding what the three wires into a transmitter do: !Three wires into a transistor{width="400"} - S = source (of power .. connect to a voltage source) - G = gate (like the switch of a light switch .. more like a dimmer knob) - D = drain (current leaves .. connected to ground) - B = Body \... (often connected to the source) Think of S and D as the wires going into a light switch and G as the dimmer knob. Each blue line represents a position of the dimmer switch. The gate or dimmer switch determines the amount of amplification and the value of the current source behavior. So what are the dependent and independent variables above? There are two independent variables: gate V~g~ and source voltage V~s~. Right now it is not important to understand how V~g~ is physically measured. The important question is \"What is the nature of the current source behavior? It seems to be dependent on two things.\" An ideal, independent current source manipulates the voltage to keep the current constant. The current source behavior above is dependent upon the Gate. The symbols for a transistor are:
# Circuit Theory/Transistor symbols ## Circuit symbols There are lots of different types of transistors. The most popular is a MOSFET and within this family there are lots of possibilities. The goal right now is not to understand the differences and what all the lines mean. Look at them and see that normally there are three wires associated with them. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------------------- ----------- ![](JFET_P-Channel_Labelled.svg "JFET_P-Channel_Labelled.svg"){width="80"} ![](IGFET_P-Ch_Enh_Labelled.svg "IGFET_P-Ch_Enh_Labelled.svg"){width="80"} ![](IGFET_P-Ch_Enh_Labelled_simplified.svg "IGFET_P-Ch_Enh_Labelled_simplified.svg"){width="80"} ![](Mosfet_P-Ch_Sedra.svg "Mosfet_P-Ch_Sedra.svg"){width="80"} ![](IGFET_P-Ch_Dep_Labelled.svg "IGFET_P-Ch_Dep_Labelled.svg"){width="80"} P-channel ![](JFET_N-Channel_Labelled.svg "JFET_N-Channel_Labelled.svg"){width="80"} ![](IGFET_N-Ch_Enh_Labelled.svg "IGFET_N-Ch_Enh_Labelled.svg"){width="80"} ![](IGFET_N-Ch_Enh_Labelled_simplified.svg "IGFET_N-Ch_Enh_Labelled_simplified.svg"){width="80"} ![](Mosfet_N-Ch_Sedra.svg "Mosfet_N-Ch_Sedra.svg"){width="80"} ![](IGFET_N-Ch_Dep_Labelled.svg "IGFET_N-Ch_Dep_Labelled.svg"){width="80"} N-channel JFET MOSFET enh MOSFET enh (no bulk) MOSFET dep ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------------------- -----------
# Circuit Theory/Dependent sources !The four types of dependent sources \... the control variable is on the left, the output variable is on the right{width="500"} Electronic amplifiers use two variables: current and voltage. Either can be used as input, and either as output leading to four types of amplifiers. In idealized form they are represented by each of the four types of dependent source used in linear analysis, as shown in the figure, namely: Input Output Dependent source Amplifier type ------- -------- -------------------------------------------- ---------------------------- **I** **I** current controlled current source **CCCS** current amplifier **I** **V** current controlled voltage source **CCVS** transresistance amplifier **V** **I** voltage controlled current source **VCCS** transconductance amplifier **V** **V** voltage controlled voltage source **VCVS** voltage amplifier Each type of amplifier in its ideal form has an ideal input and output resistance that is the same as that of the corresponding dependent source:[^1] Amplifier type Dependent source Input impedance Output impedance ---------------------- ------------------ ----------------- ------------------ **Current** **CCCS** **0** **∞** **Transresistance** **CCVS** **0** **0** **Transconductance** **VCCS** **∞** **∞** **Voltage** **VCVS** **∞** **0** In practice the ideal impedances are only approximated. For any particular circuit, a small-signal analysis often is used to find the impedance actually achieved. A small-signal AC test current *I~x~* is applied to the input or output node, all external sources are set to zero, and the corresponding alternating voltage *V~x~* across the test current source determines the impedance seen at that node as *R = V~x~ / I~x~*. ## References [^1]: It is a curiosity to note that this table is a \"Zwicky box\"; in particular, it encompasses all possibilities.
# Circuit Theory/Operational Amplifiers !22 transistors making up an operational amplifier An operational amplifier is a circuit of about 22 transistors organized with the goal of producing an amplifier. $$V_{\!\text{out}} = A_{OL} \, (V_{\!+} - V_{\!-})$$ Ideally the open loop gain (A~OL~) is infinite. In reality the output will \"rail\" to either the positive or negative supply. Open loop means that there are no devices connecting the output to the inverting input (- or negative input). In practice most op-amps are used in \"closed-loop\", \"negative feedback\" configuration. Closed loop designs (in the first approximation) require remembering two \"golden rules\": : I. The output attempts to do whatever is necessary to make the voltage difference between the inputs zero. : II\. The inputs draw no current. Op-amp Pins Symbol ----------------------------------------------------------------------------- --------------------------------------------------------------------------- ------------------------------------------------------- ![](Schematics_voltampopamp.jpg "Schematics_voltampopamp.jpg"){width="100"} ![](Generic_741_pinout_top.png "Generic_741_pinout_top.png"){width="300"} ![](Opamppinouts.png "Opamppinouts.png"){width="200"} ## Subtraction !Subtraction or \"Differential Amplifier\" Under the condition that the *R*~*f*~ /*R*~1~ = *R*~*g*~ /*R*~2~, the output expression becomes: $$V_{\text{out}} = \frac{ R_{\text{f}} }{ R_1 } (V_{\text{2}} - V_{\text{1}})\,$$ \"A\" is the *differential gain* of the circuit. ## Operating Point Op Amps are balanced: : : The supplies are +V and -V, not V_s and ground. This is why many power supplies have both +15 and -15 volts or +5 and -5 volts. : They are made with almost equal numbers of PNP and NPN transistors. : They are best operated where the output is around 0 volts. Don\'t try to fit them into a digital circuit. ## Typical Applications Op Amps are typically used to amplify. !Non-Inverting !Inverting Vacuum tubes (light bulbs with a grid and three wires) (1907 by Lee De Forest) solved the existing need for amplification of a weak data signal. But vaccuum tubes broke in less than a year. Many famous scientist/engineer\'s first experience with technology was radio repair including Feynman and Armstrong. Transistors came next in 1951 created by Shockley. They enabled the transistor radio \... that could be held in the palm of one\'s hand. Transistors replaced vacuum tubes in almost all devices. Operational Amplifiers emerged out of math, not inventor work shops. They emerged from the needs that MatLab fills today, not a simple calculator. Attempts were made to build them with vaccum tubes and every known transistor. The 741 op amp took until transistors matured .. 1968. The 741 is still in production. Op amps are found where the difference between two devices sensing the environment are needed. They are used to replace inductors in circuits because they are cheaper and lighter. ## Inverting or Not? Op amps are drawn with the non-inverting input on top if the design goal is an output that same polarity as the input. Why isn\'t it just called \"positive input\"? Why isn\'t positive always on top? The reason is that most op amps involve negative feedback. Most designs require circuitry to be connected to the \"inverting\" input. If possible the \"non-inverting\" input is grounded. This means that the sweet middle operating point is more plausible. But the most important reason comes from multiple op amp designs. The negative or positive nature of the output can be more easily seen if the inverting and non-inverting inputs flip based upon the immediate output design intention. Negative output means that eventually a final op amp may be needed to flip the output positive. ## Local Feedback Op amp circuits are easy to design as long as the feedback is kept local \... meaning the feedback loops back over only one local op amp. The feedback does not span outputs. Only outputs connected to inputs connect two op amps. ## Buffer !buffer configuraton Buffers are needed to re-invigorate a signal. Fanout is when an output is connected to too many inputs. Buffers can restore the power needed to drive the rest of the circuit. ## Adder !Adder configuration A adder sums several (weighted) voltages: $$V_{\text{out}} = -R_{\text{f}} \left( \frac{V_1}{R_1} + \frac{V_2}{R_2} + \cdots + \frac{V_n}{R_n} \right)$$ When $R_1 = R_2 = \cdots = R_n$, and $R_{\text{f}}$ independent $$V_{\text{out}} = -\frac{R_{\text{f}}}{R_1} ( V_1 + V_2 + \cdots + V_n ) \!\$$ When $R_1 = R_2 = \cdots = R_n = R_{\text{f}}$ $$V_{\text{out}} = -( V_1 + V_2 + \cdots + V_n ) \!\$$ ## Integrator !integrator $$V_{\text{out}} = -\int_0^t \frac{ V_{\text{in}} }{RC} \, \operatorname{d}t + V_{\text{initial}}\,$$ (where $V_{\text{in}}$ and $V_{\text{out}}$ are functions of time, $V_{\text{initial}}$ is the output voltage of the integrator at time *t* = 0.) There are several potential problems with this circuit. - It is usually assumed that the input $V_{\text{in}}$ has zero DC component (i.e., has a zero average value). Otherwise, unless the capacitor is periodically discharged, the output will drift outside of the operational amplifier\'s operating range. - Even when $V_{\text{in}}$ has no offset, the leakage or bias currents into the operational amplifier inputs can add an unexpected offset voltage to $V_{\text{in}}$ that causes the output to drift. Balancing input currents **and** replacing the non-inverting ($+$) short-circuit to ground with a resistor with resistance $R$ can reduce the severity of this problem. - Because this circuit provides no DC feedback (i.e., the capacitor appears like an open circuit to signals with $\omega = 0$), the offset of the output may not agree with expectations (i.e., $V_{\text{initial}}$ may be out of the designer\'s control with the present circuit). - The initial voltage is typically enforced by a power supply in parallel with the capacitor that is switched out of the circuit at t=0. Many of these problems can be made less severe by adding a *large* resistor $R_F$ in parallel with the feedback capacitor. At significantly high frequencies, this resistor will have negligible effect. However, at low frequencies where there are drift and offset problems, the resistor provides the necessary feedback to hold the output steady at the correct value. In effect, this resistor reduces the DC gain of the \"integrator\" -- it goes from infinite to some finite value $R_F/R$. ## Differentiator !Differentiator This circuit differentiates the (inverted) signal over time. $$V_{\text{out}} = -RC \,\frac{\operatorname{d}V_{\text{in}} }{ \operatorname{d}t}$$ ## Inductor Replacement !Gyrator .. replaces an inductor Simulates an inductor. The circuit exploits the fact that the current flowing through a capacitor behaves through time as the voltage across an inductor. The capacitor used in this circuit is smaller than the inductor it simulates and its capacitance is less subject to changes in value due to environmental changes. This circuit is unsuitable for applications relying on the input impedance seen left to right and indicated by the red $Z_{in}$ symbol is the same in both circuits. The output on the left could tell the difference between the op amp circuit and an inductor. Of course there would not be a magnetic field (for a motor or transformer) and any application relying on back EMF would not work.
# Circuit Theory/Analog Computer ## Goal Design an analog computer that generates a solution to this differential equation: $$a_2{d^2 v(t) \over dt^2} + a_1{d v(t) \over dt} + a_ov(t) = f(t)$$ : f(t) is the input, the bump the car is going over : v(t) is the output, the vertical motion of the car in response to the bump : a~2~ is related to the spring constant of a shock absorber : a~1~ is related to the damping coefficient and viscosity of the oil : a~o~ is varied depending upon the desired ride ```{=html} <!-- --> ``` : The goal is to vary a~2~, a~1~, and a~o~ electronically, rather than build many models physically. This is modeling as done before WWII instead of using matlab or similar software. ```{=html} <!-- --> ``` : Modern applications of this include control systems (opening and closing valves in an industrial process, turning off and on motors, controlling a nuclear power plant). ## Organizing At first glance, need 6 op-amps, 2 for differentiation, 3 for scaling, 1 for adding. But the adder can do scaling also. Need to think about the overall circuit design too. The desired output is v(t). The function f(t) is an input. The derivatives are temporary values that are built from the output being feed back. So the math is going to look something like this: $$\frac{a_2}{a_o}{d^2 v(t) \over dt^2} + \frac{a_1}{a_o}{d v(t) \over dt} -\frac{1}{a_o}f(t) = v(t)$$ Need to feed the output back into the input also \... and will take first derivative, then second, then feed into the adder with f(t). So the math would look more like this: $$-(-\frac{a_1}{a_o}{d v(t) \over dt} - \frac{a_2}{a_o}{d^2 v(t) \over dt^2} + \frac{1}{a_o}f(t)) = v(t)$$ <File:Op-Amp> Differentiating Amplifier.svg\|this takes the input and differentiates it so output is $-{d v(t) \over dt}$ <File:Op-Amp_Inverting_Amplifier.svg%7Cthis> takes output of the first derivative which is negative and makes it positive again, so the second derivative will be negative also <File:Op-Amp> Differentiating Amplifier.svg\|this generates the second derivative ${d^2 v(t) \over dt^2}$ which is now negative like the first derivative <File:Op-Amp> Summing Amplifier.svg\|this will take the negative ${d v(t) \over dt}$ and the negative (because was inverted) $-{d^2 v(t) \over dt^2}$ terms and adds them to a positive f(t), scaling appropriately to generate $v(t)$ ## Simulating ![](ShockAbsorber1.png "ShockAbsorber1.png") Assume the output of OA4 is v(t). Then the output of OA1 is: $$-R_1C_1{d v(t) \over dt}$$ The output of OA2 is: $$-\frac{R_3}{R_2}(-R_1C_1{d v(t) \over dt}) = \frac{R_3R_1}{R_2}C_1{d v(t) \over dt}$$ The output of OA3 is: $$-R_4C_2{d (\frac{R_3R_1}{R_2}C_1{d v(t) \over dt}) \over dt} = -\frac{R_4R_3R_1}{R_2}C_1C_2{d^2 v(t) \over dt^2}$$ Assume V~14~ is f(t). Then the output of OA4, the adder is: $$-R_8(\frac{f(t)}{R_7} + \frac{-\frac{R_4R_3R_1}{R_2}C_1C_2{d^2 v(t) \over dt^2}}{R_5} + \frac{-R_1C_1{d v(t) \over dt}}{R_{56}}) = \frac{R_8R_1}{R_{56}}C_1{d v(t) \over dt} + \frac{R_8R_4R_3R_1}{R_5R_2}C_1C_2{d^2 v(t) \over dt^2} - \frac{R_8}{R_7}f(t)$$ Comparing this to: $$\frac{a_1}{a_o}{d v(t) \over dt} + \frac{a_2}{a_o}{d^2 v(t) \over dt^2} - \frac{1}{a_o}f(t) = v(t)$$ We can see that: $$\frac{a_1}{a_0} = \frac{R_8R_1}{R_{56}}C_1$$ $$\frac{a_2}{a_o} = \frac{R_8R_4R_3R_1}{R_5R_2}C_1C_2$$ $$\frac{1}{a_0} = \frac{R_8}{R_7}$$ There are three knowns a~0~, a~1~, and a~2~, 10 unknowns and 3 equations. So the problem is under constrained, meaning that other requirements can be used to pick the resistor and capacitor values.
# Circuit Theory/Circuit Definition Circuit Analysis is reverse engineering. Given a circuit, figure out the currents, voltages, and powers associated with each component. The project or problem that produced the circuit or the purpose of the circuit is not of concern. Most circuits are designed to illustrate a concept or practice the math rather than do something useful. Towards the end of this book, the \"useful\" circuits are studied that related to wireless communication. ### Untangle First untangle a circuit. Flatten into two dimensions. Put all the components in the same orientation: up and down. ### Naming This is an exercise in naming unknowns. There are only two things to remember: - Devices in series share the same current. - Devices in parallel share the same voltage. The consequence of not doing this is merely another simple equation to write down and solve. Now name the voltages and currents following these rules: - Name series voltage with the same subscript as the component such as $v_{r1} v_{c1} v_{L1}$. Choose a different naming convention for the shared voltage of parallel components such as $v_1 v_2$. Do not guess the polarity of the voltage yet. - Name the parallel currents with the same subscript as the component such as $i_{r1} i_{c1} i_{L2}$. Choose a different subscript for the shared current of series circuits such as $i_1 i_2$. Don\'t put arrow heads on wires yet indicating current direction. - Don\'t forget to put voltages across current sources and name currents coming out of voltage sources. ### Loops Loops are the smallest circles of components. Count them. Don\'t count \"loops containing loops\" or \"loops of loops.\" Say there are 3 loops. Now any three loops of components can be considered (including loops containing loops) that follow this rule: *Collectively each component must be mentioned in a loop at least once.* Some loops are trivial. Components in parallel will form a loop, but they share the same voltage. If you call them a loop, then you will end up with an equation that says $V_{r1} -V_{r2}=0$. Don\'t count trivial loops unless you can not see devices sharing the same EMF difference. Draw a loop with a different color pen and name the loop something like $L_1 L_2 L_3$. Put an arrowhead describing the direction of the loop. Now go around the loop in the chosen direction, put a + on the wire entering each component and - on the wire leaving the component. Current supplies in parallel with a component will share the same voltage as the component so nothing needs to be done. Current supplies without a parallel component will need a voltage assigned to them. The polarity doesn\'t matter. But a polarity has to be chosen. Voltage supplies can be symbolized by alternating plates (long and short) or a circle with + and - in it. Assign + to the long plate, and - to the short plate. Otherwise use the + and - in the voltage source symbol. If two loops overlap, leave the first + and -. Don\'t put conflicting + and - signs on the same component. Don\'t use the word \"mesh\" here. \"Mesh analysis\" is covered later. It is a different type of analysis that is not as general, but often is much easier than Kirchhoff\'s Law. Kirchhoff\'s Law always works and is described next. ### Junctions A \"junction\" is a collection of wires at the same EMF (not voltage .. electro motive force is an absolute, voltage is relative). Wires touching each other have the same energy per charge (EMF) in them. Junctions stop at any component. Some \"Junctions\" are trivial. These are the junctions where a single wire connects only two components. Don\'t count these unless you can not identify series components \"sharing\" a current. Count the \"non-trivial\" \"Junctions.\" Say there are 3. Subtract 1. This makes 2. You can write two junction equations. There typically more than 2 possible junction equations. Make sure the two written mention all the currents at least once. At this point equations can be written around a node or a \"cut set\" which is similar to at big loop with smaller loops within it. Explore the electrical version of cut sets here. They can make analyzing just part of a circuit easier (discussed later). Again the equations have to include each unknown current at least once. Name the \"Junctions\" with symbols like $J_1 J_2$. Now put arrow heads for current direction for passive (resistors) and reactive (capacitors and inductors) components based upon the voltage polarity. The current should move from + to -. The arrow head should be into the + and out of the -. Current sources will already have a current direction. Voltage sources with a series component share the same current. The direction of this current is determined by the voltage polarity on the component. Voltage sources that don\'t have a series component can be given current in any direction. Remember that the polarity of these voltages and currents is capturing the circuit topology, not predicting the polarity of the ultimate numeric answer. Don\'t use the word \"node\" here. \"Node analysis\" is covered later. It is a different type of analysis that is not as general, but often is much easier than Kirchoff\'s Law. Kirchoff\'s Law always works and is described later.
# Circuit Theory/Kirchhoff's Law Kirchhoff\'s law is a method of finding the voltage across every device and the current through every device. It takes into account the circuit topology (series/parallel), multiple sources, sources of different types, and components of different types. Technician courses spend a lot of time developing an intuition that will eventually lead to an expertise that is beyond the \"design, theory, science\" scope of this course. Kirchhoff\'s law always works. It is the basis of all simulation software. The goal here is to be able to check, to develop estimations, and build up one\'s trust/understanding of simulation software. Kirchhoff\'s law starts with a drawing. The drawing is of a circuit that is labeled with voltage polarities and current directions, with loops and junctions as described earlier. Kirchhoff\'s circuit analysis can not start without this drawing. The circuit may be an existing one that is reversed engineered. The circuit may be a thought experiment that is exploring alternatives. Resistance, Capacitance, Inductance, and any voltage or current, any source voltage or current may be an unknown. For every unknown, there needs to be an equation according to linear algebra. Kirchhoff\'s laws find equations in three places: - Terminal Relations - Loops - Junctions ### Counting knowns and unknowns Look at the drawing and write down the symbols for each known and unknown. If an unknown write $= ?$ it. If a known, write $= value { ..} units$ next to it. Power supply values should be assigned symbols such as $V_{s1} V_{s2} I_{s1} I_{s2}$ and then given values if they are known. Count the number of unknowns. A component value (resistance, capacitance, inductance), a voltage or a current can be an unknown. This is how many equations there need to be. Count the number of components. Add the number of loops and junctions. This is how many equations there are. If the number of unknowns doesn\'t match, there is a problem. If there are too many equations, there are two possibilities: - problem is over constrained (a fixed numerical constant needs to be made variable, a requirement needs to be renegotiated in the design process) - there is a dependent equation (much more difficult, this is why there are all the rules for sign, direction, counting loops and junctions) If there are too many unknowns, these are the possibilities. - The problem is under constrained. Solve with symbols, make list of the independent variables that are going to be symbols in the answers and dependent variables that are going to equal something. Sometimes the entire problem is to be solved with symbols and there are no numbers. - If the problem is out of a text book, then re-read the problem perhaps there are other facts that can be turned into equations. - Make assumptions. Make them very clearly and loudly .. NOW at the beginning of the problem. ### Terminal Equations The terminal equations were covered earlier. Here are some additional points: - If the current is not going into the + voltage side, then add a negative sign. - Write the differential form, not the integral form of the terminal relation. - There are no terminal relations for independent supplies, dependent supplies do have a terminal relation. - Don\'t try to solve the equations that include differentials right now just write them. ### Loop Equations The principle of energy conservation implies that the sum of the electrical potential differences (voltage) around any closed loop is zero: $$\sum_{k=1}^n V_k = 0$$ Go around the loop in the direction labeled with your finger. If your finger enters the plus side first, the voltage (in the formula, not perhaps in the solution) is positive. If your finger enters the negative side first, the voltage is negative. There are two cases where the voltage will be negative: - a voltage source arbitrarily ended up negative - a previous loop labeled the voltages first and it happened to be in the opposite direction The current direction does not matter in the loop equations. Write an equation for each loop. The goal is not to guess the + or - voltage of the answer (a technician\'s goal). The goal is to get the + or - in the equation to correctly match the circuit. When finished, the last step is to look through the answers and see if they make sense from an intuitive point of view. That\'s it. ### Junction Equations The principle of electric charge conservation implies that at any \"junction\", the sum of the currents flowing into the note is zero. $$\sum_{k=1}^n {I}_k = 0$$ *n* is the total number of branches with currents attached to the \"junction.\" If the current is flowing into the node, make it positive. If current is flowing out of the node, make it negative. Check series sections for two different current symbols. Current should be the same in a series section. The goal of the + and - signs is to capture the circuit design in the equations. This has nothing to do with whether the ultimate current is flowing in or out of the node. Do not try to guess current direction either. ### What\'s Next Nothing. Kirchhoff\'s analysis falls apart because the number of equations increases dramatically as a circuit becomes more complex. This is not a problem for computers, but it is a problem for engineers and techs. The rest of this course is full of math, simplifications, quirks, tricks, tips, and shortcuts. All have limitations. All fail at some point. The goal is to go through them, observe conditions when they succeed and fail, and then add them to our design tool belt and our intuition.
# Circuit Theory/Simultaneous Equations ### Solving Equations The goal of this section is to illustrate how complicated circuits can get very quickly. This sets up the need for learning circuit simplification techniques described later. The goal here is to use math tools to design circuits. There are several issues that need to be reviewed while solving simultaneous linear equations: - Numeric or Symbolic answers - Algebra - Symbolic Computation - Numeric Solutions (Linear Algebra) After quick reviews, the goal is to start designing/reverse engineering circuits. #### Numerical or Symbolic You are going to need to solve linear simultaneous equations two ways in this course: - result in numerical answers when perfectly constrained - result in variable symbol answers when under constrained You are going to need to recognize the difference between the two. #### Algebra Algebra can be used for simple circuits. Even more complicated circuits can be designed or reversed engineered using algebra, but not in a way that others can check. The solutions become very complicated. Better, more standard, techniques exist. You need to learn when to switch to these more respectable techniques. #### Symbolic Computation In its research context, \"symbolic computation\" has many goals, of which two concern us: **numeric computing** solutions that approximate with floating point numbers, and **symbolic computing** that focuses on exact solutions using symbols and formulas. You are going to need both to succeed. There are lots of packages that try to do both. This text focuses on MathWork\'s MuPAD and MatLab plus Mathematica\'s Wolfram Alpha. MatLab has a huge engineering community growing it\'s toolboxes including the symbolic toolbox MuPAD. Mathematica represents how people think, learn and communicate math. Mathematica is more attractive to scientists. You need to invest time in three types of solutions: - solutions using variable names - symbolic solutions using fractions with whole numbers and constants like $\pi$ - numeric approximations All you have ever done with a calculator are numeric approximations. All you have ever done in algebra is form solutions with variable names. The middle solution is called a \"symbolic solution\" where answers are expressed in whole number ratios instead of decimal places. #### Numeric Solution Symbolic solutions (MathWorks MuPAD or Mathematica) require a lot more typing. They stress computers more and are more likely to fail. But they are a lot better at exploring theories, pointing out concepts, and creating transparency. This transparency enables conversations, corrections, and growth of intuition. Numeric solutions hide details, make consideration of design alternatives harder, and make troubleshooting/harmonizing/checking engineering work more difficult. But they are a lot faster both setting up, executing and in exploring alternatives interatively. This is what MathWorks MatLab focuses on. Numeric solutions require organizing all solutions into matrices before going to the computer. Linear Algebra is a course typically taken after calculus that explains how to do this. But lots of engineering classes require using some of Linear Algebra\'s concepts before you take the course. The same is true here. Read the examples below and you will get the hang of it. ### Solution Summary From the previous two pages, the solution can be outlined as follows: 1. Label currents and voltages 2. Identify loops, add + - to each voltage 3. Identify Junctions, put arrow heads on currents 4. Count knowns and unknowns 5. Write terminal equations 6. Write loop equations 7. Write junction equations 8. Solve equations: 1. Algebra 2. Differential Equations 3. Symbolic Solution 4. Numeric Solution 9. Simulate (circuitlab everycircuit icircuit falstad animations ecstudio) 10. Build Intuition/Check/Compare
# Circuit Theory/Sinusoidal Sources ## Steady State \"Steady State\" means that we are not dealing with turning on or turning off circuits in this section. We are assuming that the circuit was turned on a very long time ago and it is behaving in a pattern. We are computing what the pattern will look like. The \"complex frequency\" section models turning on and off a circuit with an exponential. ## Sinusoidal Forcing Functions Let us consider a general AC forcing function: $$v(t) = M\sin(\omega t + \phi)$$ In this equation, the term M is called the \"Magnitude\", and it acts like a scaling factor that allows the peaks of the sinusoid to be higher or lower than +/- 1. The term ω is what is known as the \"Radial Frequency\". The term φ is an offset parameter known as the \"Phase\". Sinusoidal sources can be current sources, but most often they are voltage sources. ## Other Terms There are a few other terms that are going to be used in many of the following sections, so we will introduce them here: Period : The period of a sinusoidal function is the amount of time, in seconds, that the sinusoid takes to make a complete wave. The period of a sinusoid is always denoted with a capital T. This is not to be confused with a lower-case t, which is used as the independent variable for time. ```{=html} <!-- --> ``` Frequency : Frequency is the reciprocal of the period, and is the number of times, per second, that the sinusoid completes an entire cycle. Frequency is measured in Hertz (Hz). The relationship between frequency and the Period is as follows: $$f = \frac{1}{T}$$ : Where f is the variable most commonly used to express the frequency. ```{=html} <!-- --> ``` Radian Frequency : Radian frequency is the value of the frequency expressed in terms of Radians Per Second, instead of Hertz. Radian Frequency is denoted with the variable $\omega$. The relationship between the Frequency, and the Radian Frequency is as follows: $$\omega = 2 \pi f$$ Phase : The phase is a quantity, expressed in radians, of the time shift of a sinusoid. A sinusoid phase-shifted $\phi = +2 \pi$ is moved forward by 1 whole period, and looks exactly the same. An important fact to remember is this: $$\sin (\frac{\pi}{2}-t) = \cos (t)$$ or $\sin (t) = \cos (t - \frac{\pi}{2})$ Phase is often expressed with many different variables, including $\phi, \psi, \theta, \gamma$ etc\... This wikibook will try to stick with the symbol $\phi$, to prevent confusion. ## Lead and Lag A circuit element may have both a voltage across its terminals and a current flowing through it. If one of the two (current or voltage) is a sinusoid, then the other must also be a sinusoid (remember, voltage is the derivative of the current, and the derivative of a sinusoid is always a sinusoid). However, the sinusoids of the voltage and the current may differ by quantities of magnitude and phase. If the current has a lower phase angle than the voltage the current is said to **lag** the voltage. If the current has a higher phase angle then the voltage, it is said to **lead** the voltage. Many circuits can be classified and examined using lag and lead ideas. ## Sinusoidal Response Reactive components (capacitors and inductors) are going to take energy out of a circuit like a resistor and then pump some of it back into the circuit like a source. The result is initially a mess. But after a while (5 time constants), the circuit starts behaving in a pattern. The capacitors and inductors get in a rhythm that reflects the driving sources. If the source is sinusoidal, the currents and voltages will be sinusoidal. This is called the \"particular\" or \"steady state\" response. In general: $$A_{in} \cos(\omega_{in} t + \phi_{in}) \to A_{out} \cos(\omega_{out} t + \phi_{out})$$ What happens initially, what happens if the capacitor is initially charged, what happens if sources are switched in and out of a circuit is that there is an energy imbalance. A voltage or current source might be charged by the initial energy in a capacitor. The derivative of the voltage across an Inductor might instantaneously switch polarity. Lots of things are happening. We are going to save this for later. Here we deal with the steady state or \"particular\" response first. ## Sinusoidal Conventions For the purposes of this book we will generally use cosine functions, as opposed to sine functions. If we absolutely need to use a sine, we can remember the following trigonometric identity: $$\cos(\omega t) = \sin(\pi/2 -\omega t)$$ We can express all sine functions as cosine functions. This way, we don\'t have to compare apples to oranges per se. This is simply a convention that this wikibook chooses to use to keep things simple. We could easily choose to use all sin( ) functions, but further down the road it is often more convenient to use cosine functions instead by default. ## Sinusoidal Sources There are two primary sinusoidal sources: wall outlets and oscillators. Oscillators are typically crystals that electrically vibrate and are found in devices that communicate or display video such as TV\'s, computers, cell phones, radios. An electrical engineer or tech\'s working area will typically include a \"function generator\" which can produce oscillations at many frequencies and in shapes that are not just sinusoidal. RMS or Root mean square is a measure of amplitude that compares with DC magnitude in terms of power, strength of motor, brightness of light, etc. The trouble is that there are several types of AC amplitude: - peak - peak to peak - average - RMS Wall outlets are called AC or alternating current. Wall outlets are sinusoidal voltage sources that range from 100 RMS volts, 50 Hz to 240 RMS volts 60 Hz worldwide. RMS, rather than peak (which makes more sense mathematically), is used to describe magnitude for several reasons: - historical reasons related to the competition between Edison (DC power) and Tesla (Sinusoidal or AC power) - effort to compare/relate AC (wall outlets) to DC (cars, batteries) .. 100 RMS volts is approximately 100 DC volts. - average sinusoidal is zero - meter movements (physical needles moving on measurement devices) were designed to measure both DC and RMS AC RMS is a type of average: $p_{\mathrm{rms}} = \sqrt {{1 \over {T_2-T_1}} {\int_{T_1}^{T_2} {[p(t)]}^2\, dt}}$ Electrical power delivery is a complicated subject that will not be covered in this course. Here we are trying to define terms, design devices that use the power and understand clearly what comes out of wall outlets.
# Circuit Theory/Maximum Power Transfer ## Maximum Power Transfer Often we would like to transfer the most power from a source to a load placed across the terminals as possible. How can we determine the optimum resistance of the load for this to occur? Let us consider a source modelled by a Thévenin equivalent (a Norton equivalent will lead to the same result, as the two are directly equivalent), with a load resistance, *R~L~*. The source resistance is *R~s~* and the open circuit voltage of the source is *v~s~*: ![](Maximum_Power_Transfer_Circuit.svg "Maximum_Power_Transfer_Circuit.svg") The current in this circuit is found using Ohm\'s Law: $$i=\frac{v_s}{R_s+R_L}$$ The voltage across the load resistor, *v~L~*, is found using the voltage divider rule: $$v_L=v_s \,\frac{R_L}{R_s + R_L}$$ We can now find the power dissipated in the load, *P~L~* as follows: $$P_L=v_Li=\frac{R_L \, v^2_s}{\left(R_s+R_L\right)^2}$$ We can now rewrite this to get rid of the *R~L~* on the top: $$P_L=\frac{v^2_s}{ \left(\frac{{R_s}}{\sqrt{R_L}}+\sqrt{R_L}\right)^2} = \frac{v^2_s}{ R_s \left(\frac{\sqrt{R_s}}{\sqrt{R_L}}+\frac{\sqrt{R_L}}{\sqrt{R_s} }\right)^2}$$ Assuming the source resistance is not changeable, then we obtain maximum power by minimising the bracketed part of the denominator in the above equation. It is an elementary mathematical result that $x+x^{-1}$ is at a minimum when *x=1*. In this case, it is equal to 2. Therefore, the above expression is minimum under the following condition: $$\frac{\sqrt{R_s}}{\sqrt{R_L}}=1$$ This leads to the condition that: : : {\|style=\" border: solid 2px #D6D6FF; padding: 1em;\" valign=\"top\" \|align=\"left\"\|$R_L=R_s \,$ \|} ### Efficiency The efficiency, *η* of the circuit is the proportion of all the energy dissipated in the circuit that is dissipated in the load. We can immediately see that at maximum power transfer to the load, the efficiency is 0.5, as the source resistor has half the voltage across it. We can also see that efficiency will increase as the load resistance increases, even though the power transferred will fall. The efficiency can be calculated using the following equation: $$\eta=\frac{P_L}{P_L+P_s}$$ where *P~s~* is the power in the source resistor. This can be found using a simple modification to the equation for *P~L~*: $$P_s=\frac{v^2_s}{ R_L \left(\frac{\sqrt{R_s}}{\sqrt{R_L}}+\frac{\sqrt{R_L}}{\sqrt{R_s} }\right)^2}$$ The graph below shows the power in the load (as a proportion of the maximum power, *P~max~*) and the efficiency for values of *R~L~* between 0 and 5 times *R~s~*. ![](Maximum_Power_Transfer_Graph.svg "Maximum_Power_Transfer_Graph.svg") It is important to note that under conditions of maximum power transfer as much power is dissipated in the source as in the load. This is not a desirable condition if, for example, the source is the electricity supply system and the load is your electric heater. This would mean that the electricity supply company would be wasting half the power it generates. In this case, the generators, power lines, etc. are designed to give the lowest source resistance possible, giving high efficiency. The maximum power transfer condition is used in (usually high-frequency) communications systems where the source resistance can not be made low, the power levels are relatively low and it is paramount to get as much signal power as possible to the receiving end of the system (the load).
# Circuit Theory/Power Factor Power factor is defined as: $$p_f = \cos(\phi_v - \phi_i)$$ Facts: - The power factor is ideally 1. - Power factors less than 0.9 cause a visit by your utility company. - Building wire codes are designed to maximize the power factor. - Circuits are purely resistive (no capacitors or inductors) when they have a power factor of 1. - Capacitors can cancel out inductors (and vice versa) to create purely resistive circuits. - The Math of this is easiest in the phasor domain. - Exceptions to this are where building up oscillations are the design objective \... such as the cavity in a microwave oven or designing a musical instrument. - The turbulence that the power factor measures can only be seen in the phasor domain. Let\'s consider two circuits: !series RLC circuit !parallel RLC circuit ## Series Circuit The voltage across the inductor and capacitor have to cancel each other out. This means that the power supply doesn\'t see either. This means that the inductor and capacitor are passing energy back and forth, but the resistor and power supply can not see them. This means that $$\mathbb{V}_L + \mathbb{V}_C = 0$$ $$\mathbb{V}_L = - \mathbb{V}_C$$ The current is going to be the same: $$\mathbb{I}$$ From the terminal relations: $$\mathbb{V}_L = jwL\mathbb{I}$$ $$\mathbb{I} = jwC\mathbb{V}_C$$ Solving for $\mathbb{V}_C$: $$\mathbb{V}_C = \frac{\mathbb{I}}{jwC}$$ Substituting into the voltage equation: $$jwL\mathbb{I} = - \frac{\mathbb{I}}{jwC}$$ Now solving for C: $$C = \frac{1}{Lw^2}$$ ## Parallel Circuit The current through the inductor and capacitor have to cancel each other out. This means that the power supply doesn\'t see either. This means that the inductor and capacitor are passing energy back and forth, but the resistor and power supply can not see them. This means that $$\mathbb{I}_L + \mathbb{I}_C = 0$$ $$\mathbb{I}_L = - \mathbb{I}_C$$ The voltage is going to be the same: $$\mathbb{V}$$ From the terminal relations: $$\mathbb{V} = jwL\mathbb{I}_L$$ $$\mathbb{I}_C = jwC\mathbb{V}$$ Solving for $\mathbb{I}_L$: $$\mathbb{I}_L = \frac{\mathbb{V}}{jwL}$$ Substituting into the current equation: $$jwC\mathbb{V} = - \frac{\mathbb{V}}{jwL}$$ Now solving for C: $$C = \frac{1}{Lw^2}$$ So either way the formula for the capacitor to cancel out the inductor is the same. This is strange because in the series circuit the L&C have to combine to be a short to be invisible, and in the parallel circuit they have to combine to be an open. Obviously, there is never going to be a perfect match. If there were a perfect match with ideal devices and a butterfly flapped its wings, the circuit could blow up. But that is another story for later in this course \... ## Dependence on Frequency Eliminating the effects of inductance with capacitance is dependent upon frequency. If the frequency deviates, then another imbalance occurs. In power distribution systems, the 60 Hz or 50 Hz frequency doesn\'t change. But in modems, radios and cable TV boxes, the frequency does change \... when someone speaks, when data moves through a cable, when changing channels. One of the objectives of this course is to understand how to design/plan for these changes.
# Circuit Theory/Complex Frequency ### Complex Frequency Why? Phasor concepts can be extended to cover the turning off and on of circuits using exponentials. For example: $$V_s(t)= (1-e^{-\frac{t}{\tau}})\cdot f(t)$$ turn on $$V_s(t)= ( e^{-\frac{t}{\tau}})\cdot f(t)$$ turn off The value of $\tau$ (or the time constant) determines how quickly the circuit turns on and off. Adding some constants can determine when the circuit turns on and off. Why not Laplace transforms? Laplace transforms can model infinite slopes for turning off and on circuits. We are not going to do that in this course. The real world can be modeled with $\tau$. Laplace transforms are simple, beautiful and truly amazing in that they can handle infinities and infinitesimals. Scientists and mathematicians are always interested in tools that help them work with the road blocks of infinities and infinitesimals. So far this course has been dealing with ideal inductors, resistors, wires, sources, etc. And if we were to deal with ideal turning off and on, we could not use phasors. We would have to use Laplace. So at this point an exception has been made. Or one could just consider \"Complex Frequencies\" as exploring a more complex function in a way similar to phasors. ### Complex Frequency Derivation Before $V(t)=V_m cos(\omega t + \phi)$ modeled steady state circuits (never turned off and on). Now let\'s consider $V(t) = V_m e^{\sigma t} cos(\omega t + \phi)$. Sigma or $\sigma$ is usually negative, otherwise the circuit will explode. Splitting the charging problem into two problems and adding the results in the end is called \"superposition\" which usually works. So we can reduce both situations down to exploring the phasor math of this equation. Substituting $cos(\omega t + \phi) = \operatorname{Re}(e^{j(\omega t + \phi)})$ from Euler\'s equation, we can start a derivation that shows almost nothing changes in the phasor domain! expression notes -------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------ $V(t) = \operatorname{Re}(V_m e^{\sigma t}e^{j(\omega t + \phi}))$ substitution $V(t) = \operatorname{Re}(V_m e^{j\phi} e^{(\sigma+j\omega)t})$ reorganizing the exponents $s=\sigma + j\omega$ defining the complex frequency $s$ $V(t) = \operatorname{Re}(V_m e^{j\phi} e^{st})$ after substitution there is no difference $\mathbb{V}=V_m e^{j\phi}$ Defining the phasor \... nothing different .. $s$ instead of $j\omega$ from derivatives and integrals $V(t) = \operatorname{Re}(\mathbb{V} e^{st})$ Can we assume $\omega$ (angular frequency) and $s$ (complex frequency) can be treated the same? Yes \... almost. ### time domain to complex frequency domain The above process shows that converting v(t) and i(t) to phasors is the exact same process. No need to think about $s$ at all. Terminal Equation Phasor Domain Complex Frequency domain ---------------------- ------------------------------ ----------------------------- $V = RI$ $\mathbb{V} = R\mathbb{I}$ $\mathbb{V} = R\mathbb{I}$ $V = L\frac{d}{dt}I$ $\mathbb{V} = jwL\mathbb{I}$ $\mathbb{V} = sL\mathbb{I}$ $I = C\frac{d}{dt}V$ $\mathbb{I} = jwC\mathbb{V}$ $\mathbb{I} = sC\mathbb{V}$ What is interesting is that the complex frequency operators are the same as the Laplace transform operators. This is why they both use the term \"complex frequency\" to describe s. What makes the Laplace transform operators so complicated is the different way the transform the functions! However, as we will see later (in transfer functions), when turning a circuit into a black box, hooking a driving source up to it and then describing the output, the driving function transform doesn\'t matter. Just the derivative and integral operator transforms matter. ### math in the Complex Frequency Domain Math in the Complex Frequency Domain, with symbols, does not involve keeping track of the $\sqrt{-1}$. The symbol $s$ contains a complex number. The math programs all work internally in rectangular form. Substituting numerically for $s$ with a complex number is simple: $$s = \sigma + j\omega$$. ### complex frequency back to time domain The unknown function(s) is/are going to look something like this: $V(t) = \operatorname{Re}(\mathbb{V} e^{st})$ or $I(t) = \operatorname{Re}(\mathbb{I} e^{st})$. Substituting for s in the time domain means working with exponents a little. Getting back into the time domain will not be as simple as putting the unknown function in polar form. ### Summary Find $s$ during the creation of phasors instead of $\omega$. Substitue $s$ for $j\omega$ when replacing the derivative in the terminal relations. Use $s=\sigma + j\omega$ when moving back into the time domain. The goal in the examples is to explore the similarities and differences of the symbol $s$ as used in Complex Frequency analysis and in the Laplace transform. The Laplace transform also uses the symbol $s$ and also calls it the \"complex frequency.\" But are they the same thing? No. They both use the same complex frequency techniques for transforming the differential and integral operators. But they use different techniques for transforming the functions. Complex frequency transforms functions like phasors and operators like Laplace transforms.
# Circuit Theory/Impedance The impedance concept has to be formally introduced in order to solve node and mesh problems. !the impedance symbol is .. a box ## Symbols & Definition Impedance is a concept within the phasor domain / complex frequency domain. Impedance is not a phasor although it is a complex number. Impedance = Resistance + Reactance: $$Z = R + X$$ : Impedance = $Z$ : Resistance = $R$ : Reactance = $X$ ## Reactance Reactance comes from either inductors or capacitors: $$X_L$$ $$X_C$$ Reactance comes from solving the terminal relations in the phasor domain/complex frequency domain as ratios of V/I: $$\frac{V}{I} = R$$ $$\frac{V}{I} = X_L = j\omega L$$ or $X_L = sL$ $$\frac{V}{I} = X_C = \frac{1}{j\omega C}$$ or $X_C = \frac{1}{sC}$ Because of Euler\'s equation and the assumption of exponential or sinusoidal driving functions, the operator $\frac{d}{dt}$ can be decoupled from the voltage and current and re-attached to the inductance or capacitance. At this point the inductive reactance and the capacitive reactance are conceptually imaginary resistance (not a phasor). Reactance is measured in ohms like resistance. ## Characteristics Impedance has magnitude and angle like a phasor and is measured in ohms. Impedance only exists in the phasor or complex frequency domain. Impedance\'s angle indicates whether the inductor or capacitor is dominating. A positive angle means that inductive reactance is dominating. A negative angle means that capacitive reactance is dominating. An angle of zero means that the impedance is purely resistive. Impedance has no meaning in the time domain.
# Circuit Theory/Series Resistance ## Series Resistance Two or more resistor can be connected in series to increase the total resistance . The Total Resistance is equal to the sum of all the resistor\'s resistance . The total resistance In Series connected circuit Current and voltage will be reduced : ![](Resistors_in_Series.svg "fig:Resistors_in_Series.svg"){width="200"} : $R_{tot}=R_1+R_2+R_3+...+R_n \,$ ## Series Impedance !used to show how impedance add\'s in series A branch is defined as any group of resistors, capacitors and inductors that can be circled with only two wires crossing the circle boundary. A branch connects two, non-trivial nodes or junctions. Within a branch the components are said to be \"in series.\" Consider a branch containing a Resistor, Capacitor and Inductor. Say the driving function or source is $$V_s = 10*cos(22400t+30^\circ)$$ $$V_s = 10*e^{-5000t}cos(22400t+30^\circ)$$ There is just one current, $I$. ## Symbolic Derivation !the impedance symbol is .. a box The terminal equations are: $$\mathbb{V}_r = \mathbb{I}*R$$ $$\mathbb{V}_L = \mathbb{I}*j\omega L$$ or $\mathbb{V}_L = \mathbb{I}*sL$ $$\mathbb{I} = \mathbb{V}_c *j\omega C$$ or $\mathbb{I} = \mathbb{V}_c *sC$ There are no junction equations and the loop equation is: $$\mathbb{V}_r + \mathbb{V}_L + \mathbb{V}_c - \mathbb{V}_s = 0$$ Solving the terminal equations for voltage, substituting and then dividing by $\mathbb{I}$ yields: $$\frac{\mathbb{V}_s}{\mathbb{I}} = R + j\omega L + \frac{1}{j\omega C}$$ $$\frac{\mathbb{V}_s}{\mathbb{I}} = R + sL + \frac{1}{sC}$$ In terms of impedance, if: $$Z = R + j\omega L + \frac{1}{j\omega C}$$ $$Z = R + sL + \frac{1}{sC}$$ Then: $$\frac{\mathbb{V}_s}{\mathbb{I}} = Z$$ In general, impedances add in series like resistors do in the time domain: $$Z = \sum R_i + \sum j\omega L_i + \sum\frac{1}{j\omega C_i}$$ $$Z = \sum R_i + \sum sL_i + \sum\frac{1}{sC_i}$$ !matlab screen shot of numeric calculation .. /m-file/ ## Numeric Example In rectangular form: $$Z = 100 + .15714j$$ $$Z = 80.508 + 2.2759j$$ In polar form (remember impedance is not a phasor, it is a concept in the phasor or complex frequency domain): $$Z = 100.0001\angle 0.0016 (0.09^\circ)$$ $$Z = 80.5402\angle 0.0283 (1.6193^\circ)$$ ## Notes - Calculations like this are only necessary when trying to find out what is going on in one little part of the circuit \... and Kirchhoff would take too long. This was true in the past, but given the modern capabilities of matLab and mupad, the importance of the series concept may diminish. ```{=html} <!-- --> ``` - It appears that the exponential term decreases the overall magnitude and increases the reactance \... increases in the inductive direction with the exponential term. ```{=html} <!-- --> ``` - The V/I ratio sets up/prepares for the transfer function discussion later.
# Circuit Theory/Parallel Resistance ## Parallel Resistance Resistors in parallel share the same voltage. They split the current up. Giving the current multiple paths to follow means that the overall resistance decreases. !A diagram of several resistors, side by side, both leads of each connected to the same wires. $$R_\mathrm{total} =\frac{1}{ \frac{1}{R_1} + \frac{1}{R_2} + \cdots + \frac{1}{R_n}} = \frac{1}{\sum\frac{1}{R_i}}$$ The above equation is often called the \"one over \-- one over\" equation. ## Parallel Impedance !used to show how impedance add\'s in parallel A group of parallel branches split up the current, but share the same voltage. The parallel branches connect the same two nodes. The impedance of parallel branches can be combined into one impedance. Consider these parallel branches: one with a resistor, another with a capacitor and a third with an inductor. Now drive them with a voltage source: $$V_s = 10*cos(22400t+30^\circ)$$ $$V_s = 10*e^{-5000t}cos(22400t+30^\circ)$$ There is just one current, $V$. ## symbolic derivation !the impedance symbol is .. a box !Parallel Impedance calculation with matlab ..m-file The terminal equations are: $$\mathbb{V}_s = \mathbb{I}_r*R$$ $$\mathbb{V}_s = \mathbb{I}_L*j\omega L$$ or $\mathbb{V}_s = \mathbb{I}_L*sL$ $$\mathbb{I}_c = \mathbb{V}_s *j\omega C$$ or $\mathbb{I}_c = \mathbb{V}_s *sC$ There are no loop equations and the junction equation is: $$\mathbb{I}_r + \mathbb{I}_L + \mathbb{I}_c - \mathbb{I}_s = 0$$ Solving the terminal equation for currents, substituting and dividing both sides by $\mathbb{V}_s$ yields: $$\frac{\mathbb{I}_s}{\mathbb{V}_s} = \frac{1}{R} + \frac{1}{j\omega L} + j\omega C$$ $$\frac{\mathbb{I}_s}{\mathbb{V}_s} = \frac{1}{R} + \frac{1}{sL} + sC$$ In terms of impedance, if: $$\frac{1}{Z} = \frac{1}{R} + \frac{1}{j\omega L} + j\omega C$$ $$\frac{1}{Z} = \frac{1}{R} + \frac{1}{sL} + sC$$ Then: $$\frac{\mathbb{I}_s}{\mathbb{V}_s} = \frac{1}{Z}$$ In general, impedances add in series like resistors do in the time domain: $$\frac{1}{Z} = \sum\frac{1}{R_i} + \sum\frac{1}{j\omega L_i} + \sum j\omega C_i$$ $$\frac{1}{Z} = \sum\frac{1}{R_i} + \sum\frac{1}{sL_i} + \sum sC_i$$ or $$Z = \frac{1}{\sum\frac{1}{R_i} + \sum\frac{1}{j\omega L_i} + \sum j\omega C_i}$$ $$Z = \frac{1}{\sum\frac{1}{R_i} + \sum\frac{1}{sL_i} + \sum sC_i}$$ ## numeric example $$Z = 99.9938 - 0.7857i = 99.9969\angle -0.0079 (-0.4502^\circ)$$ $$Z = 186.85 -837.07i = 857.6701\angle -1.3512 (-77.4170^\circ)$$ So the exact same components hooked in series are dominated by the inductor (large reactance of the inductor overshadows the smaller reactance of the capacitor), but when the same components are hooked in parallel, the small er capacitive reactance dominates. ## notes What is the point of all this? The goal is to start with simple circuits, explore them with words and symbols, find the patterns and generalize, establish and name concepts and then wait for their application. What are we waiting for? Selecting channels on a TV/Radio/Wifi, ZigBee, RFID, Cellphones, Blue Tooth and sending data over these channels as well as to hard drives and SD cards, monitors and hubs, designing antennas, \....
# Circuit Theory/Node Analysis Node analysis is done in the phasor domain. The Node Analysis method reduces the number of equations and unknowns one is finding in a circuit. Kirchhoff\'s method finds all currents and voltages. Node Analysis only finds the voltages at nodes (junctions). Node analysis starts with Kirchhoff junction equations: $$\sum_{k=1}^n {I}_k = 0$$ and solves terminal equations so that current is a function of voltage, and then substitutes into the junction current equation: $$i = \frac{\Delta V}{R}$$ $$i = C * j\omega \Delta V = sC \Delta V$$ $$i = \frac{\Delta V}{j\omega L} = \frac{\Delta V}{sL}$$ What is $\Delta V$? It is the voltage with respect to ground of the node on either side of the device being considered. $$\Delta V = V_{nodeA} - V_{nodeB}$$ Where current is following from node_A to node_B. At first glance this may seem trivial, but there are subtle differences exposed when doing the problems: - Node voltages are relative to ground. They are not Kirchhoff\'s drops across individual devices. - Assume all currents leave nodes. - Terminal relation equations are more complicated. - Has to be done in the phasor domain so impedances between nodes can be computed. - Can have too few equations requiring finding \"super node\" equations. - Some problems can not be solved. Recognizing these is not trivial. ## Examples ### Basic case !Basic example circuit with one unknown voltage, V~1~.{width="280"} The only unknown voltage in this circuit is V~1~. There are three connections to this node and consequently three currents to consider. The direction of the currents in calculations is chosen to be away from the node. 1. Current through resistor R~1~: (V~1~ - V~S~) / R~1~ 2. Current through resistor R~2~: V~1~ / R~2~ 3. Current through current source I~S~: -I~S~ \ With Kirchhoff\'s current law, we get: $\frac{V_1 - V_S}{R_1} + \frac{V_1}{R_2} - I_S = 0$\ This equation can be solved in respect to V~1~: $V_1 = \frac{\left( \frac{V_S}{R1} + I_S \right)}{\left( \frac{1}{R_1} + \frac{1}{R_2} \right)}$\ Finally, the unknown voltage can be solved by substituting numerical values for the symbols. Any unknown currents are easy to calculate after all the voltages in the circuit are known. $V_1 = \frac{\left( \frac{5\text{ V}}{100\,\Omega} + 20\text{ mA} \right)}{\left( \frac{1}{100\,\Omega} + \frac{1}{200\,\Omega} \right)} \approx 4.667\text{ V}$ The fact that $V_1 < V_s$ and implies that current flows in the opposite direction through R~1~ reflects the fact that assuming that current flows out of a node just helps us write equations that capture the circuit topology in order to write logically consistent equations. They are in no way a guess at the final current direction. ### Another Example Given the Circuit below, find the voltages at all nodes. center\|framed\|example circuit for nodal analysis example. - node 0: $V_0 = 0V\,$ (defined as ground node)\ - node 1: $V_1 = 9V\,$ (free node voltage)\ - node 2: $\frac{V_1 - V_2}{1k} = \frac{V_2 - V_0}{3k} + \frac{V_2 - V_3}{2k}$\ \ - node 3: $\frac{V_2 - V_3}{2k} = \frac{V_3 - V_0}{2k}$\ which results in the following system of linear equations: $$\left\{\begin{matrix} +11 V_2 & -3 V_3 & = & 54 \\ +1 V_2 & -2 V_3 & = & 0\end{matrix}\right.$$ Therefore, the solution is: $$\left\{\begin{matrix} V_0 =0.00V \\ V_1 =9.00V \\ V_2 =5.68V \\ V_3 =2.84V\end{matrix}\right.$$\ ### Supernodes !In this circuit, V~A~ is between two unknown voltages, and is therefore a supernode.{width="182"} In this circuit, we initially have two unknown voltages, V~1~ and V~2~. The voltage at V~3~ is already known to be V~B~ because the other terminal of the voltage source is at ground potential. The current going through voltage source V~A~ cannot be directly calculated. Therefore we can not write the current equations for either V~1~ or V~2~. However, we know that the same current leaving node V~2~ must enter node V~1~. Even though the nodes can not be individually solved, we know that the combined current of these two nodes is zero. This combining of the two nodes is called the supernode technique, and it requires one additional equation: V~1~ = V~2~ + V~A~. The complete set of equations for this circuit is: $\begin{cases} \frac{V_1 - V_\text{B}}{R_1} + \frac{V_2 - V_\text{B}}{R_2} + \frac{V_2}{R_3} = 0\\ V_1 = V_2 + V_\text{A}\\ \end{cases}$ By substituting V~1~ to the first equation and solving in respect to V2, we get: $V_2 = \frac{(R_1 + R_2) R_3 V_\text{B} - R_2 R_3 V_\text{A}}{(R_1 + R_2) R_3 + R_1 R_2}$
# Circuit Theory/Mesh Analysis !Non-trivial meshes of the planar circuit labeled 1, 2, and 3.{width="300"} Mesh analysis is done in the phasor domain. The mesh analysis method reduces the number of equations and unknowns one is finding in a circuit. Kirchhoff\'s method finds all currents and voltages. Mesh analysis only finds mesh (loop) currents. Mesh analysis starts with the normal Kirchhoff loop equations: $$\Delta_{k=1}^n {V}_k = 0$$ and solves terminal equations so that voltage is a function of current, and then substitutes into the loop voltage equation: $$v = \Delta I * R$$ $$v = \frac{\Delta I}{C * j\omega} = \frac{\Delta I}{sC}$$ $$v = \Delta I * j\omega L = \Delta I * sL$$ What is $\Delta I$? It is the difference (or addition) of possibly two mesh currents following through a device. It can be just one current if the device is not part of two meshes. Devices that are part of two meshes need the mesh currents added or subtracted (depending on direction). $$\Delta I = I_{meshA} - I_{meshB}$$ At first glance mesh analysis may seem trivial, but there are subtle differences to Kirchhoff\'s exposed when doing the problems: Mesh currents can be in the same direction or different directions through the same device. They are not Kirchhoff\'s currents through individual devices. Without careful labeling of the mesh current directions on the planar circuit diagram, it is impossible to keep directions straight. - Mesh currents are positive if they are in the same direction of the particular Kirchhoff loop equation being written, negative if they would cause a negative voltage. - Mesh currents are typically CW and dictate the loop equation direction. - Has to be done in the phasor domain so impedances between nodes can be computed. - Can have too few equations requiring finding additional equations from \"Super Meshes\". - Some problems can not be solved. Recognizing these is not trivial. ## Mesh currents !Figure 2: Circuit with mesh currents labeled as i~1~, i~2~, and i~3~. The arrows show the direction of the mesh current.{width="300"} Mesh analysis works by arbitrarily assigning mesh currents in the non-trivial loops/meshes. Figure 1 labels the essential meshes with one, two, and three. A mesh current may not correspond to any physically flowing current, but the physical currents are easily found from them. It is usual practice to have all the mesh currents loop in the same direction. ## Example center\|framed\|Circuit diagram for use with the Mesh Current example problem. The circuit has 2 loops indicated on the diagram. Using KVL we get: - **Loop1:** $0=9-1000I_1-3000(I_1-I_2)$ - **Loop2:** $0=3000(I_1-I_2)-2000I_2-2000I_2$ Simplifying we get the simultaneous equations: $$0=9-4000I_1+3000I_2$$ $$0=0+3000I_1-7000I_2$$ Solving to get: $$I_1=3.32mA$$ $$I_2=1.42mA$$ ## Setting up the equations Each mesh produces one equation. These equations are the sum of the voltage drops in a complete loop of the mesh current.For problems more general than those including current and voltage sources, the voltage drops will be the impedance of the electronic component multiplied by the mesh current in that loop. If a voltage source is present within the mesh loop, the voltage at the source is either added or subtracted depending on if it is a voltage drop or a voltage rise in the direction of the mesh current. For a current source that is not contained between two meshes, the mesh current will take the positive or negative value of the current source depending on if the mesh current is in the same or opposite direction of the current source.The following is the same circuit from above with the equations needed to solve for all the currents in the circuit. $\begin{cases} \text{Mesh 1: } I_1 = I_s\\ \text{Mesh 2: } -V_s + R_1(I_2-I_1) + \frac{1}{sc}(I_2-I_3)=0\\ \text{Mesh 3: } \frac{1}{sc}(I_3-I_2) + R_2(I_3-I_1) + LsI_3=0\\ \end{cases} \,$\ ### Supermesh !Figure 3: Circuit with a supermesh. Supermesh occurs because the current source is in between the essential meshes.{width="300"} A supermesh occurs when a current source is contained between two essential meshes. The circuit is first treated as if the current source is not there. This leads to one equation that incorporates two mesh currents. Once this equation is formed, an equation is needed that relates the two mesh currents with the current source. This will be an equation where the current source is equal to one of the mesh currents minus the other. The following is a simple example of dealing with a supermesh. $\begin{cases} \text{Mesh 1, 2: } -V_s + R_1I_1 + R_2I_2 = 0\\ \text{Current source: } I_s = I_2 - I_1 \end{cases} \,$
# Circuit Theory/Dangling Resistors !100 ohm dangling resistor is only connected to the circuit by one wire !dangling resistor removed When opening capacitors, inductors or current sources during circuit analysis, sometimes a resistor is left connected to the circuit with only one wire. It can be removed from the circuit. It can be removed because there is no current through it. This means that the electromotive force is the same through the resistor. The green and the red dot are part of the same node. The original voltage between green and black is going to be the same voltage between red and black. The total Resistance will be r1+r2.
# Circuit Theory/Shorted Resistors !Circuit With a Short of Resistor 3 !The effective circuit: Resistor 3 removed because not impacting the circuit A wire in the left circuit is shorting the 100Ω resistor. All current will bypass the resistor and travel through the short. The voltage across the 100Ω resistor is going to be zero. The 100Ω resistor is not impacting the circuit. For analysis purposes, the 100Ω resistor can be removed. The real world wire is going to have some resistance, and a tiny trickle of current will go through the resistor. The exact magnitude is going to depend upon the amount of resistance in the wire. The ideal math would involve infinity. So typically the assumption of a short is done by redrawing the circuit. This is why redrawing circuits when making assumptions (such as removing a resistor because of the short) is important.
# Circuit Theory/Open Puzzles Sloppy people build circuits with shorts where wires accidentally touch. These people are easy to spot. The circuit looks like a bird\'s nest. Opens are harder. Intermittent opens are caused by bad wires, bad connections, bad soldering, warm up/cool down expansion contraction, dust, and physical movement of the circuit. Finding them is difficult. One technique is to push every where in the circuit with a wooden stick to try and re-create an open. Identifying opens is the best thing to practice at the moment. !Circuit with Open This circuit has an open between the red and black dots. No current is flowing. The electro motive force (EMF) extends from the battery + terminal through resistors 4 and 5. The EMF from the negative terminal of the battery extends through resistor 6. Thus the voltage drop between the red and black dots is the battery voltage of 1 volt. !Circuit where open causes dangling resistor, or where opening a short puts the resistor back in the circuit Opening a wire can cause dangling resistors. A wire removed between red and green removes resistor 2 from the circuit. Opening a short can put a resistor back into the circuit. A wire between between green and ground would short resistor 4. Opening this wire puts resistor 4 back into the circuit. If a wire connected black, green and red, then resistor 4 would be shorted out of the circuit. Resistors 2 and 3 would combine in parallel, and the combination would combine in series with resistor 1. !Two opens complicating things Two wires have been removed from this circuit. This has left resistors 2,3,7,5 and 8 dangling. It has made the EMF of red and green, the same as the EMF between resistors 1 and 6. It has made the EMF of the black and blue the same as the EMF between resistors 6 and 4. The voltage drop from red to black will be the same voltage drop from green to blue. !Which resistors are left dangling because of these two opens? Resistors 3,4,5 and 6 are no longer are participating in this circuit. !What are the voltages between the colored points? The EMF of the green, red, yellow, blue points in the circuit is all the same \... that of the positive terminal of the battery. The EMF of the black is that of the negative terminal of the battery. The voltage between any pair of green, red, yellow and blue is zero. The voltage between black and any of the other colors is going to be 1 volt.
# Circuit Theory/One Port Devices There are many circuits that can solve any particular task. Kirchhoff or any other analysis technique can not describe the bare minimum, most simple, alternative to an existing circuit that works. The goal is to figure out a circuit\'s characteristics \... like an eigenvalue \... the minimal parameters that totally define it. The minimal characteristics or parameters serve two purposes: - Enable design of alternative, cheaper, simpler circuits that do the same thing - Help designers using the existing circuit predict its impact on other circuits attached to it. ## One-Port ![](One_Port_Circuit.svg "One_Port_Circuit.svg") Impedance, resistance and reactance are often drawn as a rectangle instead of their normal circuit symbols. This is the beginning of dealing with the real world rather than the ideal. A \"port\" hides what is inside of it like a \"black box\". A resistor, capacitor, inductor and power source are one-port (two-wire) devices. But in the real world a resistor could also have some inductance, or capacitance, or act as an antenna channeling wireless energy into the circuit. More generally, a one-port circuit can have any number of passive elements, independent and dependent sources and nodes. A port can be described as a circuit that has been designed, analyzed and tested. At this point, a circuit\'s internal details, its design, and its theory of operation are no longer important. It becomes a building block. Complex circuits may consist of a few ports where each port itself may be complex. When ports are named, miniaturized and mass-produced, they become a new circuit device. One-port devices are usually found at the beginning and the end of a circuit. The middle of a circuit is built with two-port devices, which are covered later. A port has characteristics besides its impedance and whether it contains a source or not. A port has parameters. The ideal parameters we have been studying are sometimes called lumped element parameters. These parameters may change depending on how the port is \"driven\". Ports can have different \"driving points\". ## Example Suppose we are going to connect a DC Voltage power supply to points a and b. The goal is to characterize the insides of the box that contains a DC voltage source and a couple of resistors. Do this by: - Plot V~ab~ as depending upon the current (instead of the actual situation where current is dependent upon the added voltage supply) so that the slope is resistance. From the plot find the slope (resistance). What does the vertical, V~ab~ axis intercept represent? What does the horizontal (current) axis intercept represent? - Calculate the V~ab~ if nothing is attached to the one port device. - Zero the voltage source and calculate the resistance between a and b. - Create another one port device that behaves the same with just one source and resistor. Simulate it and show that it produces the same V~ab~ curve or line. <File:Example26aa.png%7CCircuit> that problem statement is referring to <File:Example26c.png%7CSince> current is on the independent (x) axis and voltage is dependent, need a current source. <File:Example26e.png%7CSimulation> that can be found at circuitlab.com ### Plot V~ab~ : Circuit was simulated at circuitlab resulting in the plot above that matches the formula below. : Slope of the line is 66.66667 ohms and the intercept is -1 volt. : The equation of the line can be formed by node analysis at a: $$I - \frac{V_{ab}}{100} - \frac{V_{ab}+3}{200} = 0$$ : Solving for V~ab~ $$V_{ab} = \frac{200*I}{3} - 1$$ : Can see in the simulation that the intercept when i = 0 is -1 and slope is 200/3. ### Calculate V~ab~ with nothing attached Nothing attached means the current is zero, so from the equation V~ab~=-1 \... which is the V~ab~ vertical axis intercept. !Circuit with voltage source shorted so can compute resistance between points a and b. ### Zero voltage source, calculate resistance between a and b After shorting the voltage source, have 200 and 100 ohm resistors in parallel so: $$R_{ab} = \frac{1}{\frac{1}{200} + \frac{1}{100}} = \frac{200}{3}$$ which is the slope of the equation. ### Create simpler one port device <File:Example26d.png%7Csimple> circuit the performs exactly the same way as the more complicated one <File:Example26e.png%7Csimulation> at circuitlab.com is same as the 2 resistor circuit with -3 volt source
# Circuit Theory/Source Injection Source injection is a trick used when parallel/series combinations don\'t exist in a circuit. Source injection helps find the overall impedance of a circuit from V~s~/I~s~. Vs and Is are found in the phasor/complex frequency domain using node or mesh analysis. <File:Example24a.png%7Coriginal> complicated circuit, want to look at just the red part <File:Example24b.png%7Cwant> to reduce middle resistors into one equivalent resistor <File:Example24c.png%7Cremove> middle part from circuit, inject source of 1 volt, find source current and compute the equivalent resistance !mupad screen shot of code node analysis of the source injected circuit Suppose have a complicated circuit, want to break it up into smaller sections, find a clump of passive devices in the middle of it, want to find their equivalent, but can not combine in series or parallel. This type of problem has to be done with source injection (or Y Δ Transform .. but that is later). One is really not physically injecting anything into the circuit, one is just pretending so that node analysis can be used to find the overall real (in phasor/complex frequency domain) impedance. For the circuit above, the node analysis shows that the overall current is: $$I_s = 0.2542735043$$ This means that: $$R_{eq} = \frac{V_s}{I_s} = \frac{1}{0.2542735043} = 3.9328 ohms$$
# Circuit Theory/Lab4.5.1 !the original circuit, R7 is the load, find thevenin equivalent of the rest of the circuit !Finding Vth using ohm\'s law !thevenin resistance is calculated by zeroing the sources and opening the load !redrawing thevenin resistance network to make calculation easier Example, find the thevenin equivalent of this circuit, treating R7 as the load. - Simulate the circuit, displaying load voltage and current as the load is swept through a range of resistance values - Simulate the thevenin equivalent circuit and again sweep the load voltage and current through a range of resistance values ## Finding Thevenin Voltage Open the load (resistor R7), and find the voltage across it\'s terminals. R~5~ and R~6~ are dangling and can be removed. V~th~ = V~A~ - V~B~ V~A~ = 2-V~R1~ = 2 - (2-5)\*2.2/(2.2+4.7) .. voltage divider V~A~ = 2.9565 V~B~ = 5-V~R3~ = 5 - 5\*6.8/(6.8+6.8) .. voltage divider V~B~ = 2.5 volts V~th~ = 2.9565 - 2.5 = 0.4565 volts Can check with this simulation. ## Finding Thevenin Resistance Remove the load, zero the sources. Redraw up and down so the parallel/serial relationships between the resistors are obvious. - $R_{th} = 1 + \frac{1}{\frac{1}{2.2} + \frac{1}{4.7}} + \frac{1}{\frac{1}{6.8} + \frac{1}{6.8}} + 1.5$ - $R_{th} = 7.3986$ ## Finding Norton Current I~N~ = V~th~/R~th~ = 0.4565/7.3986 = 0.0617 amp ## Simulating the original circuit In the simulation, can see the computed Norton\'s current when the load is 0 ohms. Can see the computed Thevenin voltage when the load is around 20 ohms which approximates an open. ## Comparing with the Thevenin Equivalent In this simulation, can see the same values, except this time the load voltage is relative to ground, so don\'t have to look at a drop or differences between two voltages as with the original circuit simulation. <File:Example25e.png%7CSweep> simulation of original circuit for R7 values of 47 ranging from 0 to 20 <File:Example25f.png%7CThe> thevenin equivalent with the R7 load in place <File:Example25g.png%7CSweep> simulation of the thevenin equivalent circuit for R7 values ranging from 0 to 20 ohms
# Circuit Theory/Thevenin-Norton ## Vth using Node !opening load, finding V~th~ using Node .. code $$V_{th} = 6.4516$$ ## In using Node !shorting load, finding I~n~ using Node .. code $$I_N = 1.064773736$$ ## Rth or Rn $$V_{th}/I_N= \frac{6.4516}{1.064773736} = 6.0591 ohms$$ ## Finding Rth using source injection and node <File:Example23d.png%7Czero> sources to find Rth <File:Example23e.png%7Cadd> source injection since parallel/series combinations do not exist <File:Example23g.png%7Credraw> up and down before solving Here is the mupad/matlab code that generates the answer R~th~ = 6.0591 ohms. ## Comparing Node with Thevenin Equivalent !solving using Node .. code !solving using Thevenin equivalent Solving the node equations yields: $$V_a = 5.393$$ $$V_b = 1.1673$$ $$V_c = 1.107$$ $$i_{12} = 0.3571$$ $$v_{12} = 4.286$$ Using the Thevenin equivalent (and voltage divider) to compute voltage across the 12 ohm resistor: $$v_{12} = V_s*\frac{12}{R{total}}$$ $$v_{12} = 6.4516*\frac{12}{6.0591+12} = 4.287$$ So they match \... Thevenin voltage and resistance can not be computed from a node analysis of the entire circuit, but the node analysis of the entire circuit can be used to check if the thevenin equivalent produces the same numbers.
# Circuit Theory/Example70 !original circuit $$V_{s1} = \frac{\sqrt{2}}{6}\cos (t+\frac{\pi}{4})$$ $$V_{s2} = \cos (t+\frac{\pi}{3})$$ $$\mathbb{V}_{s1} = \frac{1}{6}(1 + j)$$ $$\mathbb{V}_{s2} = \frac{1}{2}(1 + j\sqrt{3})$$ The series components can be lumped together .. which simplifies the circuit a bit. ## Node Analysis !Node analysis !mupad and matlab /code/ for all the work below $$\frac{\mathbb{V}_{s1} - \mathbb{V}_a}{5} - \mathbb{V}_a - \frac{\mathbb{V}_a + \mathbb{V}_{s2}}{j\sqrt{3}} = 0$$ $$\mathbb{V}_a = -0.42063 + j0.065966$$ ## Mesh Analysis !Mesh analysis $$i_1 - i_2 - V_{s1} + 5 * i_1 = 0$$ $$i_2 j\sqrt{3} - V_{s2} + i_2 - i_1 = 0$$ $$i_3 = i_1 - i_2$$ Solving $$i_3 = -0.42063 + j.065966$$ Which is the same as the voltage through the 1 ohm resistor. ## Thevenin voltage !Thevenin voltage requires opening the load Make ground the negative side of $V_{s2}$, then: $$V_{th} = V_A - V_B$$ $$V_{th} = i*j\sqrt{3} - V_{s2}$$ $$V_{th} = \frac{V_{s1} + V_{s2}}{5 + j\sqrt{3}}*j\sqrt{3} - V_{s2}$$ Solving $$V_{th} = -0.747977 - j0.5492$$ ## Norton Current <File:Example70norton1.png%7Cshort> out the load <File:Example70norton2.png%7Csplit> into two circuits so can use superposition <File:Example70norton3.png%7Chalf> the circuit is shorted out by shorting the voltage sources $$i_n = i_1 - i_2 = \frac{V_{s1}}{5} - \frac{V_{s2}}{j\sqrt{3}}$$ $$i_n = -0.4667 + j0.3220$$ ## Thevenin/Norton Impedance ![](Example70impedance.png "Example70impedance.png") short voltage sources, open current sources, remove load and find impedance where the load was attached $$Z_{th} = \frac{1}{\frac{1}{5} + \frac{1}{j\sqrt{3}}} = 0.537 + j1.5465$$ check $$Z_{th} = \frac{V_{th}}{I_n} = 0.537 + j1.5465$$ yes! they match ## Evaluate Thevenin Equivalent Circuit ![](Example70theveninEquivalent.png "Example70theveninEquivalent.png") Going to find current through the resistor and compare with mesh current $$i = \frac{V_{th}}{Z_{th} + 1} = -0.42063 + j0.06599$$ yes! they match ## Find Load value for maximum power transfer $$Z_{L} = z_{th}^* = 0.537 - j1.5465$$ ## Find average power transfer with Load that maximizes $$Z_{th} + Z_{L} = 0.537*2$$ $$P_{avg} = \frac{Re(V_{th})^2}{Z_{th} + Z_{L}} = \frac{\sqrt{0.747977^2 + 0.5492^2}}{2*0.537} = 0.8037 watts$$ ## Simulation ![](Example70simulation2.png){width="800"} The circuit was simulated. A way was found to enter equations into the voltage supply parameters which improves accuracy: <File:Example70-vs11.png%7Ctype> sqrt(3) instead of a numeric approximation <File:Example70-vs2.png%7Cadded> pi/2 to convert from cos to sin sources To compare with the results above, need to translate the current and voltage through the resistor into the time domain. ### Period Period looks right about 6 seconds \... should be: $$T = \frac{1}{f} = \frac{2*\pi}{w} = 2*\pi = 6.2832$$ ### Current Current through 1 ohm resistor, once moved into the time domain (from the above numbers) is: $$i(t) = 0.4258*cos(t + 171^{\circ})$$ From the mesh analysis, the current\'s through both sources were computed: $$i_{s1} = 0.1192*cos(t + 9.72^{\circ})$$ The magnitudes are accurate, they are almost π out of phase which is can be seen on the simulation. ### Voltage The voltage is the same as the current through a 1 ohm resistor: $$v(t) = 0.4258*cos(t + 171^{\circ})$$ The voltage of the first (left) source is: $$V_{s1} = \frac{\sqrt{2}}{6} cos(t + \frac{pi}{4}) = 0.2357 * cos(t + 45^{\circ})$$ The magnitudes match. The voltage through the source peaks before the current because the first source sees the inductor. The voltage through the resistor should peak about 171 - 45 = 126° before the source \... which it appears to do.
# Circuit Theory/Superposition ## Goal Split multisource circuit into smaller, simpler circuits, compute current or voltage and add. ## Procedure Pick one source, turn off all or set to zero all others: - Set Voltage Sources to V=0, doesn\'t care about current so is a short - Set Current Sources to I=0, doesn\'t care about the voltage so turns into an open ## Example 1 Find the current through the 3 ohm resistor assuming moving left to right is positive: <File:Example16a.png%7CThe> original circuit is equal to <File:Example16b.png%7Cthis> circuit where i = 24/5 plus <File:Example16c.png%7Cthis> circuit where i = -14/5 (current divider) plus <File:Example16d.png%7Cthis> circuit where i = -3/5. The total current in the direction shown on the original diagram is going to be: $\frac{24}{5} - \frac{14}{5} - \frac{3}{5} = \frac{7}{5} amp$ ## Example 2 Find the current through the 4 ohm resistor assuming moving left to right is positive: <File:Example17a.png%7CThe> original circuit is equal to <File:Example17b.png%7Cthis> circuit which can be re-drawn as <File:Example17bs.png%7Cthis> circuit where i = 35/3 = 11.67 plus <File:Example17c.png%7Cthis> circuit which can be re-drawn as <File:Example17cs.png%7Cthis> circuit where i = -11/36 = -.3056 plus <File:Example17d.png%7Cthis> circuit which can be re-drawn as <File:Example17ds.png%7Cthis> circuit where i = 25/18 = 1.3889 (current divider) $i = 35/3 - 11/36 + 25/18 = 51/4 = 12.75 amps$ Simulation at circuit lab confirms the answer: !DC Simulation at Circuit Lab
# Circuit Theory/Extra Element The Extra Element technique helps break down one complicated problem into several simpler ones like superposition. However the goal is to find impedance rather than current or voltage. By removing the element that most complicates the circuit the overall circuit impedance can be obtained. $$Z_{in} = Z^{\infty}_{in} \left( \frac{1+\frac{Z^0_{e}}{Z}}{1+\frac{Z^{\infty}_{e}}{Z}} \right)$$ where $$Z\$$ is the impedance chosen as the extra element to be removed $$Z^{\infty}_{in}$$ is the input impedance with Z removed (or made infinite) $$Z^0_{e}$$ is the impedance seen by the extra element Z with the source shorted (or made zero) $$Z^{\infty}_{e}$$ is the impedance seen by the extra element Z with the source opened (or made infinite) Computing these three terms may seem like extra effort, but they are often easier to compute than the overall input impedance. ### Example !4 resistors, 1 capacitor example !set up for node analsysis !node analysis in mupad ../code/ .. need to solve for vs/current to compare answers Consider the problem of finding $Z_{in}$ for the circuit in Figure 1 using the EET (note all component values are unity for simplicity). If the capacitor (gray shading) is denoted the extra element then $$Z = \frac{1}{s}$$ Removing this capacitor from the circuit we find <File:Example18b.png%7Ccapacitor> removed, looking at the input (source input) <File:Example18c.png%7Ccapacitor> removed, reorganizing circuit so can see input impedance $Z^{\infty}_{in}$ $$Z^{\infty}_{in} = 2\|1 +1 = \frac{5}{3}$$ Calculating the impedance seen by the capacitor with the input shorted we find <File:Example18d.png%7Cshorted> source, finding $Z^0_{e}$ <File:Example18h.png%7Cshorted> source redrawn $$Z^0_{e} = 1\|(1+1\|1) = \frac{3}{5}$$ Calculating the impedance seen by the capacitor with the input open we find <File:Example18d.png%7Copen> source, finding $Z^{\infty}_{e}$ <File:Example18h.png%7Copen> source redrawn $$Z^{\infty}_{e} = 2\|1+1 = \frac{5}{3}$$ Therefore using the EET, we find $$Z_{in} = \frac{5}{3} \left(\frac{1+\frac{3}{5}s}{1+\frac{5}{3}s}\right)$$ Note that this problem was solved by calculating three simple driving point impedances by inspection.
# Circuit Theory/Symmetry Some very complicated circuits can be solved by seeing symmetry. Three examples are presented below: ## Example 1 Bridge Balance <File:Example19a.png%7COriginal> Complicated Circuit <File:Example19b.png%7CRedrawn> up and down <File:Example19c.png%7CZ> impedances are all equal, so middle Z has no current going through it, nodes on either side are at the same EMF <File:Example19d.png%7Cmiddle> Z can be replaced by short or open, since no current is going through it ## Example 2 Cube <File:Example20a.png%7Coriginal> flattened cube of resistors <File:Example20b.png%7Cidentifying> identical EMF locations <File:Example20d.png%7Credrawing> idential EMF as the same nodes, can see three groups of parallel resistors ## Example 3 2D-Grid\ Suppose there is an infinite 2 dimensional grid of impedances (Z). What is the input impedance if connected across (in parallel) with any given impedance? <File:Example21a.png%7CCurrent> due to injection at any spot splits in quarters and then begins to fill the resistive grid like water filling an infinite bucket. <File:Example21b.png%7CCurrent> removed at another spot splits in quarters and then begins to drain the resistive grid like draining an infinite bucket. <File:Example21c.png%7CTogether> the two create a steady state situtation where the question \"What is the input impedance\" can be asked. The current i is i/4 + i/4 = i/2. v = i/2\*Z so v/i = Z/2 = input impedance. If the grid were three dimensional, the current would split into 6 equal sections, thus the input impedance would be Z/3. So what does this mean? It helps us understand that the infinity of space has an impedance: 376.730\... ohms which is plank\'s impedance \* 4π and is related to the speed of light, the permeability of free space and permitivity of free space. Perhaps this is related entanglement and to the trinity since: $\frac{Z}{3} = \frac{1}{\frac{1}{Z} + \frac{1}{Z} + \frac{1}{Z}}$
# Circuit Theory/Y Δ !Circuit after Δ Y transformation of top bridge .. can now use parallel/serial combinations rather than source injection to find Thevenin\'s resistanceThe bridge circuit example was solved with source injection, but could have been solved with a Y Δ transformation. ![](Example23g.png "Example23g.png")\ The 5,2 and 3 ohm resistors form a Δ that could be transformed into a Y. ![](Wye-delta-2.svg)\ The equations are: $$R_1 = \frac{R_bR_c}{R_a + R_b + R_c}, R_2 = \frac{R_aR_c}{R_a + R_b + R_c}, R_3 = \frac{R_aR_b}{R_a + R_b + R_c}$$ $$R_1 = \frac{5*2}{3 + 5 + 2}=1, R_2 = \frac{3*2}{3 + 5 + 2}=0.6, R_3 = \frac{3*5}{3 + 5 + 2}=1.5$$ Now Thevenin\'s resistance can be solved by parallel and serial combinations: $$R_{th} = \frac{1}{\frac{1}{8} + \frac{1}{10.6}} + 1.5 = 6.0591$$ Which is the same value found through source injection.
# Circuit Theory/Quadratic Equation Revisited ### The Quadratic Equation The roots to the quadratic polynomial $y = ax^2 + bx +c$ are easily derived and many people memorized them in high school: $\begin{align} x &= \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}. \end{align}$ ### Derivation of the Quadratic Equation To derive this set $y = 0$ and complete the square: $\begin{align} 0 &= ax^2 + bx +c \\ 0 &= a \left( x^2 + \frac{b}{a} x + \frac{c}{a} \right)\\ 0 &= x^2 + \frac{b}{a} x + \left(\frac{b}{2a}\right)^2 + \frac{c}{a} - \left(\frac{b}{2a}\right)^2 \\ 0 &= \left( x + \frac{b}{2a} \right)^2 + \left(\frac{c}{a} - \left(\frac{b}{2a}\right)^2 \right). \end{align}$ Solving for $x$ gives $\begin{align} 0 &= \left( x + \frac{b}{2a} \right)^2 + \left(\frac{c}{a} - \left(\frac{b}{2a}\right)^2\right) \\ \left( x + \frac{b}{2a} \right)^2 &= -\left(\frac{c}{a} - \left(\frac{b}{2a}\right)^2\right) \\ &= \frac{b^2 - 4ac }{\left(2a\right)^2}. \end{align}$ Taking the square root of both sides and putting everything over a common denominator gives $\begin{align} x + \frac{b}{2a} &= \pm \sqrt{\frac{b^2 - 4ac }{\left(2a\right)^2}} \\ x &= \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}. \end{align}$ ### Numerical Instability of the Usual Formulation of the Quadratic Equation Middlebrook has pointed out that this is a poor expression from a numerical point of view for certain values of $a$, $b$, and $c$. \[Give an example here\] Middlebrook showed how a better expression can be obtained as follows. First, factor $-\frac{b}{2a}$ out of the expression: $\begin{align} x &= \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \\ &= \left( -\frac{b}{2a} \right) \left( 1 \pm \sqrt{1 - \frac{4ac}{b^2}} \right). \end{align}$ Now let $Q^2 = \frac{ac}{b^2}.$ Then $\begin{align} x &= \left( -\frac{b}{2a} \right) \left( 1 \pm \sqrt{1 - 4Q^2} \right) \end{align}$ ### A More Numerically Stable Formulation of the Negative Root Considering just the negative square root we have $\begin{align} x_1 &= \left( -\frac{b}{2a} \right) \left( 1 - \sqrt{1 - 4Q^2} \right). \end{align}$ Multiplying the numerator and denominator by $1 + \sqrt{1 - 4Q^2}$ gives $\begin{align} x_1 &= \left( -\frac{b}{2a} \right) \left( 1 - \sqrt{1 - 4Q^2} \right) \left( \frac{1 + \sqrt{1 - 4Q^2}}{1 + \sqrt{1 - 4Q^2}} \right) \\ &= \left( -\frac{b}{2a} \right) \left( \frac{1 - 1 + 4Q^2}{1 + \sqrt{1 - 4Q^2}} \right) \\ &= -\frac{2 b Q^2}{a} \left( \frac{1}{1 + \sqrt{1 - 4Q^2}} \right) \\ &= -\frac{2 b \left( \frac{ac}{b^2} \right)}{a} \left( \frac{1}{1 + \sqrt{1 - 4Q^2}} \right) \\ &= -\frac{2 c}{b} \left( \frac{1}{1 + \sqrt{1 - 4Q^2}} \right) \\ &= -\frac{c}{b} \left( \frac{1}{\frac{1}{2} + \frac{1}{2}\sqrt{1 - 4Q^2}} \right). \end{align}$ By defining $F = \frac{1}{2} + \frac{1}{2}\sqrt{1 - 4Q^2}$ we can write $\begin{align} x_1 &= -\frac{c}{bF} . \end{align}$ Note that as $Q \to 0$, $F \to 1$. ### Finding the Positive Root Using the Same Approach Turning now to the positive square root we have $\begin{align} x_2 &= \left( -\frac{b}{2a} \right) \left( 1 + \sqrt{1 - 4Q^2} \right) \\ &= \left( -\frac{b}{a} \right) \left( \frac{1}{2} + \frac{1}{2}\sqrt{1 - 4Q^2} \right) \\ &= -\frac{bF}{a}. \end{align}$ Using the two roots $x_1$ and $x_2$, we can factor the quadratic equation $\begin{align} y &= a x^2 + b x + c \\ &= a \left( x^2 + \frac{b}{a} + \frac{c}{a}\right) \\ &= a \left( x - x_1\right) \left( x - x_2\right) \\ &= a \left( x + \frac{c}{bF}\right) \left( x +\frac{bF}{a}\right). \end{align}$ ### Accuracy for Low $Q$ For values of $Q \le 0.3$ the value of $F$ is within 10% of 1 and we may neglect it. As noted above, the approximation gets better as $Q \to 0$. With this approximation the quadratic equation has a very simple factorization: $\begin{align} y &= a x^2 + b x + c \\ &\approx a \left( x + \frac{c}{b}\right) \left( x +\frac{b}{a}\right), \end{align}$ an expression that involves no messy square roots and can be written by inspection. Of course, it is necessary to check the assumption about $Q$ being small before using the simplification. Without this simplification, $F$ needs to be calculated and the roots are slightly more complicated. \[Explore the consequences if $Q > 0.5$.\]
# Circuit Theory/Transients Transient analysis produces an equation of voltage or current. ## Energy Imbalance The temporary conditions are caused by an energy imbalance. The energy imbalance occurs between power sources and capacitors or inductors. Power sources may charge capacitors or inductors. The capacitors or inductors may dump previously stored energy into resistors, each other or charge power sources. Transients occur while energy is being balanced in the circuit. ## Transient Origins The events that can cause transients are: - switching on power - changing a component\'s value in a functioning circuit - discharging a component after the circuit has been turned off Turning a knob can change a value, but so can temperature, light, acceleration, stretching, compressing, humidity, etc. Electrical transducers sense non-electrical energy and cause resistance, capacitance or inductance values to change or change the energy stored in a capacitor/inductor. ## First & Second Order Analysis First order circuits have either a capacitor or inductor. Second order circuits have two energy storage elements and require a different analysis technique. First order transients voltages and currents are typically one sinusoidal riding one exponential. Second order transients are typically described as one of the following: - overdamped - critically damped - underdamped - undamped The word \"damped\" refers how two different types of energy storage elements (capacitors and inductors) interact as energy is dissipated. The math in general shows the combination of two sinusoidals riding on two exponentials. ## Math Summary There are two ways to solve transient problems. #### Differential Equations Something causes the energy imbalance. The goal is to find the final value of a charging circuit, not the equation describing how energy was added to the circuit. The goal is to find an equation for the discharge. The steps are to form a differential equation (no integrals at any step) and evaluate constants. Differential equation analysis requires computing a constant C. Unfortunately, C = 0 in most of the examples below. This is because the equation describes time from 0 to ∞. At t=∞, most designs want all energy eliminated from a circuit. #### Convolution Integral
# Circuit Theory/Initial Conditions ## Both Voltage and Current Initial conditions describe the energy stored in every capacitor and every inductor. Initial conditions are completely specified only when both voltage and current for all capacitors and all inductors is known. ## Assume Zero Assume zero for the capacitor voltage and/or inductor current if no information is given. ## Inductor Initial Conditions Every inductor has two initial conditions: current and voltage. When a switch is thrown that eliminates all power supplies, (or connects new power supplies) the inductor can turn into a power supply itself. The current through an inductor maintains it\'s direction and magnitude between $t(0_-)$ and $t(0_+)$. The voltage may instantaneously switch polarity and/or magnitude. Energy changes elsewhere in a circuit cause an inductor to block these changes by appearing as an open. An Inductors will allow any voltage to appear across it\'s terminals in order to maintain the energy in its magnetic field. An inductor doesn\'t want the current to increase or decrease. Any current change will change the energy stored in its magnetic field. But gradually, an inductor will accept change. And after a very long time it acts like a wire or short allowing current only limited by other devices in the circuit to pass through it. ## Capacitor Initial Conditions Every capacitor has two initial conditions: voltage and current. When a switch is thrown that eliminates all power supplies, (or adds power) the capacitor can turn into a power supply itself. A capacitor maintains it\'s voltage polarity and value between $t(0_-)$ and $t(0_+)$, but the current may instantaneously switch directions and may switch magnitude. A capacitor reacts to energy changes by instantly turning itself into a short or an ideal wire with no resistance. A capacitor doesn\'t care about the current flowing through it. A capacitor doesn\'t want the energy stored in the electric field between its plates to change. So the voltage is maintained, but the current can switch direction and magnitude. The current will only be limited by other devices in the circuit. But after a very long time, a capacitor gradually adapts to change and eventually develops a voltage that the rest of the circuit doesn\'t try to change. At this point the capacitor turns into an open. Inductors and capacitors both react to energy changes, but in exactly the opposite ways. ## Particular Solution The particular solution in response to a step function turns into a set of conditions that have to be present at t = ∞. These conditions should be true at all times .. and can be used to help evaluate constants. ## Progression Start with an expression with a voltage across the capacitor. This way the progression through all possible initial conditions requires taking derivatives: $$H(s)=\frac{\mathbb{V}_C}{\mathbb{V}_s} \Rightarrow V_C(t) \Rightarrow i(t) = C{d V_C(t) \over dt} \Rightarrow V_L = L{d i(t) \over dt}$$ Starting at V_L means evaluating integrals and their constants: $$H(s)=\frac{\mathbb{V}_L}{\mathbb{V}_s} \Rightarrow V_L(t) \Rightarrow i(t) = \frac{1}{L}\int V_L dt \Rightarrow V_C = \frac{1}{C}\int i(t) dt$$ Starting at the current means that may have to do both a derivative and an integral to evaluate all constants. This detail is displayed by doing one example problem four different ways. ## Summary t=0~-~ t=0~+~ source energy imbalance response value starting point ------------------------- ------------------------ --------------------------- ----------------------------------- ----------------------------------------- V~c~(0~-~) = V~c~(0~+~) capacitor itself short problem statement/assume 0 particular solution to previous problem I~c~(0~-~) ≠ I~c~(0~+~) circuit cap is in doesn\'t care determined by rest of circuit capacitor terminal relation, node, mesh I~L~(0~-~) = I~L~(0~+~) inductor itself open problem statement/assume 0 particular solution to previous problem V~L~(0~-~) ≠ V~L~(0~+~) circuit inductor is in doesn\'t care determined by the rest of circuit inductor terminal relation, node, mesh
# Circuit Theory/Time Constants Homogeneous equations are exponential. A homogeneous differential equation is discharging or charging (0 value constant DC source). A non-homogeneous differential equation has a sinusoidal source. It can be solved by splitting into a homogeneous solution plus a particular solution. The steady state solutions earlier were particular solutions. : **homogeneous equation ⇒ discharging (DC source) ⇒ homogeneous solution** \ :**non-homogeneous equation ⇒ AC source ⇒ particular (steady state) + homogeneous (discharging) solution** The proof of the exponential solution to the discharging circuit is is hard: - guess solution - see if it is possible - if possible assume it is the solution In this case it works because there is only one guess: !Capacitor voltage step-response.{width="230"} !Resistor voltage step-response.{width="230"} that we know of. A first order differential looks like this: $$g(t) +\tau \frac{d g(t)}{dt} = 0$$ A solution is: $$g(t) = e^{- \frac{t}{\tau}}$$ (Gödel proved that there are always other truths possible. We can not be certain this is the only solution.) Tau, τ, or $\tau$ has a name: $$\tau$$ = time constant The Steady State(particular) definition is: $$t \ge 5*\tau$$ since for charging and discharging: $$1-e^{-5} = .9933, e^{-5} = 0.0063$$ Try to write all answers in the form of $$g(t) = e^{- \frac{t}{\tau}}$$ instead of: $$g(t) = e^{number * t}$$ The reason is: looking at a number and taking the inverse of it is hard. This makes it hard to look at an equation and \"see\" it\'s time constant. The units of any time constant are seconds. In circuits with both inductors and capacitors, there are two time constants that are called \"zeros\". They are called zero\'s because they are solutions to the particular solution which sets the differential to zero. They are given the symbol \"s\" and are identical to the complex frequency concept.
# Circuit Theory/1Initially Excited Circuits are used to charge capacitors and inductors. Then the inductor/capacitor is switched out of the charging circuit and into the discharging circuit. There are three concepts: - charging circuit \... assume on a long time if time on not specified \... assume steady state so capacitors are opens and inductors are shorts - switching circuit (different for capacitors and inductors) - discharging circuit \... assume initially capacitors are shorts and inductors are opens There are two circuits to analyse: charging and discharging: - Charging circuit \... Assume initial conditions zero, find steady state (particular) solution \... these become the initial conditions to the discharging circuit. - Discharging circuit find the (homogeneous solution). Solving the discharging circuit has these steps: - assume the solution is an exponential - find an exponential solution - use the initial conditions and final value conditions to find the constants. - If an exponential solution can be found (i.e. there is a real part), then the assumption was valid. ## Capacitors <File:Ch7CapSwitchingCircuit.png%7CCapacitor> charging and discharging circuit separated by a switch <File:Ch7capcharging.png%7CEquivalent> charging circuit <File:Ch7capswitched.png%7CMost> switches are BBM (break before make) so the capacitor is an open while the single pole is being thrown between the two poles. Super capacitors store lots of energy, charge up very fast, discharge very fast and could replace batteries. <File:Ch7capDischarging.png%7CEquivalent> discharging circuit ### Charge Analysis Charge Analysis is steady state analysis. Assume the circuit has been on a long time. The capacitor has had a long time to charge up. What is different is that instead of a sinusoidal source, there is a DC voltage source. There is going to be a DC steady state voltage across the capacitor. A capacitor looks like an open when fully charged, so the full source voltage is going to be across the capacitor. So in this case the initial voltage across the capacitor is 1 volt. ### Discharge Analysis !Looking at a capacitor discharging, marking up the current direction and voltage polarity consistent with the normal terminal relations .. for wikibook circuit theory A trivial mesh or loop analysis (both result in the same equation) would be: $$V_R + V_c = 0$$ $$R*i + V_c = 0$$ From the capacitor terminal relationship: $$i=C{d Vc \over dt}$$ So substituting: $$RC{d Vc \over dt} + V_c =0$$ Of course, after a long time, the capacitor discharges, the resistor dissipates all the energy and both current and voltage everywhere will be zero. But what is the equation in the time domain that describes how the voltage and current go to zero? Notice that the current is going down while charging, but switches to going up when discharging. This can be instantaneous. #### finding time constant The general technique is to assume this form: $$V_c = A*e^{-\frac{t}{\tau}}$$ Substituting into the above differential equation: $$-\frac{RCA}{\tau}e^{-\frac{t}{\tau}} + A*e^{-\frac{t}{\tau}} = 0$$ Dividing through by A and the exponential, have: $$-\frac{RC}{\tau} + 1 = 0$$ Solving for tau: $$\tau = RC$$ #### finding the constants So the formula for voltage across the capacitor is now: $$V_c = A*e^{-\frac{t}{RC}} + C$$ This includes the steady state particular solution of 0 and the constant C that comes from solving a differential equation. The initial voltage across the capacitor is +1 volt at t=0~+~. This means that: $$V_c(0_+) = 1 = A + C$$ After a long period of time, the V_c(t) = 0. This helps us find find C: $$V_c(\infty) = A*0 + C = 0$$ So C = 0 and A = 1 and: $$V_c(t) = e^{-\frac{t}{RC}}$$ #### finding the current !Looking at a capacitor discharging, marking up the current direction and voltage polarity consistent with the normal terminal relations .. for wikibook circuit theory V~c~=-V~r~ or could plug into the capacitor terminal relation $$I = \frac{V_r}{R} = \frac{-Vc}{R} = -\frac{e^{-\frac{x}{RC}}}{R}$$ Thus for this circuit: $$V_C = e^{-\frac{t}{RC}}=e^{-\frac{t}{10\mu s}}$$ $$V_r = -e^{-\frac{t}{10\mu s}}$$ And: $$I = - \frac{e^{-\frac{t}{10\mu s}}}{10}$$ #### Interpreting the results V~c~ is in the polarity indicated. V~R~ is opposite the polarity drawn. The current is going in the opposite direction drawn, which makes sense if the capacitor is acting like a voltage source and dumping it\'s energy into the resistor. Both are going to be essentially zero after 5 time constants which is 50 μs. The homogeneous solution was easy to find because a DC source was used to charge the circuit. The particular solution of the discharge circuit was 0 because there was no forcing function. ## Inductors <File:Ch7IndustorSwitchingCircuit.png%7CThis> circuit shows an inductor sitting between a charging circuit and discharging circuit. Because most switches are BBM, a push button was added to short the inductor before the SPDT switch is thrown. Both switches could be replaced by a single SPDT MBB switch. However simulation software typically just has BBM switches. <File:Ch7InductorCharging.png%7CThe> equivalent inductor charging circuit <File:Ch7IndustorSwitchingCircuitEffective.png%7CThe> equivalent circuit after the push button switch is pressed, but before the SPDT BBM switch is thrown. <File:Ch7InductorSwitched.png%7CThe> equivalent circuit after the SPDT BBM switch is thrown while the push button switch maintains contact. Superconductors can be energy storage devices just like super capacitors. Current moves at the speed of light through a circular wire that acts like a continuous inductor. <File:Ch7InductorDischarging.png%7CThe> equivalent inductor discharging circuit after the push button switch is released. ### Charge Analysis !When inductor has same initial current as the current source, then no current is going to flow through the short. Superposition says the currents are going to cancel in the short. Charge Analysis is steady state analysis. Assume the circuit has been on a long time. The inductor has had a long time to build up its magnetic fields. What is different is that instead of a sinusoidal source, there is a DC current source. There is going to be a DC steady state current through the inductor. An inductor looks like a short when fully charged, so the full source current is going through the inductor. So in this case the initial current is 1 amp. ### Shorted source and inductor Analysis !An inductor stores it\'s energy in a magnetic field, current has to continue to move to keep the magnetic field from collapsing \... this is the basis of a superconductor !Inductor with initial current discharging through resistor, for wikibook circuit theory Shorting an inductor and current source by pushing the button of SW1 is safe. (It is dangerous to open wires to an inductor or current source). With ideal components, there will be no current through the short. However current through the inductor remains the same and the inductor remains charged up. ### Shorted inductor energy storage The instant the SPDT switch cuts out the current source, the inductor\'s current appears in the short. The inductor and shorting wire do not store energy very long (unless frozen because the wire acts like a resistor). ### Discharge Analysis Immediately after SW2 has completed moving the throw over to the second pole and the push button switch is released, the current of 1amp still flows through the inductor. A voltage instantly appears across the inductor and resistor. A trivial mesh or loop analysis (both result in the same equation) would be: $$V_R - V_L = 0$$ Looking at the circuit markup, the current and voltage don\'t have the positive sign convention relationship so the inductor\'s terminal relationship has a negative sign: $$V_L= - L\frac{di}{dt}$$ So: $$R*i + L\frac{di}{dt} = 0$$ Of course, after a long time, the inductor discharges, the resistor dissipates all the energy and both current and voltage everywhere will be zero. But what is the equation in the time domain that describes how the voltage and current go to zero? Notice that the voltage is positive on top of the inductor but switches polarity when discharging. This can be instantaneous. #### finding time constant The general technique is to assume this form: $$i = A*e^{-\frac{t}{\tau}}$$ Substituting into the above differential equation: $$R*A*e^{-\frac{t}{\tau}} + L*\frac{d (A*e^{-\frac{t}{\tau}})}{dt} = 0$$ Dividing through by A and then evaluating the derivative, have: $$R*e^{-\frac{t}{\tau}} - \frac{L*e^{-\frac{t}{\tau}}}{\tau} = 0$$ Dividing through by the exponential: $$R - \frac{L}{\tau}=0$$ Solving for tau: $$\tau = \frac{L}{R}$$ #### finding the constants So the formula for current now is: $$i = A*e^{-\frac{t}{\frac{L}{R}}} + C$$ The steady state particular solution is 0, and the constant C comes from solving the differential equation. The initial current is 1 amp at t=0~+~. This means that: $$1 = A + C$$ After a long time, there is nothing going on in the circuit so: $$i(\infty) = A*0 + C$$ So A=1 and C=0 thus: $$i(t) = e^{-\frac{t}{\frac{L}{R}}}$$ #### finding the voltage across the Inductor/Resistor V~L~=V~r~ or could plug into the inductor terminal relation $$V_R = R*i = R * e^{-\frac{t}{\frac{L}{R}}}$$ of plugging into the terminal relation: $$V_L = - L*\frac{d (e^{-\frac{t}{\frac{L}{R}}})}{dt} = -L*(\frac{-R}{L})e^{-\frac{t}{\frac{L}{R}}} = Re^{-\frac{t}{\frac{L}{R}}}$$ So in summary: $$V_R = V_L = 10*e^{-\frac{t}{0.1\mu s}}$$ $$i = e^{-\frac{t}{0.1\mu s}}$$ #### Interpreting the results Maintaining the current and magnetic field energy of an inductor requires shorting it during the switching between circuits. This would be just as simple as switching a capacitor, but a different type of switch is required: \... a make before break switch .. so that two circuits are connected simultaneously. The discharge circuit was marked up with the final directions and polarity of everything. But the terminal relationship for the inductor had to have a negative sign in it because the voltage and current directions did not follow the positive sign convention. Again, the homogeneous solution was easy to find because a DC source was used to charge the circuit. The particular solution of the discharge circuit was 0 because there was no forcing function.
# Circuit Theory/1Source Excitement Phasors: : Called the **\"Steady State Solution\"** solution : Sometimes the **\"Steady State Solution\"** resulted in a complete solution, sometimes a partial solution. : Full **\"Steady State Solutions\"** involved integrals and derivatives : Partial **\"Steady State Solutions\"** involved non-homogeneous ODE differential equations : The partial **\"Steady State Solution\"** is called the **\"Particular solution\"**. : The **Laplace Solution** is a complete solution that is identical to **Phasor/Complex Frequency** when eliminating operators in a differential equation (s or jω), but translates the driving function (current or voltage source) into the **Laplace domain** differently. The **Laplace Solution** can translate any driving function. **Phasors** can only translate sinusoidals. The **Convolution Integral** (coming up) is easier than either. Now we are going to finish solving the some of the incomplete, particular **\"Steady State Solutions.\"** : The non-homogeneous ODE equation is turned **homogeneous** by setting the driving function (voltage or current source) to zero and then using either the \"Method of undetermined coefficients\" or \"Variation of parameters\" to find the overall solution. The method illustrated here is the **\"Method of undetermined coefficients\"**. : This is called the **\"Transient\"** or **Homogeneous Solution**. : The **Homogeneous Solution** is found in the time domain, not phasor domain : Reduce circuit to thevenin or norton equivalent and solve for a single component (or group or components) : Add **Particular** + **Homogeneous Solution**, then evaluate **constants**. Click on the numeric solutions to see where they came from. Clicking on particular solutions or non-diff-eq solutions will bounce back to phasor examples. +-------------+-------------+-------------+-------------+-------------+ | Calculus | diff eq | LR | LR Solution | Similar RC | +=============+=============+=============+=============+=============+ | ${\ | $\texts | ! | [ | ![ | | textstyle d | tyle \surd$ | | $V_s(t) = 1 | | | \over dt}$ | | | 20 \sqrt{2} | | | ](Circuit_T | | | cos(377t+1 | | | heory/Phaso | | | 20^\circ)$\ | | | rs/Examples | | | $V_s(t) = | | | /Example_7 | | | R * i(t) + | | | "wikilink") | | | L * {d \ove | | | | | | r dt}i(t)$\ | | | | | | $i_{ | | | | | | S_P}(t) = 1 | | | | | | 5.9 cos(377 | | | | | | t + 1.73)$] | | | | | | (Circuit_Th | | | | | | eory/Phasor | | | | | | s/Examples/ | | | | | | Example_7 " | | | | | | wikilink")\ | | | | | | \ | | | | | | $i | | | | | | _{S_H}(t) = | | | | | | 2.5781*e^ | | | | | | {-\frac{t}{ | | | | | | 0.001}}$ | | +-------------+-------------+-------------+-------------+-------------+ | ${\ | | ! | [ | ![ | | textstyle d | | | $I_s(t) = 1 | | | \over dt}$ | | | 20 \sqrt{2} | | | ](Circuit_T | | | cos(377t+1 | | | heory/Phaso | | | 20^\circ)$\ | | | rs/Examples | | | $V_s(t) = | | | /Example_8 | | | R * i(t) + | | | "wikilink") | | | L * {d \ove | | | | | | r dt}i(t)$\ | | | | | | $V_s = 1 | | | | | | 814cos(377t | | | | | | +2.45)$](Ci | | | | | | rcuit_Theor | | | | | | y/Phasors/E | | | | | | xamples/Exa | | | | | | mple_8 "wik | | | | | | ilink")\<br | | | | | | \\\>\<br | | | | | | \\\>already | | | | | | solved \... | | | | | | no | | | | | | d | | | | | | ifferential | | | | | | equation! | | +-------------+-------------+-------------+-------------+-------------+ | ${\texts | | ! | [ | ![ | | tyle \int}$ | | | $V_s(t) = 1 | | | ](Circuit_T | | | 20 \sqrt{2} | | | heory/Phaso | | | cos(377t+1 | | | rs/Examples | | | 20^\circ)$\ | | | /Example_9 | | | ${ | | | "wikilink") | | | dI_s(t) \ov | | | | | | er dt}= \fr | | | | | | ac{1}{R}{dV | | | | | | _s \over dt | | | | | | } + \frac{V | | | | | | _s}{L}$\<br | | | | | | \\\>$i_s | | | | | | (t) = 48.1 | | | | | | cos(377t + | | | | | | 0.844)$](Ci | | | | | | rcuit_Theor | | | | | | y/Phasors/E | | | | | | xamples/Exa | | | | | | mple_9 "wik | | | | | | ilink")\<br | | | | | | \\\>\<br | | | | | | \\\>already | | | | | | solved \... | | | | | | no | | | | | | d | | | | | | ifferential | | | | | | equation! | | +-------------+-------------+-------------+-------------+-------------+ | [${\textst | $\texts | ![ | [ | ![ | | yle \int}$] | tyle \surd$ | ](PILR.xcf) | $I_s(t) = 1 | ](SVRC.xcf) | | (Circuit_Th | | | 20 \sqrt{2} | | | eory/Phasor | | | cos(377t+1 | | | s/Examples/ | | | 20^\circ)$\ | | | Example_10 | | | ${ | | | "wikilink") | | | dI_s(t) \ov | | | | | | er dt}= \fr | | | | | | ac{1}{R}{dV | | | | | | _s \over dt | | | | | | } + \frac{V | | | | | | _s}{L}$\<br | | | | | | \ | | | | | | \\>$V_{S_P} | | | | | | (t) = 599 \ | | | | | | cos(377t + | | | | | | 3.30)$](Cir | | | | | | cuit_Theory | | | | | | /Phasors/Ex | | | | | | amples/Exam | | | | | | ple_10 "wik | | | | | | ilink")\<br | | | | | | \\\>\<br | | | | | | \\\>$V_{ | | | | | | S_H}(t) = - | | | | | | 258 * e^{\ | | | | | | frac{-t}{0. | | | | | | 0001}}$ | | +-------------+-------------+-------------+-------------+-------------+
# Circuit Theory/2Initially Excited !full circuit with charging section, discharging section and two switches !charging circuit (sw1 closed, sw2 open)") !discharging circuit (sw1 open, sw closed)") ## Charging The source voltage could be DC. In this case the initial capacitor voltage is going to be V~s~ and the derivative of the voltage is going to be zero. The source voltage could be AC in which case the exact time or more precise phase angle of the switch over is going to determine V~s~ and the derivative of the voltage values. ## Discharging The initial inductor current is going to be zero and derivative is going to be zero. After a long time nothing will be going on. The steady state particular solution is going to be zero. The current is going to be the same throughout. Goal should be to find an expression for the current. However, any voltage could also be found and then the current. Doesn\'t matter. In summary, there will be no initial current in the discharging circuit, there will be a voltage across the capacitor. The inductor is going to act like an open at t=0~+~ so this entire voltage will appear across the inductor and instantly (between t=0~-~ and t=0~+~) cause a change in the derivative of the current through the inductor. The equation for the current for first order circuits would be: $$V_c(t) = A e^{-\frac{t}{\tau}}$$ However, this is a 2nd order circuit (with both capacitors and inductors), thus: $$V_c(t) = A e^{-st}$$ The complex frequency s has replace tau. The time constant concept disappears. An intuitive interpretation of s exists, but is more complicated. Remember: $$s = \sigma + j\omega$$ ## The differential equation Go back to the complex frequency domain to find the time constant. Start with the loop equation: $$V_c + V_r + V_L =0$$ Substitute terminal equation for V~r~ and V~L~ but not for V~c~ because want to avoid an integral: $$V_c + i(t)R + L{d i(t) \over dt} = 0$$ From the terminal relation of a capacitor, know that: $$i(t) = C {d V_c \over dt}$$ So substituting in, have a differential equation for V~c~: $$V_c + RC{d V_c \over dt} + LC{d^2 V_c \over dt^2} = 0$$ Can see the second order now. ## Finding the time constant or zeros A zero is like a time constant, but there are more than one zero\'s possible. They might each influence the circuit differently. Need to find V~c~. The particular solution (steady state) is going to be zero. (Where the name zero comes from). The homogeneous solution is going to be of this form: $$V_c(t) = Ae^{st}$$ Plugging into the differential equation: $$Ae^{st} + RCAse^{st} + LCAs^2e^{st} = 0$$ Dividing out Ae^st^ have: $$1 + RCs + LCs^2 = 0$$ $$s^2 + \frac{Rs}{L} + \frac{1}{LC} = 0$$ The zero\'s of this equation are: $$s_{1,2} = -\frac{R}{2L} \pm \sqrt{(\frac{R}{2L})^2 - \frac{1}{LC}} = -(\sigma \pm j\omega)$$ From your experience with quadratics you know that ~1,2~ come in three types of pairs: Pair Type Revised equation for V~c~ interpretation ----------------- ---------------------------------------------------- ------------------------------------------------------------------------------------- real, not equal $A_1e^{s_1t} + A_2e^{s_2t}$ overdamped equal $A_1e^{st} + A_2te^{st}$ critically damped complex $e^{-\sigma t}(A_1\cos\omega t + A_2\sin\omega t$) underdamped The revised equations (guesses) come from math proofs, and some courses derive these from Laplace transformations. Just remember this table. There are two storage elements with two initial conditions each, so there could be four equations and four constants. A~1~ and A~2~ are two of them. !for undamped (blue), under-damped (green), critically damped (red), and over-damped (cyan) cases, under-damped (green), critically damped (red), and over-damped (cyan) cases") To understand damping, think of a car driving over a curb. Undamped means the car bounces up and down for ever. Under-damped is what happens when the shocks start leaking (car bounces up and down for a while \... like riding in a boat). Critically damped is why people hate sports cars (hurts their bottom). An over damped response in a car gives feedback to a person driving a car. Circuits like that above have been used to model shock obsorbers. These circuits are called analog computers. ## Almost Resonance (Underdamped) !Impact of R and L on resonance The most interesting of the above three is Underdamped. Something like resonance occurs. Satellites expand and contract depending upon which side is facing the sun or the 2.7 kelvin of space. Repeated expansion and contraction creates an oscillation that needs to be damped out by a motor that flings a weight around that dampens the vibration. Otherwise everything that can wiggle will wiggle more and more until parts begin to break off. (A car on earth is no different). Most control circuit input is an unbalanced situation. The output models the desired behavior. The correcting (feedback control) circuits (not talked being studied here) kick in to make sure the actual behavior matches the desired behavior. Most often the objective is to design a critically damped circuit, rather than merely predict what is going to happen. Resonance (or close to it) occurs when s~1~ and s~2~ are purely imaginary. $$s_{1,2} = -\frac{R}{2L} \pm \sqrt{(\frac{R}{2L})^2 - \frac{1}{LC}} = -(\sigma \pm j\omega)$$ So: $$\sigma = \frac{R}{2L}$$ What is interesting is the radical term. It determines the nature of the 2nd order response. Pure resonance occurs when the real part of the quadratic solution is zero which would only happen when R \<\< L. !Crystals are modeled with a capacitor in parallel with a series RLC network The contents of the radical don\'t have to be zero, only the real part has to be zero in order to be overdamped: $$j\omega = \sqrt{(\frac{R}{2L})^2 - \frac{1}{LC}}$$ $$j\omega = j\sqrt{\frac{1}{LC} - (\frac{R}{2L})^2}$$ The j\'s cancel, and we have already assumed R \<\< L, so: $$\omega = \sqrt{\frac{1}{LC} - (\frac{R}{2L})^2}$$ Which called the damped, ringing, or undamped frequency. When R \<\< L, then this turns into the resonate frequency: $$\omega = \sqrt{\frac{1}{LC}}$$ Mechanical engineers try to predict ω for a given structure and materials. It could be a building or motor mount. The math proves that ω exists. Finding the exact ω usually requires testing. Instead of capacitors and inductors, mechanical engineers model everything with springs and dampers. Finding ω can be hard. This why there is an entire industry of shake tables. The spring and damper values in a structure determine how narrow or muted the resonance is. When designing a building, mechanical engineers want the envelope to be as wide and flat (muted) as possible. When designing a notch filter the electrical engineer\'s design goal is the opposite: a tall and narrow envelope. Electrical engineers call this quality. Most oscillators today are built from crystals.
# Circuit Theory/2Source Excitement Examples worked out: - LRC circuit #1 - parallel RLC network with extra resistor in L leg Working on this example: !Circuit analyzed earlier with Kirchhoff\'s laws This circuit was earlier analyzed using Kirchhoff. The goal is to repeat the analysis using Node and Mesh \... then find Thevenin\'s voltage, Norton\'s current and the equivalent impedance of the circuit from R~3~\'s point of view. The Kirchhoff goal is to find everything: : *Given that the voltage source is defined by $V_s(t) = 10cos(1000t + 30^{\circ})$ and the current source is defined by $I_s(t) = 0.5 sin(1000t + 45^{\circ})$, find all other voltages, currents and power of the sources.* The /Node and Mesh/ analysis goal does not find everything. Node voltages and mesh currents are the first things found. Then everything else can be found. /Thevenin and Norton/ look at the rest of the circuit from just one component (or group of components) point of view. So even fewer voltages and currents are found.
# Circuit Theory/Convolution Integral !Examples of arbitrary sources that could drive a circuit ## Impulse Response So far circuits have been driven by a DC source, an AC source and an exponential source. If we can find the current of a circuit generated by a Dirac delta function or impulse voltage source δ, then the convolution integral can be used to find the current to any given voltage source! ## Example Impulse Response The current is found by taking the derivative of the current found due to a DC voltage source! Say the goal is to find the δ current of a series LR circuit .. so that in the future the convolution integral can be used to find the current given any arbitrary source. !Series LR circuit with impulse δ function as voltage source Choose a DC source of 1 volt (the real Vs then can scale off this). !Series LR circuit with unit μ step function voltage source The particular homogeneous solution (steady state) is 0. The homogeneous solution to the non-homogeneous equation has the form: $$i(t) = Ae^{-\frac{t}{\frac{L}{R}}} + C$$ Assume the current initially in the inductor is zero. The initial voltage is going to be 1 and is going to be across the inductor (since no current is flowing): $$v(t) = L{d i(t) \over dt}$$ $$v(0) = 1 = L * (-\frac{A R}{L})$$ $$A = -1/R$$ If the current in the inductor is initially zero, then: $$i(0) = 0 = A + C$$ Which implies that: $$C = -A = 1/R$$ So the response to a DC voltage source turning on at t=0 to one volt (called the unit response μ) is: $$i_\mu (t) = \frac{1}{R}(1 - e^{-\frac{t}{\frac{L}{R}}})$$ Taking the derivative of this, get the impulse (δ) current is: $$i_\delta (t) = \frac{e^{-\frac{t}{\frac{L}{R}}}}{L}$$ Now the current due to any arbitrary V~S~(t) can be found using the convolution integral: $$i(t) = \int_0^t i_\delta (t-\tau) V_s(\tau) d\tau = \int_0^t f(t-\tau)g(\tau)d\tau + C_1$$ Don\'t think i~δ~ as current. It is really ${d \over dt}\frac{current}{1 volt}$. V~S~(τ) turns into a multiplier. ## LRC Example !RLC problem for circuit theory wikibook Find the time domain expression for i~o~ given that I~s~ = cos(t + π/2)μ(t) amp. Earlier the step response for this problem was found: $$i_{o_\mu} = \frac{1}{2}(1 - e^{-t}(\cos t + \sin t))$$ The impulse response is going to be the derivative of this: $$i_{o_\delta} = {d i_{o_\mu} \over dt} = 0 + \frac{1}{2}e^{-t}(\cos t + \sin t) - \frac{1}{2}e^{-t}(-\sin t + \cos t)$$ $$i_{o_\delta} = \frac{1}{2}e^{-t}(\cos t + \sin t + \sin t - \cos t) = e^{-t}\sin t$$ $$I_s = 1 + \cos t$$ $$i_o(t) = \int_0^t i_{o_\delta} (t-\tau) I_s(\tau) d\tau + C_1$$ $$i_o(t) = \int_0^t e^{-(t-\tau)}\sin (t-\tau) (1 + \cos \tau) d\tau + C_1$$ $$i_o(t) = \frac{\cos t}{5} + \frac{2 \sin t}{5} - \frac{7 e^{-t}\cos t}{10} - \frac{11 e^{-t}\sin t}{10} + \frac{1}{2} + C_1$$ The Mupad code to solve the integral (substituting x for τ) is: f := exp(-(t-x)) *sin(t-x) *(1 + cos(x)); S := int(f,x = 0..t) ## Finding the integration constant $$i_o(0_+) = 0 = \frac{1}{5} - \frac{7}{10} + \frac{1}{2} + C_1$$ This implies: $$C_1 = 0$$ ## TO DO $$i(t) = \int_0^t i_\delta (t-\tau) V_s(\tau) d\tau = \int_0^t f(t-\tau)g(\tau)d\tau$$ !Convolution of spiky function with box2.gif This was created with /matlab/, turned into a gif with ImageMagick, cropped with a photo editor and then released into the public domain. Several others have created an alternative animation. - The blue symbol $f(t)$ represents $i_\delta(t)$. - The red symbol $g(t)$ represents the arbitrary $V_s(t)$. - The current due to the V~S~ black (on top of the yellow). - The turn on event occurs at t = 5 seconds, not 0. - The voltage of the source is not on indefinitely. It turns on at zero and off at 5 time constants.
# Circuit Theory/TF Objectives Thevenin/Norton impedance completely characterizes a circuit from a load\'s point of view. Differential equations completely describe a circuit. The impulse response of a circuit is all that is needed to use the convolution integral. Phasors and complex frequencies completely describe a circuit. And even while computing the transient response, complex frequencies associated with the steady state sinusoidal response appeared. Are they all related? Yes. The goal is to understand all the above as a transfer function. Why? Most engineering uses this concept. Here are some electrical applications: - Analog Computers \... (modeling before digital computers) - Signal Processing "wikilink") \... (wireless, cable communication) - Control theory \... (motors don\'t die and don\'t spin out of control when the load changes) - Linear time-invariant system theory \... (general math model which assumes the values of resistors, inductors and capacitors don\'t vary over time, temperature, bias .. but provides a good starting point for establishing expectations and experimenting) The goal is to introduce transfer functions in the context of electronics. ## Transfer Function Definition A **Transfer Function** is the ratio of the output of a system to the input of a system. If we have an input function of *X(s)*, and an output function *Y(s)*, we define the transfer function *H(s)* to be: $$H(s) = {Y(s) \over X(s)}$$ ## Four RLC Transfer Functions In the context of RLC circuits, transfer functions are in a phasor/complex frequency/laplace domain concept. They are not a time domain concept. They are independent of the forcing function/source. There are four possible RLC transfer patterns: $\frac{output}{input}$ Example Circuit Transfer Function -------------------------------- ------------------------------------------------------------------ -------------------------------------- $\frac{V_{out}(s)}{I_{in}(s)}$ !impedance $H(s) = R + Ls$ $\frac{I_{out}(s)}{V_{in}(s)}$ !admittance $H(s) = \frac{1}{R} + Cs$ $\frac{V_{out}(s)}{V_{in}(s)}$ !voltage divider $H(s) = \frac{Ls}{R + Ls}$ $\frac{I_{out}(s)}{I_{in}(s)}$ !current divider $H(s) = \frac{Cs}{\frac{1}{R} + Cs}$ ## Applications The transfer function has many applications as we will soon see. But it\'s immediate benefit is eliminating the need to find the differential equation. Reviewing previous examples: +----------------------+----------------------+----------------------+ | Example | Differential | Transfer Function | | | Equation | | +======================+======================+======================+ | convolution | $$v(t) = L{d i(t) | admittance$$ | ittance "wikilink"): | | p | | | | roblem = \frac{\mathbb{I} | | ral#Example_Impulse_ | | (s)}{\mathbb{V}(s)} | | Response "wikilink") | | = \frac{1}{sL + R}$$ | | | | | | <File:Exa | | | | mple40a.png%7CGiven> | | | | voltage source, find | | | | total current | | | +----------------------+----------------------+----------------------+ | Second Order, | $I_s = {d^2 i_o \ | current divider: | | Source | over dt^2} + 2 {d i_ | | | Excitem | o \over dt} + 2 i_o$ | $$H(s) = \fra | | ent}{\ | | 2Source_Excitement/E | | mathbb{I}_s(s)} = \f | | xample46 "wikilink") | | rac{\frac{1}{R + Ls} | | | | }{\frac{1}{R + Ls} + | | <File:E | | \frac{1}{R} + Cs}$$ | | xample46.png%7CFind> | | | | i~o~ giving Is | | $$H(s) = \frac{ | | | | \mathbb{I}_o(s)}{\ma | | | | thbb{I}_s(s)} = \fra | | | | c{1}{s^2 + 2s + 2}$$ | | | | | | | | | | | | R :=1; L :=1; C :=1; | | | | simplify( | | | | (1/(R + L*s))/(1/(R | | | | + L*s) + 1/R + C*s)) | +----------------------+----------------------+----------------------+ | Second Order, | $V_ | Voltage Divider | | Source | s(t) = L{d (\frac{V_ | $H(s) = \frac{\math | | Excitement \over dt} | bb{V}_{cr}(s)}{\math | | Theory/2Source_Excit | + LC {d^2 (V_{CR} \o | bb{V}_s(s)} = \frac{ | | ement/Example45#Homo | ver dt^2}) + V_{CR}$ | \frac{1}{\frac{1}{R} | | geneous.2FTransient_ | | + Cs}}{\frac{1}{\fr | | Solution "wikilink") | | ac{1}{R} + Cs}+Ls}$\ | | | | $H( | | <File:Exa | | s) = \frac{1}{CLs^2 | | mple45B.png%7CGiven> | | + \frac{Ls}{R} + 1}$ | | V_s, find V_cr | | | +----------------------+----------------------+----------------------+ ## Interpreting Complex Roots After finding the transfer function, the next step is finding the time constant or the complex frequency roots and from these guess the form of the solution. The homogeneous solution is found by setting the denominator of the transfer function to zero. Factoring the denominator and finding the complex frequency roots is called finding \"zeros.\" The numerator (which was one in all the above examples) may have a complex frequency polynomial (in complicated circuits) that can also be set equal to zero. The roots are called \"poles.\" Poles influence the circuit\'s response to different frequencies rather than the time domain response. ## Summarizing Time This ends the normal circuit theory course. Time domain analysis could continue and this is hinted at in the following example. Before WWII it was important to continue in order to model physical systems with analog computers. But today, digital computers can model much more accurately. So stopping time analysis here leaves further study for a specialized class. Let\'s summarize what we have learned about circuits in the time domain. - Superposition allows replacing multiple sources with one source at a time (zeroing the others) and then adding the results of all sources. - Impedance, admittance, voltage divider and current divider formulas lead directly to the differential equations \... which is the same math for phasor/complex frequency and the Laplace domain. - The Convolution integral eliminates the need to transform driving functions (particularly sinusoidal) into the phasor/complex frequency/Laplace domain. Instead the source is replaced with 1 volt or 1 amp, and the particular solution turns into a DC final condition (t = ∞) placed on the homogeneous solution and appears with in the differential equation constant.
# Circuit Theory/State Variables New techniques are needed to solve 2nd order and higher circuits: - Symbolic solutions are so complicated, merely comparing answers is an exercise - Analytical solution techniques are more fragmented - The relationship between constants, initial conditions and circuit layout are becoming complicated A change in strategy is needed if circuit analysis is going to: - Move beyond the ideal - Consider more complicated circuits - Understand limitations/approximations of circuit modeling software The solution is \"State Variables.\" After a state variable analysis, the exercise of creating symbolic solution can be simplified by eliminating terms that don\'t have a significant impact on the output. ### State Space The State Space approach to circuit theory abandons the symbolic/analytical approach to circuit analysis. The state variable model involves describing a circuit in matrix form and then solving it numerically using tools like series expansions, Simpson\'s rule, and Cramer\'s Rule. This was the original starting point of matlab. ### State \"State\" means \"condition\" or \"status\" of the energy storage elements of a circuit. Since resistors don\'t change (ideally) and don\'t store energy, they don\'t change the circuit\'s state. A state is a snap shot in time of the currents and voltages. The goal of \"State Space\" analysis is to create a notation that describes all possible states. ### State Variables The notation used to describe all states should be as simple as possible. Instead of trying to find a complex, high order differential equation, go back to something like Kirchhoff analysis and just write terminal equations. State variables are voltages across capacitors and currents through inductors. This means that purely resistive circuit cut sets are collapsed into single resistors that end up in series with an inductor or parallel to capacitor. Rather than using the symbols v and i to represent these unknowns, they are both called x. Kirchhoff\'s equations are used instead of node or loop equations. Terminal equations are substituted into the Kirchhoff\'s equations so that remaining resistor\'s currents and voltages are shared with inductors and capacitors. ### State Space Model ![](Typical_State_Space_Model_(CT).svg "Typical_State_Space_Model_(CT).svg") This State Space Model describes the inputs (step function μ(t), initial conditions X(0)), the output Y(t) and A,B,C and D. A-B-C-D are transfer functions that combine as follows: $$\frac{\mathbb{Y}}{\mathbb{\mu}} = B(s)\left(\frac{1}{s - A(s)}\right)C(s) + D(s)$$ A control systems class teaches how to build these block diagrams from a desired transfer function. Integrals \"remember\" or accumulate a history of past states. Derivatives predict future state and both, in addition to the current state can be separately scaled. \"A\" represents feedback. \"D\" represents feed forward. There is lots to learn. Don\'t try to figure out how a negative sign appeared in the denominator and where the addition term came from. How does the above help us predict voltages and currents in a circuit? Let\'s start by defining terms and do some examples: - A is a square matrix representing the circuit components (from Kirchhoff\'s equations. - B is a column matrix or vector representing how the source impacts the circuit (from Kirchhoff\'s equations). - C is a row matrix or vector representing how the output is computed (could be voltage or current) - D is a single number that indicates a multiplier of the source .. is usually zero unless the source is directly connected to the output through a resistor. A and B describe the circuit in general. If X is a column matrix (vector) representing all unknown voltages and currents, then: $$\boldsymbol{\dot{X}} = \boldsymbol{A}\boldsymbol{X} + \boldsymbol{B}\boldsymbol{\mu}$$ At this point, X is known and represents a column of functions of time. The output can be derived from the known X\'s and the original step function μ using C and D: $$y = \boldsymbol{C}\boldsymbol{X} + D*\boldsymbol{\mu}$$ ### MatLab Implementation !screen shot of matlab with simulink toolbox showing how to get to the state-space block for wikibook circuit analysis This would not be a step forward without tools such as MatLab. These are the relevant MatLab control system toolbox commands: - step(A,B,C,D) assumes the initial conditions are zero - initial(A,B,C,D,X(0)) just like step but takes into account the initial conditions X(0) In addition, there is a simulink block called \"State Space\" that can be used the same way. ### Video Introduction - 41 minute introduction from digilent corp - 5 minute application to a circuit ## Further reading - Control Systems/State-Space Equations - matlab help links
# Circuit Theory/Fourier Transform right\|framed\|Joseph Fourier, after whom the Fourier Transform is named, was a famous mathematician who worked for Napoleon. This course started with phasors. We learned how to transform forcing sinusodial functions such as voltage supplies into phasors. To handle more complex forcing functions we switched to complex frequencies. This enabled us to handle forcing functions of the form: $$e^{st}\cos(\omega t + \phi)$$ where s is: $$s=\sigma + j\omega$$ And the convolution integral can do anything. Along the way \"s\" began to transform the calculus operators back into algebra. Within the complex domain, \"s\" could be re-attached to the inductors and capacitors rather than forcing functions. The transfer function helped us use \"s\" to capture circuit physical characteristics. This is all good for designing a circuit to operate at a single frequency ω. But what about circuits that operate at a variety of frequencies? A RC car may operate at 27mhz, but when a control is pressed, the frequency might increase or decrease. Or the amplitude may increase or decrease. Or the phase may shift. All of these things happen in a cell phone call or wifi/blue tooth/xbee/AM/FM/over the air tv, etc. How does a single circuit respond to these changes? ## Fourier analysis Fourier analysis says we don\'t have to answer all the above questions. Just one question has to be answered/designed to. Since any function can be turned into a series of sinusoidals added together, then sweeping the circuit through a variety of omegas can predict its response to any particular combination of them. So to start this we get rid of the exponential term and go back to phasors. Set σ to 0: $$s = j\omega$$ The variable ω is known as the \"radial frequency\" or just frequency. With this we can design circuits for cell phones that all share the air, for set-top cable TV boxes that pack multiple channels into one black cable. Every vocal or pixel change during transmission or reception can be designed for within this framework. All that is required is to sweep through all the frequencies that a sinusoidal voltage or current source can produce. Analysis stays in the frequency domain. Because everything repeats over and over again in time, there is no point in going back to the time from a design point of view. ## Radial Frequency In the Fourier transform, the value $\omega$ is known as the **Radial Frequency**, and has units of radians/second (rad/s). People might be more familiar with the variable f, which is called the \"Frequency\", and is measured in units called Hertz (Hz). The conversion is done as such: $$\omega = 2\pi f$$ For instance, if a given AC source has a frequency of 60 Hz, the resultant radial frequency is: $$\omega = 2\pi f = 2\pi(60) = 120\pi$$ ## Fourier Domain The Fourier domain then is broken up into two distinct parts: the **magnitude graph**, and the **phase graph**. The magnitude graph has jω as the horizontal axis, and the magnitude of the transform as the vertical axis. Remember, we can compute the magnitude of a complex value C as: $$C = A + jB$$ $$|C| = \sqrt{A^2 + B^2}$$ The Phase graph has jω as the horizontal axis, and the phase value of the transform as the vertical axis. Remember, we can compute the phase of a complex value as such: $$C = A + jB$$ $$\angle C = \tan^{-1}\left(\frac{B}{A}\right)$$ The phase and magnitude values of the Fourier transform can be considered independent values, although some abstract relationships do apply. Every fourier transform must include a phase value and a magnitude value, or it cannot be uniquely transformed back into the time domain. The combination of graphs of the magnitude and phase responses of a circuit, along with some special types of formatting and interpretation are called Bode Plots.
# Circuit Theory/Bode Plots ## Bode Plots Bode plots plot the transfer function. Since the transfer function is a complex number, both the magnitude and phase are plotted (in polar coordinates). The independent variable ω is swept through a range of values that center on the major defining feature such as time constant or resonant frequency. A magnitude plot has dB of the transfer function magnitude on the vertical axis. The phase plot typically has degrees on the vertical axis. !voltage across capacitor and resistor parallel combination is the output !Bode plot for V~CR~ compared to V~S~ which looks like a passive, low pass filter with slope of -40dB/decade, the cut off frequency looks to be 10^0^ = 1 radian/sec. The resistor dominates at DC and the capacitor dominates at very high frequencies. !find current through R~3~ ## MatLab tr and bode ### Example 1 Previously the transfer function was found to be: $$H(s) = \frac{\mathbb{V}_{cr}(s)}{\mathbb{V}_s(s)} = \frac{1}{CLs^2 + \frac{Ls}{R} + 1} = \frac{1}{s^2 + 2s + 1}$$ MatLab has a short hand notation method for entering this information where the coefficients are listed (high power to low power)(numerator first, then denominator). For this example f = tf([1],[1 2 1]) Leaving the colon off the end should display the transfer function. The next step is to plot it: grid on bode(f) The result is a low pass filter. Rather than understand how to create these plots (not trivial), the goal is to interpret the plot .. (which is almost the same thing). But at this point, the goal is to exercise MatLab. !Bode diagram of R3 current versus V~s~, looks like a notch filter at around 1K radians/sec ### Example 2 Previously the transfer function was found to be: $$\frac{\mathbb{I}_o}{\mathbb{V}_s} = \frac{1000s^3 + 5*10^9s}{s^4 + 5*10^6*s^3 + 2.000015*10^{12}*s^2 + 3.5*10^{13}*s + 5*10^{13}}$$ f = tf([1000 0 5*10^9 0],[1 5*10^6 2.000015*10^12 3.5*10^13 5*10^13]) grid on bode(f) ### Magnitude Graph Bode magnitude plots are dB which is both a measure of power and voltage and current simultaneously. The vertical dB axis is not an approximation or relative to anything. The vertical axis is an accurate number. The horizontal, dependent axis could be radians/sec or Hz. ### Phase Graph The Bode Phase Plot is a graph where the radial frequency is plotted along the X axis, and phase shift of the circuit *at that frequency* is plotted on the Y-axis. Axis could be in radians or degrees, frequency could be in radians per second or Hz. ## Poles and Zeros A transfer function has 7 features that can be realized in circuits. Before looking at these features, the terms pole, zero and origin need to be defined. Start with this definition of a transfer function: $$H(j\omega) = \frac{Z(j\omega)}{P(j\omega)}$$ - Zeros are roots in the numerator. - Poles are roots in the denominator. - The origin is where s = jω = 0 (no real part in a Bode analysis). When the frequency is zero, the input is DC. This is where after a long time caps open and inductors short. The 7 possible features in a transfer function are: - A constant - Zeros at the origin (s in the numerator) - Poles at the origin (s in the denominator) - Real Zero (an s+a factor in the numerator) - Real Pole (an S+a factor in the denominator) - Complex conjugate poles - Complex conjugate zeros The bode and bodeplot functions are available in the MatLab Control system toolbox. BodePlotGui does the same thing and is discussed here. BodePlotGui was developed at Swarthmore through an NSF grant. There is a summary of the Swathmore Bode Diagram tutorial. Circuit simulation software can plot bode diagrams also. ## Bode Equation Format let us say that we have a generic transfer function with poles and zeros: $$H(j\omega) = \frac{(\omega_A + j\omega)(\omega_B + j\omega)}{(\omega_C+ j\omega)(\omega_D + j\omega)}$$ Each term, on top and bottom of the equation, is of the form $(\omega_N + j\omega)$. However, we can rearrange our numbers to look like the following: $$\omega_N(1 + \frac{j\omega}{\omega_N})$$ Now, if we do this for every term in the equation, we get the following: $$H_{bode}(j\omega) = \frac{\omega_A \omega_B}{\omega_C \omega_D} \frac{(1 + \frac{j\omega}{\omega_A})(1 + \frac{j\omega}{\omega_B})} {(1 + \frac{j\omega}{\omega_C})(1 + \frac{j\omega}{\omega_D})}$$ This is the format that we are calling \"Bode Equations\", although they are simply another way of writing an ordinary frequency response equation. ## DC Gain The constant term out front: $$\frac{\omega_A \omega_B}{\omega_C \omega_D}$$ is called the \"DC Gain\" of the function. If we set $\omega \to 0$, we can see that everything in the equation cancels out, and the value of H is simply our DC gain. DC then is simply the output when the input\'s frequency is zero. ## Break Frequencies in each term: $$(1 + \frac{j\omega}{\omega_N})$$ the quantity $\omega_N$ is called the \"Break Frequency\". When the radial frequency of the circuit equals a break frequency, that term becomes (1 + 1) = 2. When the radial frequency is much higher than the break frequency, the term becomes much greater than 1. When the radial Frequency is much smaller than the break frequency, the value of that term becomes approximately 1. ### Approximations Bode diagrams are constructed by drawing straight lines (on log paper) that approximations of what are really curves. Here is a more precise definition. The term \"much\" is a synonym for \"At least 10 times\". \"Much Greater\" becomes \"At least 10 times greater\" and \"Much less\" becomes \"At least 10 times less\". We also use the symbol \"\<\<\" to mean \"is much less than\" and \"\>\>\" to mean \"Is much greater than\". Here are some examples: - 1 \<\< 10 - 10 \<\< 1000 - 2 \<\< 20 Right! - 2 \<\< 10 WRONG! For a number of reasons, Electrical Engineers find it appropriate to approximate and round some values very heavily. For instance, manufacturing technology will never create electrical circuits that perfectly conform to mathematical calculations. When we combine this with the \<\< and \>\> operators, we can come to some important conclusions that help us to simplify our work: If A \<\< B: - A + B = B - A - B = -B - A / B = 0 All other mathematical operations need to be performed, but these 3 forms can be approximated away. This point will come important for later work on bode plots. Using our knowledge of the Bode Equation form, the DC gain value, Decibels, and the \"much greater, much less\" inequalities, we can come up with a fast way to approximate a bode magnitude plot. Also, it is important to remember that these gain values are not constants, but rely instead on changing frequency values. Therefore, the gains that we find are all *slopes* of the bode plot. Our slope values all have units of \"decibel per decade\", or \"db/decade\", for short. ## At Zero Radial Frequency At zero radial frequency, the value of the bode plot is simply the DC gain value *in decibels*. Remember, bode plots have a log-10 magnitude Y-axis, so we need to convert our gain to decibels: $$Magnitude = 20\log_{10}(DC Gain)$$ ## At a Break Point We can notice that each given term changes its effect as the radial frequency goes from below the break point, to above the break point. Let\'s show an example: $$(1 + \frac{j\omega}{5})$$ Our breakpoint occurs at 5 radians per second. When our radial frequency is *much less* than the break point, we have the following: $$Gain = (1 + 0) = 1$$ $$Magnitude = 20\log_{10}(1) = 0db/decade$$ When our radial frequency is equal to our break point we have the following: $$Gain = |(1 + j)| = \sqrt{2}$$ $$Magnitude = 20\log_{10}(\sqrt{2}) = 3db/decade$$ And when our radial frequency is much higher (10 times) our break point we get: $$Gain = |(1 + 10 j)| \approx 10$$ $$Magnitude = 20\log_{10}(10) = 20db/decade$$ However, we need to remember that some of our terms are \"Poles\" and some of them are \"Zeros\". ### Zeros Zeros have a positive effect on the magnitude plot. The contributions of a zero are all positive: Radial Frequency \<\< Break Point : 0db/decade gain.\ Radial Frequency = Break Point : 3db/decade gain.\ Radial Frequency \>\> Break Point : 20db/decade gain. ### Poles Poles have a negative effect on the magnitude plot. The contributions of the poles are as follows: Radial Frequency \<\< Break Point : 0db/decade gain.\ Radial Frequency = Break Point : -3db/decade gain.\ Radial Frequency \>\> Break Point : -20db/decade gain. ## Conclusions To draw a bode plot effectively, follow these simple steps: 1. Put the frequency response equation into bode equation form. 2. identify the DC gain value, and mark this as a horizontal line coming in from the far left (where the radial frequency conceptually is zero). 3. At every \"zero\" break point, increase the slope of the line upwards by 20db/decade. 4. At every \"pole\" break point, decrease the slope of the line downwards by 20db/decade. 5. at every breakpoint, note that the \"actual value\" is 3db off from the value graphed. And then you are done!
# Circuit Theory/Filters !Low pass filter !High pass filter !Band Pass filter !Band Stop filter !Comb filter Some terms used to describe and classify linear filters: ## Frequency Response - - Low-pass filter -- low frequencies are passed, high frequencies are attenuated. - High-pass filter -- high frequencies are passed, low frequencies are attenuated. - Band-pass filter -- only frequencies in a frequency band are passed. - Band-stop filter or band-reject filter -- only frequencies in a frequency band are attenuated. - Notch filter -- rejects just one specific frequency - an extreme band-stop filter. - Comb filter -- has multiple regularly spaced narrow passbands giving the bandform the appearance of a comb. - All-pass filter -- all frequencies are passed, but the phase of the output is modified. ```{=html} <!-- --> ``` - Cutoff frequency is the frequency beyond which the filter will not pass signals. It is usually measured at a specific attenuation such as 3dB. - Roll-off is the rate at which attenuation increases beyond the cut-off frequency. - Transition band, the (usually narrow) band of frequencies between a passband and stopband. - Ripple#Frequency_domain "wikilink") is the variation of the filter\'s insertion loss in the passband. - The order of a filter is the degree of the approximating polynomial and in passive filters corresponds to the number of elements required to build it. Increasing order increases roll-off and brings the filter closer to the ideal response.
# Circuit Theory/Active Filters Active filters have op amps or amplifiers in them. They usually don\'t have inductors because they are expensive, heavy and large when compared to capacitors. ## Minimal Filter Transfer Functions Each filter type has a characteristic transfer function: Filter Type Transfer Function ------------- --------------------------------- High Pass $\frac{s^2}{aS^2 + bs + c}$ Low Pass $\frac{1}{aS^2 + bs + c}$ Band Pass $\frac{s}{aS^2 + bs + c}$ Notch $\frac{s^2 + d}{aS^2 + bs + c}$ First the goal is to build a transfer function from the op-amp circuit so that a bode diagram can be plotted. This is a simple matter of substituting s for derivatives in the terminal relations. ## Active Filter Components Rather than draw an example op amp circuit for each of the above filters, it is easier to draw four op amp circuits that are more related to the desired transfer function: +-------------------------+----------------+-------------------------+ | Circuit | Generates | Transfer Function | +=========================+================+=========================+ | ![](Activ | Complex Pole | derivation | | Example90/ "wikilink")\ | | | | $-\frac{R_ | | | | 3}{R_1 + (C_2R_1R_2 + C | | | | _2R_1R_3 + C_2R_2R_3)s | | | | + C_1C_2R_1R_2R_3s^2}$ | +-------------------------+----------------+-------------------------+ | ![](Acti | Zero at Origin | $-sRC$ | | veFilterOriginZero.png) | | | +-------------------------+----------------+-------------------------+ | ![](Ac | Real Pole | $\frac{-\frac{1}{R_ | | tiveFilterRealPole.png) | | 1C}}{s+\frac{1}{R_2C}}$ | +-------------------------+----------------+-------------------------+ | ![](Ac | Real Zero | $-R_ | | tiveFilterRealZero.png) | | 2C(s + \frac{1}{R_1C})$ | +-------------------------+----------------+-------------------------+ Most filter design starts with the desired transfer function. Then the circuit is built. With the above four configurations, any transfer function can be created. Better filters are have stepper slopes and narrower bands in their bode diagrams. This is measured with a factor called Q for quality. This is why there are so many different types of filter designs. ## Under Constrained Design Suppose you wanted this transfer function: $$\frac{s+1}{(s+2)(s+3)(s+4)}$$ Then an active filter could be built like this: <File:ActiveFilterRealZero.png%7Cstage> A\<br \\\>$-R_2C(s + \frac{1}{R_1C})$ <File:ActiveFilterRealPole.png%7Cstage> B\<br \\\>$\frac{-\frac{1}{R_1C}}{s+\frac{1}{R_2C}}$ <File:ActiveFilterRealPole.png%7Cstage> C\<br \\\>$\frac{-\frac{1}{R_1C}}{s+\frac{1}{R_2C}}$ <File:ActiveFilterRealPole.png%7Cstage> D\<br \\\>$\frac{-\frac{1}{R_1C}}{s+\frac{1}{R_2C}}$ Choosing values to match the above transfer function results in a table like this: Input Stage Variables Feedback stage variables ---------------------------- -------------------------- $R_{1_A}C_A = 1$ $R_{2_A}C_A = 1$ $R_{1_B}C_B = \frac{1}{2}$ $R_{2_B}C_B = 1$ $R_{1_C}C_C = \frac{1}{3}$ $R_{2_C}C_C = 1$ $R_{1_D}C_D = \frac{1}{4}$ $R_{2_D}C_D = 1$ There are 12 unknowns and 8 equations. This is called an under constrained problem. It means that one can apply other design rules. For example, capacitors are more expensive than resistors. Buying in bulk is less expensive. So \... choose one value for all the capacitors and then adjust resistor values. Choose C = 1μF Then all the resistors are 1 M&Ohm; accept R~1B~, R~1C~ and R~1D~.
# Circuit Theory/Source Transformations ## Source Transformations Independent current sources can be turned into independent voltage sources, and vice-versa, by methods called \"Source Transformations.\" These transformations are useful for solving circuits. We will explain the two most important source transformations, **Thevenin\'s Source**, and **Norton\'s Source**, and we will explain how to use these conceptual tools for solving circuits. ## Black Boxes A circuit (or any system, for that matter) may be considered a **black box** if we don\'t know what is inside the system. For instance, most people treat their computers like a black box because they don\'t know what is inside the computer (most don\'t even care), all they know is what goes in to the system (keyboard and mouse input), and what comes out of the system (monitor and printer output). Black boxes, by definition, are systems whose internals aren\'t known to an outside observer. The only methods that an outside observer has to examine a black box is to send input into the systems, and gauge the output. ## Thevenin\'s Theorem Let\'s start by drawing a general circuit consisting of a source and a load, as a block diagram: ![](General_Source-Load_Circuit.svg "General_Source-Load_Circuit.svg") Let\'s say that the source is a collection of voltage sources, current sources and resistances, while the load is a collection of resistances only. Both the source and the load can be arbitrarily complex, but we can conceptually say that the source is directly equivalent to a single voltage source and resistance (figure (a) below). -------------------------------------------------------- ------------------------------------------------------------------------------ ![](Thevenin_Equivalent.svg "Thevenin_Equivalent.svg") ![](Thevenin_Equivalent_Under_Test.svg "Thevenin_Equivalent_Under_Test.svg") *(a)* *(b)* -------------------------------------------------------- ------------------------------------------------------------------------------ We can determine the value of the resistance *R~s~* and the voltage source, *v~s~* by attaching an independent source to the output of the circuit, as in figure (b) above. In this case we are using a current source, but a voltage source could also be used. By varying *i* and measuring *v*, both *v~s~* and *R~s~* can be found using the following equation: $$v=v_s+iR_s \,$$ There are two variables, so two values of *i* will be needed. See Example 1 for more details. We can easily see from this that if the current source is set to zero (equivalent to an open circuit), then *v* is equal to the voltage source, *v~s~*. This is also called the open-circuit voltage, *v~oc~*. This is an important concept, because it allows us to model what is inside a unknown (linear) circuit, just by knowing what is coming out of the circuit. This concept is known as **Thévenin\'s Theorem** after French telegraph engineer Léon Charles Thévenin, and the circuit consisting of the voltage source and resistance is called the **Thévenin Equivalent Circuit**. ## Norton\'s Theorem Recall from above that the output voltage, *v*, of a Thévenin equivalent circuit can be expressed as $$v=v_s+iR_s \,$$ Now, let\'s rearrange it for the output current, *i*: $$i=-\frac{v_s}{R_s}+\frac{v}{R_s}$$ This is equivalent to a KCL description of the following circuit. We can call the constant term *v~s~/R~s~* the source current, *i~s~*. ![](Norton_Equivalent_Under_Test.svg "Norton_Equivalent_Under_Test.svg") The equivalent current source and the equivalent resistance can be found with an independent source as before (see Example 2). When the above circuit (the **Norton Equivalent Circuit**, after Bell Labs engineer E.L. Norton) is disconnected from the external load, the current from the source all flows through the resistor, producing the requisite voltage across the terminals, *v~oc~*. Also, if we were to short the two terminals of our circuit, the current would all flow through the wire, and none of it would flow through the resistor (current divider rule). In this way, the circuit would produce the short-circuit current *i~sc~* (which is exactly the same as the source current *i~s~*). ## Circuit Transforms We have just shown turns out that the Thévenin and Norton circuits are just different representations of the same black box circuit, with the same Ohm\'s Law/KCL equations. This means that we cannot distinguish between Thévenin source and a Norton source from outside the black box, and that we can directly equate the two as below: ---------------------------------------------------- ---------- -------------------------------------------------- center $\equiv$ center ---------------------------------------------------- ---------- -------------------------------------------------- We can draw up some rules to convert between the two: - The values of the resistors in each circuit are conceptually identical, and can be called the equivalent resistance, *R~eq~*: $$R_{s_n}=R_{s_t}=R_s=R_{eq}$$ - The value of a Thévenin voltage source is the value of the Norton current source times the equivalent resistance (Ohm\'s law): $$v_s=i_sr\,$$ If these rules are followed, the circuits will behave identically. Using these few rules, we can transform a Norton circuit into a Thévenin circuit, and vice versa. This method is called **source transformation**. See Example 3. ## Open Circuit Voltage and Short Circuit Current The open-circuit voltage, *v~oc~* of a circuit is the voltage across the terminals when the current is zero, and the short-circuit current *i~sc~* is the current when the voltage across the terminals is zero: ---------------------------------------------------------- ------------------------------------------------------------ ![](Open_Circuit_Voltage.svg "Open_Circuit_Voltage.svg") ![](Short_Circuit_Current.svg "Short_Circuit_Current.svg") *The open circuit voltage* *The short circuit current* ---------------------------------------------------------- ------------------------------------------------------------ We can also observe the following: - The value of the Thévenin voltage source is the open-circuit voltage: $$v_s=v_{oc}\,$$ - The value of the Norton current source is the short-circuit current: $$i_s=i_{sc}\,$$ We can say that, generally, $$R_{eq}=\frac{v_{oc}}{i_{sc}}$$ ## Why Transform Circuits? How are Thevenin and Norton transforms useful? : Describe a black box characteristics in a way that can predict its reaction to any load. : Find the current through and voltage across any device by removing the device from the circuit! This can instantly make a complex circuit much simpler to analyze. : Stepwise simplification of a circuit is possible if voltage sources have a series impedance and current sources have a parallel impedance.
# Circuit Theory/Analysis Methods ## Analysis Methods When circuits get large and complicated, it is useful to have various methods for simplifying and analyzing the circuit. There is no perfect formula for solving a circuit. Depending on the type of circuit, there are different methods that can be employed to solve the circuit. Some methods might not work, and some methods may be very difficult in terms of long math problems. Two of the most important methods for solving circuits are **Nodal Analysis**, and **Mesh Current Analysis**. These will be explained below. ## Superposition One of the most important principals in the field of circuit analysis is the principal of **superposition**. It is valid only in linear circuits. What does this mean? In plain English, it means that if we have a circuit with multiple sources, we can \"turn off\" all but one source at a time, and then investigate the circuit with only one source active at a time. We do this with every source, in turn, and then add together the effects of each source to get the total effect. Before we put this principle to use, we must be aware of the underlying mathematics. ### Necessary Conditions Superposition can only be applied to **linear** circuits; that is, all of a circuit\'s sources hold a linear relationship with the circuit\'s responses. Using only a few algebraic rules, we can build a mathematical understanding of superposition. If *f* is taken to be the response, and *a* and *b* are constant, then: $$f(ax_1+bx_2)= f(ax_1) + f(bx_2) \,$$ In terms of a circuit, it clearly explains the concept of superposition; each input can be considered individually and then summed to obtain the output. With just a few more algebraic properties, we can see that superposition cannot be applied to non-linear circuits. In this example, the response *y* is equal to the square of the input x, i.e. y=x^2^. If *a* and *b* are constant, then: $$y=(ax_1+bx_2)^2 \ne (ax_1)^2 + (bx_2)^2 = y_1+y_2\,$$ Note that this is only one of an infinite number of counter-examples\... ### Step by Step Using superposition to find a given output can be broken down into four steps: 1. Isolate a source - Select a source, and set all of the remaining sources to zero. The consequences of \"turning off\" these sources are explained in Open and Closed Circuits. In summary, turning off a voltage source results in a short circuit, and turning off a current source results in an open circuit. (Reasoning - no current can flow through a open circuit and there can be no voltage drop across a short circuit.) 2. Find the output from the isolated source - Once a source has been isolated, the response from the source in question can be found using any of the techniques we\'ve learned thus far. 3. Repeat steps 1 and 2 for each source - Continue to choose a source, set the remaining sources to zero, and find the response. Repeat this procedure until every source has been accounted for. 4. Sum the Outputs - Once the output due to each source has been found, add them together to find the total response. ## Impulse Response An **impulse response** of a circuit can be used to determine the output of the circuit: ![](System_Block.svg "System_Block.svg"){width="400"} The output y is the **convolution** h \* x of the input x and the impulse response: $$y(t) = (h*x)(t) = \int_{-\infty}^{+\infty} h(t-s)x(s)ds$$. If the input, x(t), was an **impulse** ($\delta(t)$), the output y(t) would be equal to h(t). By knowing the impulse response of a circuit, any source can be plugged-in to the circuit, and the output can be calculated by convolution. ## Convolution The **convolution operation** is a very difficult, involved operation that combines two equations into a single resulting equation. Convolution is defined in terms of a definite integral, and as such, solving convolution equations will require knowledge of integral calculus. This wikibook will not require a prior knowledge of integral calculus, and therefore will not go into more depth on this subject then a simple definition, and some light explanation. ### Definition The convolution a \* b of two functions a and b is defined as: $$(a * b)(t) = \int_{-\infty}^\infty a(\tau)b(t - \tau)d\tau$$ The asterisk operator is used to denote convolution. Many computer systems, and people who frequently write mathematics on a computer will often use an asterisk to denote simple multiplication (the asterisk is the multiplication operator in many programming languages), however an important distinction must be made here: **The asterisk operator means convolution.** ### Properties Convolution is commutative, in the sense that $a * b = b * a$. Convolution is also *distributive* over addition, i.e. $a * (b + c) = a * b + a * c$, and *associative*, i.e. $a * (b * c) = (a * b) * c$. ### Systems, and convolution Let us say that we have the following block-diagram system: +----------------------------------+----------------------------------+ | ![](System_Block.svg | - *x(t)* = **system input** | | "System_Block.svg"){width="400"} | - *h(t)* = **impulse | | | response** | | | - *y(t)* = **system output** | +----------------------------------+----------------------------------+ Where x(t) is the input to the circuit, h(t) is the circuit\'s impulse response, and y(t) is the output. Here, we can find the output by convoluting the impulse response with the input to the circuit. Hence we see that the impulse response of a circuit is not just the ratio of the output over the input. In the frequency domain however, component in the output with frequency ω is the product of the input component with the same frequency and the transition function at that frequency. The moral of the story is this: *the output to a circuit is the input convolved with the impulse response.*
# Python Programming/Overview Python is a high-level, structured, open-source programming language that can be used for a wide variety of programming tasks. Python was created by Guido Van Rossum in the early 1990s; its following has grown steadily and interest has increased markedly in the last few years or so. It is named after Monty Python\'s Flying Circus comedy program. Python is used extensively for system administration (many vital components of Linux distributions are written in it); also, it is a great language to teach programming to novices. NASA has used Python for its software systems and has adopted it as the standard scripting language for its Integrated Planning System. Python is also extensively used by Google to implement many components of its Web Crawler and Search Engine & Yahoo! for managing its discussion groups. Python within itself is an interpreted programming language that is automatically compiled into bytecode before execution (the bytecode is then normally saved to disk, just as automatically, so that compilation need not happen again until and unless the source gets changed). It is also a dynamically typed language that includes (but does not require one to use) object-oriented features and constructs. The most unusual aspect of Python is that whitespace is significant; instead of block delimiters (braces → \"{}\" in the C family of languages), indentation is used to indicate where blocks begin and end. For example, the following Python code can be interactively typed at an interpreter prompt, display the famous \"Hello World!\" on the user screen: ``` python >>> print ("Hello World!") Hello World! ``` Another great feature of Python is its availability for all platforms. Python can run on Microsoft Windows, Macintosh and all Linux distributions with ease. This makes the programs very portable, as any program written for one platform can easily be used on another. Python provides a powerful assortment of built-in types (e.g., lists, dictionaries and strings), a number of built-in functions, and a few constructs, mostly statements. For example, loop constructs that can iterate over items in a collection instead of being limited to a simple range of integer values. Python also comes with a powerful standard library, which includes hundreds of modules to provide routines for a wide variety of services including regular expressions and TCP/IP sessions. Python is used and supported by a large Python Community that exists on the Internet. The mailing lists and news groups like the tutor list actively support and help new python programmers. While they discourage doing homework for you, they are quite helpful and are populated by the authors of many of the Python textbooks currently available on the market. *Python 2 vs. Python 3:* Years ago, the Python developers made the decision to come up with a major new version of Python, which became the 3.*x* series of versions. The 3.x versions are *backward-incompatible* with Python 2.*x*: certain old features (like the handling of Unicode strings) were deemed to be too unwieldy or broken to be worth carrying forward. Instead, new, cleaner ways of achieving the same results were added. See also ../Python 2 vs. Python 3/ chapter.
# Python Programming/Getting Python To program in Python, you need a Python interpreter to run your code---we will discuss interpreters later. If it\'s not already installed, or if the version you are using is obsolete, you will need to obtain and install Python using the methods below. The current Python versions are 3.x; versions 2.x are discontinued and no longer maintained. ## Installing Python in Windows Go to the Python Homepage and get the proper version for your platform. Download it, read the instructions and get it installed. To run Python from the command line, you will need to have the python directory in your PATH. You can instruct the Python installer to add Python to the path, but if you do not do that, you can add it manually. The PATH variable can be modified from the Window\'s System control panel. To expand the PATH in Windows 7: 1. Go to Start. 2. Right click on computer. 3. Click on properties. 4. Click on \'Advanced System Settings\' 5. Click on \'Environmental Variables\'. 6. In the system variables select Path and edit it, by appending a \';\' (without quote) and adding \'C:\\python27\'(without quote). If you prefer having a temporary environment, you can create a new command prompt short-cut that automatically executes the following statement: `PATH %PATH%;c:\python27` If you downloaded a different version (such as Python 3.1), change the \"27\" for the version of Python you have (27 is 2.7.x, the current version of Python 2.) ### Cygwin By default, the Cygwin installer for Windows does not include Python in the downloads. However, it can be selected from the list of packages. ## Installing Python on Mac Users on Mac OS X will find that it already ships with Python 2.3 (OS X 10.4 Tiger) or Python 2.6.1 (OS X Snow Leopard), but if you want the more recent version head to Python Download Page follow the instruction on the page and in the installers. As a bonus you will also install the Python IDE. ## Installing Python on Unix environments Python is available as a package for most Linux distributions. In some cases, the distribution CD will contain the python package for installation, while other distributions require downloading the source code and using the compilation scripts. ### Gentoo Linux Gentoo includes Python by default---the package management system *Portage* depends on Python. ### Ubuntu Linux Users of Ubuntu will notice that Python comes installed by default, only it sometimes is not the latest version. To check which version of Python is installed, type ``` bash python -V ``` into the terminal. ### Arch Linux Arch Linux does not come with Python pre-installed by default, but it is easily available for installation through the package manager to pacman. As root (or using sudo if you\'ve installed and configured it), type: ``` bash pacman -S python ``` This will be update package databases and install Python 3. Python 2 can be installed with: ``` bash pacman -S python2 ``` Other versions can be built from source from the Arch User Repository. ### Source code installations Some platforms do not have a version of Python installed, and do not have pre-compiled binaries. In these cases, you will need to download the source code from the official site. Once the download is complete, you will need to unpack the compressed archive into a folder. To build Python, simply run the configure script (requires the Bash shell) and compile using make. ### Other Distributions Python, also referred to as CPython to avoid confusion, is written in the C programming language "wikilink"), and is the official reference implementation. CPython can run on various platforms due to its portability. Apart from CPython there are also other implementations that run on top of a virtual machine. For example, on Java\'s JRE (Java Runtime Environment) or Microsoft\'s .NET CLR (Common Language Runtime). Both can access and use the libraries available on their platform. Specifically, they make use of reflection "wikilink") that allows complete inspection and use of all classes and objects for their very technology. *Python Implementations (Platforms)* Environment Description Get From ------------- ------------------------ ----------------------------------------- Jython Java Version of Python Jython IronPython C# Version of Python IronPython ### Integrated Development Environments (IDE) It\'s common to use a simple text editor for writing Python code, but you may feel the need to upgrade to a more advanced *IDE*. CPython ships with IDLE; however, IDLE is not considered user-friendly.[^1] For Linux, KDevelop and Spyder are popular. For Windows, PyScripter is free, quick to install, and comes included with PortablePython. *Some Integrated Development Environments (IDEs) for Python* Environment Description Get From ------------------------ ----------------------------------------- ---------------------------------------------------- ActivePython Highly flexible, Pythonwin IDE ActivePython Anjuta IDE Linux/Unix Anjuta Eclipse (PyDev plugin) Open-source IDE Eclipse Eric Open-source Linux/Windows IDE. Eric KDevelop Cross-language IDE for KDE KDevelop Ninja-IDE Cross-platform open-source IDE. Nina-IDE PyScripter Free Windows IDE (portable) PyScripter Pythonwin Windows-oriented environment Pythonwin Spyder Free cross-platform IDE (math-oriented) Spyder VisualWx Free GUI Builder VisualWx The Python official wiki has a complete list of IDEs. There are several commercial IDEs such as Komodo, BlackAdder, Code Crusader, Code Forge, and PyCharm. However, for beginners learning to program, purchasing a commercial IDE is unnecessary. ## Trying Python online You can try Python online, thereby avoiding the need to install. The online Python shell at Python\'s official site provides a web Python REPL (read--eval--print loop). ## Keeping Up to Date Python has a very active community and the language itself is evolving continuously. Make sure to check python.org for recent releases and relevant tools. The website is an invaluable asset. Public Python-related mailing lists are hosted at mail.python.org. Two examples of such mailing lists are the **Python-announce-list** to keep up with newly released third party-modules or software for Python and the general discussion list **Python-list**. These lists are mirrored to the Usenet newsgroups **comp.lang.python.announce** & **comp.lang.python**. ## Notes [^1]: The Things I Hate About IDLE That I Wish Someone Would Fix.
# Python Programming/Interactive mode Python has two basic modes: script and interactive. The normal mode is the mode where the scripted and finished `.py` files are run in the Python interpreter. Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory. As new lines are fed into the interpreter, the fed program is evaluated both in part and in whole. Interactive mode is a good way to play around and try variations on syntax. On macOS or linux, open a terminal and simply type \"python\". On Windows, bring up the command prompt and type \"py\", or start an interactive Python session by selecting \"Python (command line)\", \"IDLE\", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files. Python should print something like this: `$ `**`python`**\ `Python 3.0b3 (r30b3:66303, Sep  8 2008, 14:01:02) [MSC v.1500 32 bit (Intel)] on win32`\ `Type "help", "copyright", "credits" or "license" for more information.`\ `>>>` (If Python doesn\'t run, make sure it is installed and your path is set correctly. See Getting Python.) The `>>>` is Python\'s way of telling you that you are in interactive mode. In interactive mode what you type is immediately run. Try typing `1+1` in. Python will respond with `2`. Interactive mode allows you to test out and see what Python will do. If you ever feel the need to play with new Python statements, go into interactive mode and try them out. A sample interactive session: `>>> `**`5`**\ `5`\ `>>> `**`print(5*7)`**\ `35`\ `>>> `**`"hello" * 2`**\ `'hellohello'`\ `>>> `**`"hello".__class__`**\ `<type 'str'>` However, you need to be careful in the interactive environment to avoid confusion. For example, the following is a valid Python script: ``` python if 1: print("True") print("Done") ``` If you try to enter this as written in the interactive environment, you might be surprised by the result: `>>> `**`if 1:`**\ `...   `**`print("True")`**\ `... `**`print("Done")`**\ `  File "``<stdin>`{=html}`", line 3`\ `    print("Done")`\ `        ^`\ `SyntaxError: invalid syntax` What the interpreter is saying is that the indentation of the second print was unexpected. You should have entered a blank line to end the first (i.e., \"if\") statement, before you started writing the next print statement. For example, you should have entered the statements as though they were written: ``` python if 1: print("True") print("Done") ``` Which would have resulted in the following: `>>> `**`if 1:`**\ `...   `**`print("True")`**\ `...`\ `True`\ `>>> `**`print("Done")`**\ `Done`\ `>>>` ### Interactive mode Instead of Python exiting when the program is finished, you can use the -i flag to start an interactive session. This can be **very** useful for debugging and prototyping. `python -i hello.py`
# Python Programming/Self Help This book is useful for learning Python, but there might be a topic that the book does not cover. You might want to search for modules in the standard library, or inspect an unknown object\'s functions, or perhaps you know there is a function that you have to call inside an object but you don\'t know its name. This is where the interactive help comes into play. ## Built-in help overview Built-in interactive help at a glance: ``` python help() # Starts an interactive help help("topics") # Outputs the list of help topics help("OPERATORS") # Shows help on the topic of operators help("len") # Shows help on len function help("re") # Shows help on re module help("re.sub") # Shows help on sub function from re module help(len) # Shows help on the object passed, the len function help([].pop) # Shows help on the pop function of a list dir([]) # Outputs a list of attributes of a list, which includes functions import re help(re) # Shows help on the help module help(re.sub) # Shows help on the sub function of re module help(1) # Shows help on int type help([]) # Shows help on list type help(def) # Fails: def is a keyword that does not refer to an object help("def") # Shows help on function definitions ``` ## Navigating Help To start Python\'s interactive help, type \"help()\" at the prompt. `>>>help()` You will be presented with a greeting and a quick introduction to the help system. For Python 2.6, the prompt will look something like this: `Welcome to Python 2.6! This is the online help utility.`\ \ `If this is your first time using Python, you should definitely check out`\ `the tutorial on the Internet at ``http://docs.python.org/tutorial/``.`\ \ `Enter the name of any module, keyword, or topic to get help on writing`\ `Python programs and using Python modules. To quit this help utility and`\ `return to the interpreter, just type "quit".`\ \ `To get a list of available modules, keywords, or topics, type "modules",`\ `"keywords", or "topics". Each module also comes with a one-line summary`\ `of what it does; to list the modules whose summaries contain a given word`\ `such as "spam", type "modules spam".` Notice also that the prompt will change from \"`>>>`\" (three right angle brackets) to \"help\>\" You can access the different portions of help simply by typing in `modules`, `keywords`, or `topics`. Typing in the name of one of these will print the help page associated with the item in question. To get a list of available modules, keywords, or topics, type \"modules\",\"keywords\", or \"topics\". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as \"spam\", type \"modules spam\". You can exit the help system by typing \"quit\" or by entering a blank line to return to the interpreter. ## Help Parameter You can obtain information on a specific command without entering interactive help. For example, you can obtain help on a given topic simply by adding a string in quotes, such as `help("object")`. You may also obtain help on a given object as well, by passing it as a parameter to the help function. ## External links - help in 2. Built-in Functions, docs.python.org