diff --git a/AUTHORS.rst b/AUTHORS.rst index 9af2ca4..2125442 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -61,6 +61,14 @@ Fixes: - Ozan Çağlayan +- kikocorreo + +- Sergio Oller + +- Robert Gieseke + +- Jonathan J. Helmus + Traductores al español ====================== diff --git a/CHANGES.rst b/CHANGES.rst index e6d54e1..eb6cd2e 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,6 +1,28 @@ + Novedades =========== +Publicación 2013.2 beta (21 August 2013) +------------------------------------- + +* Capítulo Numpy simplificado (Valentin Haenel) + +* Nuevo diseño para el renderizado HTML (Gaël Varoquaux) + +Publicación 2013.1 (10 Feb 2013) +---------------------------- + +* Mejoras en el capítulo avanzado de manipulación de imágenes (Emmanuelle Gouillart) + +* Actualizado el capítulo introductorio al lenguaje (Valentin Haenel) + +* Actualizado el capítulo introductorio numpy (Valentin Haenel) + +* Nuevo capítulo avanzado interfaz con C (Valentin Haenel) + +* Correcciones menores y mejoras en varias partes (Robert Gieseke, Ozan Çağlayan, + Sergio Oller, kikocorreo, Valentin Haenel) + Publicación 2012.3 (26 Nov 2012) ----------------------------- @@ -51,4 +73,3 @@ simplificado (Gaël Varoquaux). Se han añadido capítulos avanzados: Python constructs avanzados (Zbigniew Jędrzejewski-Szmek), Código de depuración (Gaël Varoquaux), optimización de código (Gaël Varoquaux), procesamiento de imagen (Emmanuelle Gouillart), scikit-learn (Fabian Pedregosa). - diff --git a/_static/default.css b/_static/default.css new file mode 100644 index 0000000..64c8c76 --- /dev/null +++ b/_static/default.css @@ -0,0 +1,847 @@ +/** + * Sphinx Doc Design + */ + +body { + font-family: sans-serif; + font-size: 150%; + background-color: #11303d; + color: #000; + margin: 0; + padding: 0; +} + +/* :::: LAYOUT :::: */ + +div.document { + background-color: #1c4e63; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 230px; +} + +div.body { + background-color: white; + padding: 0 20px 30px 20px; +} + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; +} + +div.clearer { + clear: both; +} + +div.footer { + color: #fff; + width: 100%; + padding: 9px 0 9px 0; + text-align: center; + font-size: 75%; +} + +div.footer a { + color: #fff; + text-decoration: underline; +} + +div.related { + background-color: #133f52; + color: #fff; + width: 100%; + height: 30px; + line-height: 30px; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +div.related a { + color: white; +} + +/* ::: TOC :::: */ +div.sphinxsidebar h3 { + font-family: 'Trebuchet MS', sans-serif; + color: white; + font-size: 1.4em; + font-weight: normal; + margin: 0; + padding: 0; +} + +div.sphinxsidebar h3 a { + color: white; +} + +div.sphinxsidebar h4 { + font-family: 'Trebuchet MS', sans-serif; + color: white; + font-size: 1.3em; + font-weight: normal; + margin: 5px 0 0 0; + padding: 0; +} + +div.sphinxsidebar p { + color: white; +} + +div.sphinxsidebar p.topless { + margin: 5px 10px 10px 10px; +} + +div.sphinxsidebar ul { + margin: 10px; + padding: 0; + list-style: none; + color: white; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar a { + color: #98dbcc; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +/* :::: MODULE CLOUD :::: */ +div.modulecloud { + margin: -5px 10px 5px 10px; + padding: 10px; + line-height: 160%; + border: 1px solid #cbe7e5; + background-color: #f2fbfd; +} + +div.modulecloud a { + padding: 0 5px 0 5px; +} + +/* :::: SEARCH :::: */ +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* :::: COMMON FORM STYLES :::: */ + +div.actions { + padding: 5px 10px 5px 10px; + border-top: 1px solid #cbe7e5; + border-bottom: 1px solid #cbe7e5; + background-color: #e0f6f4; +} + +form dl { + color: #333; +} + +form dt { + clear: both; + float: left; + min-width: 110px; + margin-right: 10px; + padding-top: 2px; +} + +input#homepage { + display: none; +} + +div.error { + margin: 5px 20px 0 0; + padding: 5px; + border: 1px solid #d00; + font-weight: bold; +} + +/* :::: INLINE COMMENTS :::: */ + +div.inlinecomments { + position: absolute; + right: 20px; +} + +div.inlinecomments a.bubble { + display: block; + float: right; + background-image: url(style/comment.png); + background-repeat: no-repeat; + width: 25px; + height: 25px; + text-align: center; + padding-top: 3px; + font-size: 0.9em; + line-height: 14px; + font-weight: bold; + color: black; +} + +div.inlinecomments a.bubble span { + display: none; +} + +div.inlinecomments a.emptybubble { + background-image: url(style/nocomment.png); +} + +div.inlinecomments a.bubble:hover { + background-image: url(style/hovercomment.png); + text-decoration: none; + color: #3ca0a4; +} + +div.inlinecomments div.comments { + float: right; + margin: 25px 5px 0 0; + max-width: 50em; + min-width: 30em; + border: 1px solid #2eabb0; + background-color: #f2fbfd; + z-index: 150; +} + +div#comments { + border: 1px solid #2eabb0; + margin-top: 20px; +} + +div#comments div.nocomments { + padding: 10px; + font-weight: bold; +} + +div.inlinecomments div.comments h3, +div#comments h3 { + margin: 0; + padding: 0; + background-color: #2eabb0; + color: white; + border: none; + padding: 3px; +} + +div.inlinecomments div.comments div.actions { + padding: 4px; + margin: 0; + border-top: none; +} + +div#comments div.comment { + margin: 10px; + border: 1px solid #2eabb0; +} + +div.inlinecomments div.comment h4, +div.commentwindow div.comment h4, +div#comments div.comment h4 { + margin: 10px 0 0 0; + background-color: #2eabb0; + color: white; + border: none; + padding: 1px 4px 1px 4px; +} + +div#comments div.comment h4 { + margin: 0; +} + +div#comments div.comment h4 a { + color: #d5f4f4; +} + +div.inlinecomments div.comment div.text, +div.commentwindow div.comment div.text, +div#comments div.comment div.text { + margin: -5px 0 -5px 0; + padding: 0 10px 0 10px; +} + +div.inlinecomments div.comment div.meta, +div.commentwindow div.comment div.meta, +div#comments div.comment div.meta { + text-align: right; + padding: 2px 10px 2px 0; + font-size: 95%; + color: #538893; + border-top: 1px solid #cbe7e5; + background-color: #e0f6f4; +} + +div.commentwindow { + position: absolute; + width: 500px; + border: 1px solid #cbe7e5; + background-color: #f2fbfd; + display: none; + z-index: 130; +} + +div.commentwindow h3 { + margin: 0; + background-color: #2eabb0; + color: white; + border: none; + padding: 5px; + font-size: 1.5em; + cursor: pointer; +} + +div.commentwindow div.actions { + margin: 10px -10px 0 -10px; + padding: 4px 10px 4px 10px; + color: #538893; +} + +div.commentwindow div.actions input { + border: 1px solid #2eabb0; + background-color: white; + color: #135355; + cursor: pointer; +} + +div.commentwindow div.form { + padding: 0 10px 0 10px; +} + +div.commentwindow div.form input, +div.commentwindow div.form textarea { + border: 1px solid #3c9ea2; + background-color: white; + color: black; +} + +div.commentwindow div.error { + margin: 10px 5px 10px 5px; + background-color: #fbe5dc; + display: none; +} + +div.commentwindow div.form textarea { + width: 99%; +} + +div.commentwindow div.preview { + margin: 10px 0 10px 0; + background-color: #70d0d4; + padding: 0 1px 1px 25px; +} + +div.commentwindow div.preview h4 { + margin: 0 0 -5px -20px; + padding: 4px 0 0 4px; + color: white; + font-size: 1.3em; +} + +div.commentwindow div.preview div.comment { + background-color: #f2fbfd; +} + +div.commentwindow div.preview div.comment h4 { + margin: 10px 0 0 0!important; + padding: 1px 4px 1px 4px!important; + font-size: 1.2em; +} + +/* :::: SUGGEST CHANGES :::: */ +div#suggest-changes-box input, div#suggest-changes-box textarea { + border: 1px solid #ccc; + background-color: white; + color: black; +} + +div#suggest-changes-box textarea { + width: 99%; + height: 400px; +} + + +/* :::: PREVIEW :::: */ +div.preview { + background-image: url(style/preview.png); + padding: 0 20px 20px 20px; + margin-bottom: 30px; +} + + +/* :::: INDEX PAGE :::: */ + +table.contentstable { + width: 90%; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* :::: INDEX STYLES :::: */ + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable dl, table.indextable dd { + margin-top: 0; + margin-bottom: 0; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +form.pfform { + margin: 10px 0 20px 0; +} + +/* :::: GLOBAL STYLES :::: */ + +.docwarning { + background-color: #ffe4e4; + padding: 10px; + margin: 0 -20px 0 -20px; + border-bottom: 1px solid #f66; +} + +p.subhead { + font-weight: bold; + margin-top: 20px; +} + +a { + color: #355f7c; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: 'Trebuchet MS', sans-serif; + background-color: #f2f2f2; + font-weight: normal; + color: #20435c; + border-bottom: 1px solid #ccc; + margin: 20px -20px 10px -20px; + padding: 3px 0 3px 10px; +} + +div.body h1 { margin-top: 0; font-size: 200%; } +div.body h2 { font-size: 160%; } +div.body h3 { font-size: 140%; } +div.body h4 { font-size: 120%; } +div.body h5 { font-size: 110%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #c60f0f; + font-size: 0.8em; + padding: 0 4px 0 4px; + text-decoration: none; + visibility: hidden; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink { + visibility: visible; +} + +a.headerlink:hover { + background-color: #c60f0f; + color: white; +} + +div.body p, div.body dd, div.body li { + text-align: justify; + line-height: 130%; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +ul.fakelist { + list-style: none; + margin: 10px 0 10px 20px; + padding: 0; +} + +.field-list ul { + padding-left: 1em; +} + +.first { + margin-top: 0 !important; +} + +/* "Footnotes" heading */ +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +/* "Topics" */ + +div.topic { + background-color: #eee; + border: 1px solid #ccc; + padding: 0 7px 0 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* Admonitions */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +div.admonition dl { + margin-bottom: 0; +} + +div.admonition p { + display: inline; +} + +div.seealso { + background-color: #ffc; + border: 1px solid #ff6; +} + +div.warning { + background-color: #ffe4e4; + border: 1px solid #f66; +} + +div.note { + background-color: #eee; + border: 1px solid #ccc; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +table.docutils { + border: 0; +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 0; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.field-list td, table.field-list th { + border: 0 !important; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +dl { + margin-bottom: 15px; + clear: both; +} + +dd p { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +.refcount { + color: #060; +} + +dt:target, +.highlight { + background-color: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +th { + text-align: left; + padding-right: 5px; +} + +pre { + padding: 5px; + background-color: #efc; + color: #333; + border: 1px solid #ac9; + border-left: none; + border-right: none; + overflow: auto; + font-size: 1.2em; +} + +td.linenos pre { + padding: 5px 0px; + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + margin-left: 0.5em; +} + +table.highlighttable td { + padding: 0 0.5em 0 0.5em; +} + +tt { + background-color: #ecf0f3; + padding: 0 1px 0 1px; + font-size: 0.95em; +} + +tt.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +tt.descclassname { + background-color: transparent; +} + +tt.xref, a tt { + background-color: transparent; + font-weight: bold; +} + +.footnote:target { background-color: #ffa } + +h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt { + background-color: transparent; +} + +.optional { + font-size: 1.3em; +} + +.versionmodified { + font-style: italic; +} + +form.comment { + margin: 0; + padding: 10px 30px 10px 30px; + background-color: #eee; +} + +form.comment h3 { + background-color: #326591; + color: white; + margin: -10px -30px 10px -30px; + padding: 5px; + font-size: 1.4em; +} + +form.comment input, +form.comment textarea { + border: 1px solid #ccc; + padding: 2px; + font-family: sans-serif; + font-size: 100%; +} + +form.comment input[type="text"] { + width: 240px; +} + +form.comment textarea { + width: 100%; + height: 200px; + margin-bottom: 10px; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +div.math { + text-align: center; +} + +span.eqno { + float: right; +} + +img.logo { + border: 0; +} + +/* :::: PRINT :::: */ +div.document, +div.documentwrapper, +div.bodywrapper { + margin: 0; + width : 100%; +} + +div.sphinxsidebar, +/*div.related,*/ +div.footer, +div#comments div.new-comment-box, +#top-link { + display: none; diff --git a/_static/my_default.css b/_static/my_default.css new file mode 100644 index 0000000..2302255 --- /dev/null +++ b/_static/my_default.css @@ -0,0 +1,853 @@ +/** + * Sphinx Doc Design + */ + +body { + font-family: sans-serif; + font-size: 100%; + background-color: #11303d; + color: #000; + margin: 0; + padding: 0; +} + +/* :::: LAYOUT :::: */ + +div.document { + background-color: #1c4e63; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 0; +} + +div.body { + background-color: white; + padding: 0 20px 30px 20px; +} + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; + visibility: hidden; + width: 0 +} + +div.sphinxsidebar { + float: left; + width: 0 + margin-left: -100%; + font-size: 90%; + visibility: hidden; +} + +div.clearer { + clear: both; +} + +div.footer { + color: #fff; + width: 100%; + padding: 9px 0 9px 0; + text-align: center; + font-size: 75%; + visibility: hidden; +} + +div.footer a { + color: #fff; + text-decoration: underline; +} + +div.related { + background-color: #133f52; + color: #fff; + width: 100%; + height: 30px; + line-height: 30px; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +div.related a { + color: white; +} + +/* ::: TOC :::: */ +div.sphinxsidebar h3 { + font-family: 'Trebuchet MS', sans-serif; + color: white; + font-size: 1.4em; + font-weight: normal; + margin: 0; + padding: 0; +} + +div.sphinxsidebar h3 a { + color: white; +} + +div.sphinxsidebar h4 { + font-family: 'Trebuchet MS', sans-serif; + color: white; + font-size: 1.3em; + font-weight: normal; + margin: 5px 0 0 0; + padding: 0; +} + +div.sphinxsidebar p { + color: white; +} + +div.sphinxsidebar p.topless { + margin: 5px 10px 10px 10px; +} + +div.sphinxsidebar ul { + margin: 10px; + padding: 0; + list-style: none; + color: white; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar a { + color: #98dbcc; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +/* :::: MODULE CLOUD :::: */ +div.modulecloud { + margin: -5px 10px 5px 10px; + padding: 10px; + line-height: 160%; + border: 1px solid #cbe7e5; + background-color: #f2fbfd; +} + +div.modulecloud a { + padding: 0 5px 0 5px; +} + +/* :::: SEARCH :::: */ +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* :::: COMMON FORM STYLES :::: */ + +div.actions { + padding: 5px 10px 5px 10px; + border-top: 1px solid #cbe7e5; + border-bottom: 1px solid #cbe7e5; + background-color: #e0f6f4; +} + +form dl { + color: #333; +} + +form dt { + clear: both; + float: left; + min-width: 110px; + margin-right: 10px; + padding-top: 2px; +} + +input#homepage { + display: none; +} + +div.error { + margin: 5px 20px 0 0; + padding: 5px; + border: 1px solid #d00; + font-weight: bold; +} + +/* :::: INLINE COMMENTS :::: */ + +div.inlinecomments { + position: absolute; + right: 20px; +} + +div.inlinecomments a.bubble { + display: block; + float: right; + background-image: url(style/comment.png); + background-repeat: no-repeat; + width: 25px; + height: 25px; + text-align: center; + padding-top: 3px; + font-size: 0.9em; + line-height: 14px; + font-weight: bold; + color: black; +} + +div.inlinecomments a.bubble span { + display: none; +} + +div.inlinecomments a.emptybubble { + background-image: url(style/nocomment.png); +} + +div.inlinecomments a.bubble:hover { + background-image: url(style/hovercomment.png); + text-decoration: none; + color: #3ca0a4; +} + +div.inlinecomments div.comments { + float: right; + margin: 25px 5px 0 0; + max-width: 50em; + min-width: 30em; + border: 1px solid #2eabb0; + background-color: #f2fbfd; + z-index: 150; +} + +div#comments { + border: 1px solid #2eabb0; + margin-top: 20px; +} + +div#comments div.nocomments { + padding: 10px; + font-weight: bold; +} + +div.inlinecomments div.comments h3, +div#comments h3 { + margin: 0; + padding: 0; + background-color: #2eabb0; + color: white; + border: none; + padding: 3px; +} + +div.inlinecomments div.comments div.actions { + padding: 4px; + margin: 0; + border-top: none; +} + +div#comments div.comment { + margin: 10px; + border: 1px solid #2eabb0; +} + +div.inlinecomments div.comment h4, +div.commentwindow div.comment h4, +div#comments div.comment h4 { + margin: 10px 0 0 0; + background-color: #2eabb0; + color: white; + border: none; + padding: 1px 4px 1px 4px; +} + +div#comments div.comment h4 { + margin: 0; +} + +div#comments div.comment h4 a { + color: #d5f4f4; +} + +div.inlinecomments div.comment div.text, +div.commentwindow div.comment div.text, +div#comments div.comment div.text { + margin: -5px 0 -5px 0; + padding: 0 10px 0 10px; +} + +div.inlinecomments div.comment div.meta, +div.commentwindow div.comment div.meta, +div#comments div.comment div.meta { + text-align: right; + padding: 2px 10px 2px 0; + font-size: 95%; + color: #538893; + border-top: 1px solid #cbe7e5; + background-color: #e0f6f4; +} + +div.commentwindow { + position: absolute; + width: 500px; + border: 1px solid #cbe7e5; + background-color: #f2fbfd; + display: none; + z-index: 130; +} + +div.commentwindow h3 { + margin: 0; + background-color: #2eabb0; + color: white; + border: none; + padding: 5px; + font-size: 1.5em; + cursor: pointer; +} + +div.commentwindow div.actions { + margin: 10px -10px 0 -10px; + padding: 4px 10px 4px 10px; + color: #538893; +} + +div.commentwindow div.actions input { + border: 1px solid #2eabb0; + background-color: white; + color: #135355; + cursor: pointer; +} + +div.commentwindow div.form { + padding: 0 10px 0 10px; +} + +div.commentwindow div.form input, +div.commentwindow div.form textarea { + border: 1px solid #3c9ea2; + background-color: white; + color: black; +} + +div.commentwindow div.error { + margin: 10px 5px 10px 5px; + background-color: #fbe5dc; + display: none; +} + +div.commentwindow div.form textarea { + width: 99%; +} + +div.commentwindow div.preview { + margin: 10px 0 10px 0; + background-color: #70d0d4; + padding: 0 1px 1px 25px; +} + +div.commentwindow div.preview h4 { + margin: 0 0 -5px -20px; + padding: 4px 0 0 4px; + color: white; + font-size: 1.3em; +} + +div.commentwindow div.preview div.comment { + background-color: #f2fbfd; +} + +div.commentwindow div.preview div.comment h4 { + margin: 10px 0 0 0!important; + padding: 1px 4px 1px 4px!important; + font-size: 1.2em; +} + +/* :::: SUGGEST CHANGES :::: */ +div#suggest-changes-box input, div#suggest-changes-box textarea { + border: 1px solid #ccc; + background-color: white; + color: black; +} + +div#suggest-changes-box textarea { + width: 99%; + height: 400px; +} + + +/* :::: PREVIEW :::: */ +div.preview { + background-image: url(style/preview.png); + padding: 0 20px 20px 20px; + margin-bottom: 30px; +} + + +/* :::: INDEX PAGE :::: */ + +table.contentstable { + width: 90%; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* :::: INDEX STYLES :::: */ + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable dl, table.indextable dd { + margin-top: 0; + margin-bottom: 0; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +form.pfform { + margin: 10px 0 20px 0; +} + +/* :::: GLOBAL STYLES :::: */ + +.docwarning { + background-color: #ffe4e4; + padding: 10px; + margin: 0 -20px 0 -20px; + border-bottom: 1px solid #f66; +} + +p.subhead { + font-weight: bold; + margin-top: 20px; +} + +a { + color: #355f7c; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: 'Trebuchet MS', sans-serif; + background-color: #f2f2f2; + font-weight: normal; + color: #20435c; + border-bottom: 1px solid #ccc; + margin: 20px -20px 10px -20px; + padding: 3px 0 3px 10px; +} + +div.body h1 { margin-top: 0; font-size: 200%; } +div.body h2 { font-size: 160%; } +div.body h3 { font-size: 140%; } +div.body h4 { font-size: 120%; } +div.body h5 { font-size: 110%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #c60f0f; + font-size: 0.8em; + padding: 0 4px 0 4px; + text-decoration: none; + visibility: hidden; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink { + visibility: visible; +} + +a.headerlink:hover { + background-color: #c60f0f; + color: white; +} + +div.body p, div.body dd, div.body li { + text-align: justify; + line-height: 130%; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +ul.fakelist { + list-style: none; + margin: 10px 0 10px 20px; + padding: 0; +} + +.field-list ul { + padding-left: 1em; +} + +.first { + margin-top: 0 !important; +} + +/* "Footnotes" heading */ +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +/* "Topics" */ + +div.topic { + background-color: #eee; + border: 1px solid #ccc; + padding: 0 7px 0 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* Admonitions */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +div.admonition dl { + margin-bottom: 0; +} + +div.admonition p { + display: inline; +} + +div.seealso { + background-color: #ffc; + border: 1px solid #ff6; +} + +div.warning { + background-color: #ffe4e4; + border: 1px solid #f66; +} + +div.note { + background-color: #eee; + border: 1px solid #ccc; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +table.docutils { + border: 0; +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 0; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.field-list td, table.field-list th { + border: 0 !important; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +dl { + margin-bottom: 15px; + clear: both; +} + +dd p { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +.refcount { + color: #060; +} + +dt:target, +.highlight { + background-color: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +th { + text-align: left; + padding-right: 5px; +} + +pre { + padding: 5px; + background-color: #efc; + color: #333; + border: 1px solid #ac9; + border-left: none; + border-right: none; + overflow: auto; +} + +td.linenos pre { + padding: 5px 0px; + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + margin-left: 0.5em; +} + +table.highlighttable td { + padding: 0 0.5em 0 0.5em; +} + +tt { + background-color: #ecf0f3; + padding: 0 1px 0 1px; + font-size: 0.95em; +} + +tt.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +tt.descclassname { + background-color: transparent; +} + +tt.xref, a tt { + background-color: transparent; + font-weight: bold; +} + +.footnote:target { background-color: #ffa } + +h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt { + background-color: transparent; +} + +.optional { + font-size: 1.3em; +} + +.versionmodified { + font-style: italic; +} + +form.comment { + margin: 0; + padding: 10px 30px 10px 30px; + background-color: #eee; +} + +form.comment h3 { + background-color: #326591; + color: white; + margin: -10px -30px 10px -30px; + padding: 5px; + font-size: 1.4em; +} + +form.comment input, +form.comment textarea { + border: 1px solid #ccc; + padding: 2px; + font-family: sans-serif; + font-size: 100%; +} + +form.comment input[type="text"] { + width: 240px; +} + +form.comment textarea { + width: 100%; + height: 200px; + margin-bottom: 10px; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +div.math { + text-align: center; +} + +span.eqno { + float: right; +} + +img.logo { + border: 0; +} + +/* :::: PRINT :::: */ +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0; + width : 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + div#comments div.new-comment-box, + #top-link { + display: none; + } +} diff --git a/_templates/layout.html b/_templates/layout.html new file mode 100644 index 0000000..2f9d117 --- /dev/null +++ b/_templates/layout.html @@ -0,0 +1,80 @@ +{% extends '!layout.html' %} + +{% block relbaritems %} + {{ super() }} + +
  • + + + Collapse to compact view + Collapse document to compact view +
  • +{% endblock %} + +{% block header %} + + {{ super() }} + + + + +{% endblock %} diff --git a/advanced/3d_plotting/examples/viz_volume_structure.png b/advanced/3d_plotting/examples/viz_volume_structure.png deleted file mode 100644 index bb97917..0000000 Binary files a/advanced/3d_plotting/examples/viz_volume_structure.png and /dev/null differ diff --git a/advanced/3d_plotting/index.rst b/advanced/3d_plotting/index.rst deleted file mode 100644 index 1b3b160..0000000 --- a/advanced/3d_plotting/index.rst +++ /dev/null @@ -1,309 +0,0 @@ -.. _mayavi-label: - -======================== -Gráficos 3D con Mayavi -======================== - -.. only:: html - - .. image:: mayavi-logo.png - :align: right - -:autor: Gaël Varoquaux - -.. contents:: Contenidos de los capítulos - :local: - :depth: 3 - - -Mlab: la interfaz de scripting -============================== - -El módulo :mod:`mayavi.mlab` proporciona funciones simples para hacer gráficas -aplicables a arrays numpy. Puedes probar las funciones usando IPython inicializando IPython con la -opción ``--gui=wx``. - -Funciones para gráficos 3D ---------------------------- - -Puntos -...... - -.. image:: examples/points3d.png - :align: right - :scale: 50 - -.. literalinclude:: examples/generate_figures.py - :start-after: ### begin points3d example - :end-before: ### end points3d example - -Líneas -...... - -.. image:: examples/plot3d.png - :align: right - :scale: 50 - -.. literalinclude:: examples/generate_figures.py - :start-after: ### begin plot3d example - :end-before: ### end plot3d example - -Superficies de elevación -........................ - -.. image:: examples/surf.png - :align: right - :scale: 50 - -.. literalinclude:: examples/generate_figures.py - :start-after: ### begin surf example - :end-before: ### end surf example - -Mallas arbitrariamente irregulares -.................................. - -.. image:: examples/mesh.png - :align: right - :scale: 50 - -.. literalinclude:: examples/generate_figures.py - :start-after: ### begin mesh example - :end-before: ### end mesh example - -.. note:: - - Una superficie se encuentra definida por puntos **connectados** formando triángulos o - polígonos. En `mlab.surf` y `mlab.mesh`, el layout de los arrays proporciona de - forma implícita las conexiones y la conectividad. Ver también - `mlab.triangular_mesh`. - -**Nuestros datos suelen ser algo más que puntos y valores: necesitan información de la -conectividad** - -Datos volumétricos -................ - -.. _mayavi-voldata-label: - -.. image:: examples/contour3d.png - :align: right - :scale: 50 - -.. literalinclude:: examples/generate_figures.py - :start-after: ### begin contour3d example - :end-before: ### end contour3d example - -.. image:: examples/viz_volume_structure.png - :align: right - :scale: 50 - -**Esta función funciona con un grid ortogonal regular:** El array de `valores` es un array -3D que proporciona la forma del grid. - -Figuras y decoraciones -------------------------- - -Gestión de figuras -.................. - -.. only:: latex - - Aquí se puede ver una lista de funciones útiles para el control de la figura en uso - - -====================================== ============================================================== -Obtener la figura en uso: `mlab.gcf()` --------------------------------------- -------------------------------------------------------------- -Limpiar la figura en uso: `mlab.clf()` --------------------------------------- -------------------------------------------------------------- -Establecer la figura a usar: `mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5)` --------------------------------------- -------------------------------------------------------------- -Guardar la figura a un fichero imagen: `mlab.savefig('foo.png', size=(300, 300))` --------------------------------------- -------------------------------------------------------------- -Cambiar la vista: `mlab.view(azimuth=45, elevation=54, distance=1.)` -====================================== ============================================================== - -Cambiando las propiedades del gráfico -......................... - -.. only:: latex - - En general, muchas propiedades de los distintos objetos presentes en la figura - podrían cambiarse. Si las visualizaciones son creadas via funciones presentes en el módulo `mlab`, - la forma más sencilla de modificar estas visualizaciones sería modificando los argumentos de las - palabras clave (`keywords`) de cada función usada tal como se describe en la documentación (`docstrings`). - -.. topic:: **Ejemplo de documentación (`docstring`, lo dejamos en inglés puesto que es - como te aparecerá cuando lo veas en el código):** `mlab.mesh` - - Plots a surface using grid-spaced data supplied as 2D arrays. - - **Function signatures**:: - - mesh(x, y, z, ...) - - x, y, z are 2D arrays, all of the same shape, giving the positions of - the vertices of the surface. The connectivity between these points is - implied by the connectivity on the arrays. - - For simple structures (such as orthogonal grids) prefer the surf function, - as it will create more efficient data structures. - - **Keyword arguments:** - - :color: the color of the vtk object. Overides the colormap, - if any, when specified. This is specified as a - triplet of float ranging from 0 to 1, eg (1, 1, - 1) for white. - - :colormap: type of colormap to use. - - :extent: [xmin, xmax, ymin, ymax, zmin, zmax] - Default is the x, y, z arrays extents. Use - this to change the extent of the object - created. - - :figure: Figure to populate. - - :line_width: The with of the lines, if any used. Must be a float. - Default: 2.0 - - :mask: boolean mask array to suppress some data points. - - :mask_points: If supplied, only one out of 'mask_points' data point is - displayed. This option is usefull to reduce the number - of points displayed on large datasets Must be an integer - or None. - - :mode: the mode of the glyphs. Must be '2darrow' or '2dcircle' or - '2dcross' or '2ddash' or '2ddiamond' or '2dhooked_arrow' or - '2dsquare' or '2dthick_arrow' or '2dthick_cross' or - '2dtriangle' or '2dvertex' or 'arrow' or 'cone' or 'cube' or - 'cylinder' or 'point' or 'sphere'. Default: sphere - - :name: the name of the vtk object created. - - :representation: the representation type used for the surface. Must be - 'surface' or 'wireframe' or 'points' or 'mesh' or - 'fancymesh'. Default: surface - - :resolution: The resolution of the glyph created. For spheres, for - instance, this is the number of divisions along theta and - phi. Must be an integer. Default: 8 - - :scalars: optional scalar data. - - :scale_factor: scale factor of the glyphs used to represent - the vertices, in fancy_mesh mode. Must be a float. - Default: 0.05 - - :scale_mode: the scaling mode for the glyphs - ('vector', 'scalar', or 'none'). - - :transparent: make the opacity of the actor depend on the - scalar. - - :tube_radius: radius of the tubes used to represent the - lines, in mesh mode. If None, simple lines are used. - - :tube_sides: number of sides of the tubes used to - represent the lines. Must be an integer. Default: 6 - - :vmax: vmax is used to scale the colormap - If None, the max of the data will be used - - :vmin: vmin is used to scale the colormap - If None, the min of the data will be used - - -Ejemplo: - -.. sourcecode:: ipython - - In [1]: import numpy as np - - In [2]: r, theta = np.mgrid[0:10, -np.pi:np.pi:10j] - - In [3]: x = r*np.cos(theta) - - In [4]: y = r*np.sin(theta) - - In [5]: z = np.sin(r)/r - - In [6]: from enthought.mayavi import mlab - - In [7]: mlab.mesh(x, y, z, colormap='gist_earth', extent=[0, 1, 0, 1, 0, 1]) - Out[7]: - - In [8]: mlab.mesh(x, y, z, extent=[0, 1, 0, 1, 0, 1], - ...: representation='wireframe', line_width=1, color=(0.5, 0.5, 0.5)) - Out[8]: - -.. image:: polar_mesh.png - :align: center - :scale: 70 - -Decoraciones -............ - -.. only:: latex - - Se pueden añadir piezas extra en la figura para mostrar información de interés, - como una barra de colores o un título. - -.. sourcecode:: ipython - - In [9]: mlab.colorbar(Out[7], orientation='vertical') - Out[9]: - - In [10]: mlab.title('Malla polar') - Out[10]: - - In [11]: mlab.outline(Out[7]) - Out[11]: - - In [12]: mlab.axes(Out[7]) - Out[12]: - -.. image:: decorations.png - :align: center - :scale: 80 - -.. Advertencia:: - - **extensión:** Si especificamos la extensión de un objeto gráfico, - `mlab.outline' y `mlab.axes` no tendrán esa extensión por defecto y habría que especificarla. - - - mlab_scripting_interface.rst - interaction.rst - - -Trabajo interactivo -================= - -.. only:: latex - - Probablemente, la manera más rápida y efectiva de crear visualizaciones bonitas con Mayavi sería - interactuando y modificando los distintos ajustes de forma interactiva. - -El "pipeline dialog" ----------------------- - -Pulsa en el botón 'Mayavi' que se encuentra en la figura para poder controlar las propiedades -de los objetos con la ayuda de ventanas de diálogos. - -.. image:: pipeline.png - :align: center - :scale: 80 - -* Establece el fondo de la figura en el nodo de las `Mayavi Scene` -* Establece el mapa de colores en el nodo `Colors and legends` -* Se pueden añadir módulos y/o filtras pulsando en el botón derecho del ratón - -El botón de grabación del script ------------------------------ - -Para descubrir con qué códifo podríamos modificar los cambios realizados de forma interactiva -podemos pulsar sobre el botón rojo cuando vayamos a realizar las modificaciones y se generarán -las correspondientes líneas de código. diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/mandelplot.png b/advanced/advanced_numpy/auto_examples/images/thumb/mandelplot.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/mandelplot.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/myobject_test.png b/advanced/advanced_numpy/auto_examples/images/thumb/myobject_test.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/myobject_test.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/pilbuffer-answer.png b/advanced/advanced_numpy/auto_examples/images/thumb/pilbuffer-answer.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/pilbuffer-answer.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/pilbuffer.png b/advanced/advanced_numpy/auto_examples/images/thumb/pilbuffer.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/pilbuffer.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/setup.png b/advanced/advanced_numpy/auto_examples/images/thumb/setup.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/setup.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/setup_myobject.png b/advanced/advanced_numpy/auto_examples/images/thumb/setup_myobject.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/setup_myobject.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/stride-diagonals-answer.png b/advanced/advanced_numpy/auto_examples/images/thumb/stride-diagonals-answer.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/stride-diagonals-answer.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/stride-diagonals.png b/advanced/advanced_numpy/auto_examples/images/thumb/stride-diagonals.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/stride-diagonals.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/stride-fakedims.png b/advanced/advanced_numpy/auto_examples/images/thumb/stride-fakedims.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/stride-fakedims.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/stride_tricks.png b/advanced/advanced_numpy/auto_examples/images/thumb/stride_tricks.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/stride_tricks.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/view-colors.png b/advanced/advanced_numpy/auto_examples/images/thumb/view-colors.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/view-colors.png differ diff --git a/advanced/advanced_numpy/auto_examples/images/thumb/wavreader.png b/advanced/advanced_numpy/auto_examples/images/thumb/wavreader.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/advanced_numpy/auto_examples/images/thumb/wavreader.png differ diff --git a/advanced/advanced_numpy/auto_examples/index.rst b/advanced/advanced_numpy/auto_examples/index.rst new file mode 100644 index 0000000..2c70700 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/index.rst @@ -0,0 +1,91 @@ + +.. raw:: html + + + +Examples +======== + +.. _examples-index: +.. figure:: ./images/thumb/mandelplot.png + :target: ./mandelplot.html + + :ref:`example_mandelplot.py` + +.. figure:: ./images/thumb/myobject_test.png + :target: ./myobject_test.html + + :ref:`example_myobject_test.py` + +.. figure:: ./images/thumb/pilbuffer-answer.png + :target: ./pilbuffer-answer.html + + :ref:`example_pilbuffer-answer.py` + +.. figure:: ./images/thumb/pilbuffer.png + :target: ./pilbuffer.html + + :ref:`example_pilbuffer.py` + +.. figure:: ./images/thumb/setup.png + :target: ./setup.html + + :ref:`example_setup.py` + +.. figure:: ./images/thumb/setup_myobject.png + :target: ./setup_myobject.html + + :ref:`example_setup_myobject.py` + +.. figure:: ./images/thumb/stride-diagonals-answer.png + :target: ./stride-diagonals-answer.html + + :ref:`example_stride-diagonals-answer.py` + +.. figure:: ./images/thumb/stride-diagonals.png + :target: ./stride-diagonals.html + + :ref:`example_stride-diagonals.py` + +.. figure:: ./images/thumb/stride-fakedims.png + :target: ./stride-fakedims.html + + :ref:`example_stride-fakedims.py` + +.. figure:: ./images/thumb/stride_tricks.png + :target: ./stride_tricks.html + + :ref:`example_stride_tricks.py` + +.. figure:: ./images/thumb/view-colors.png + :target: ./view-colors.html + + :ref:`example_view-colors.py` + +.. figure:: ./images/thumb/wavreader.png + :target: ./wavreader.html + + :ref:`example_wavreader.py` + + +.. raw:: html + +
    + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/mandelplot.py b/advanced/advanced_numpy/auto_examples/mandelplot.py new file mode 100644 index 0000000..8268833 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/mandelplot.py @@ -0,0 +1,11 @@ +import numpy as np +import mandel +x = np.linspace(-1.7, 0.6, 1000) +y = np.linspace(-1.4, 1.4, 1000) +c = x[None,:] + 1j*y[:,None] +z = mandel.mandel(c, c) + +import matplotlib.pyplot as plt +plt.imshow(abs(z)**2 < 1000, extent=[-1.7, 0.6, -1.4, 1.4]) +plt.gray() +plt.show() diff --git a/advanced/advanced_numpy/auto_examples/mandelplot.rst b/advanced/advanced_numpy/auto_examples/mandelplot.rst new file mode 100644 index 0000000..bd38604 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/mandelplot.rst @@ -0,0 +1,11 @@ + + +.. _example_mandelplot.py: + + + +**Python source code:** :download:`mandelplot.py ` + +.. literalinclude:: mandelplot.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/myobject_test.py b/advanced/advanced_numpy/auto_examples/myobject_test.py new file mode 100644 index 0000000..b005f15 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/myobject_test.py @@ -0,0 +1,31 @@ +# +# Compile myobject.c first with +# +# python3 setup_myobject.py build_ext -i +# +# If you are interested, play a bit with changing things in ``myobject.c`` +# + +import myobject + +obj = myobject.MyObject() +view = memoryview(obj) + +print("shape", view.shape) +print("strides", view.strides) +print("format", view.format) + + +# +# If you also have Numpy for Python 3 ... +# + +import numpy as np + +x = np.asarray(obj) +print(x) + +# this prints +# +# [[1 2] +# [3 4]] diff --git a/advanced/advanced_numpy/auto_examples/myobject_test.rst b/advanced/advanced_numpy/auto_examples/myobject_test.rst new file mode 100644 index 0000000..6aa6000 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/myobject_test.rst @@ -0,0 +1,11 @@ + + +.. _example_myobject_test.py: + + + +**Python source code:** :download:`myobject_test.py ` + +.. literalinclude:: myobject_test.py + :lines: 10- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/pilbuffer-answer.py b/advanced/advanced_numpy/auto_examples/pilbuffer-answer.py new file mode 100644 index 0000000..1581ace --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/pilbuffer-answer.py @@ -0,0 +1,24 @@ +import numpy as np +import Image + +# Let's make a sample image, RGBA format + +x = np.zeros((200, 200, 4), dtype=np.int8) + +x[:,:,0] = 254 # red +x[:,:,3] = 255 # opaque + +data = x.view(np.int32) # Check that you understand why this is OK! + +img = Image.frombuffer("RGBA", (200, 200), data) +img.save('test.png') + +# +# Modify the original data, and save again. +# +# It turns out that PIL, which knows next to nothing about Numpy, +# happily shares the same data. +# + +x[:,:,1] = 254 +img.save('test2.png') diff --git a/advanced/advanced_numpy/auto_examples/pilbuffer-answer.rst b/advanced/advanced_numpy/auto_examples/pilbuffer-answer.rst new file mode 100644 index 0000000..5f5dc27 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/pilbuffer-answer.rst @@ -0,0 +1,11 @@ + + +.. _example_pilbuffer-answer.py: + + + +**Python source code:** :download:`pilbuffer-answer.py ` + +.. literalinclude:: pilbuffer-answer.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/pilbuffer.py b/advanced/advanced_numpy/auto_examples/pilbuffer.py new file mode 100644 index 0000000..19f22c9 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/pilbuffer.py @@ -0,0 +1,22 @@ +import numpy as np +import Image + +# Let's make a sample image, RGBA format + +x = np.zeros((200, 200, 4), dtype=np.int8) + +TODO: fill `x` with fully opaque red [255, 0, 0, 255] + +TODO: RGBA images consist of 32-bit integers whose bytes are [RR,GG,BB,AA] + How to get that from ``x``? + +data = ... + +img = Image.frombuffer("RGBA", (200, 200), data) +img.save('test.png') + +# +# Mini-exercise +# +# 1. Now, modify ``x`` and img.save() again. What happens? +# diff --git a/advanced/advanced_numpy/auto_examples/pilbuffer.rst b/advanced/advanced_numpy/auto_examples/pilbuffer.rst new file mode 100644 index 0000000..2f98e13 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/pilbuffer.rst @@ -0,0 +1,11 @@ + + +.. _example_pilbuffer.py: + + + +**Python source code:** :download:`pilbuffer.py ` + +.. literalinclude:: pilbuffer.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/setup.py b/advanced/advanced_numpy/auto_examples/setup.py new file mode 100644 index 0000000..de0c0b2 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/setup.py @@ -0,0 +1,22 @@ +import os +import sys +from os.path import join +from distutils.sysconfig import get_python_inc +import numpy +from numpy.distutils.misc_util import get_numpy_include_dirs + +def configuration(parent_package='',top_path=None): + from numpy.distutils.misc_util import Configuration + + for filename in ['mandel.so']: + # make sure we don't have stale files lying around + if os.path.isfile(filename): + os.unlink(filename) + + config = Configuration('', parent_package, top_path) + config.add_extension('mandel', sources=['mandel.c']) + return config + +if __name__ == '__main__': + from numpy.distutils.core import setup + setup(**configuration(top_path='').todict()) diff --git a/advanced/advanced_numpy/auto_examples/setup.rst b/advanced/advanced_numpy/auto_examples/setup.rst new file mode 100644 index 0000000..91f4e06 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/setup.rst @@ -0,0 +1,11 @@ + + +.. _example_setup.py: + + + +**Python source code:** :download:`setup.py ` + +.. literalinclude:: setup.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/setup_myobject.py b/advanced/advanced_numpy/auto_examples/setup_myobject.py new file mode 100644 index 0000000..9347fe4 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/setup_myobject.py @@ -0,0 +1,5 @@ +from distutils.core import setup, Extension +setup(name='myobject', + version='1.0', + ext_modules=[Extension('myobject', ['myobject.c'])], +) diff --git a/advanced/advanced_numpy/auto_examples/setup_myobject.rst b/advanced/advanced_numpy/auto_examples/setup_myobject.rst new file mode 100644 index 0000000..370f068 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/setup_myobject.rst @@ -0,0 +1,11 @@ + + +.. _example_setup_myobject.py: + + + +**Python source code:** :download:`setup_myobject.py ` + +.. literalinclude:: setup_myobject.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/stride-diagonals-answer.py b/advanced/advanced_numpy/auto_examples/stride-diagonals-answer.py new file mode 100644 index 0000000..380f78c --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/stride-diagonals-answer.py @@ -0,0 +1,55 @@ +import numpy as np +from numpy.lib.stride_tricks import as_strided + +# +# Part 1 +# + +x = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], dtype=np.int32) + +x_diag = as_strided(x, shape=(3,), strides=((3+1)*x.itemsize,)) +x_supdiag = as_strided(x[0,1:], shape=(2,), strides=((3+1)*x.itemsize,)) +x_subdiag = as_strided(x[1:,0], shape=(2,), strides=((3+1)*x.itemsize,)) + +print x_diag +print x_supdiag +print x_subdiag + +# +# Mini-exercise: (assume C memory order) +# +# 0. How to pick diagonal entries of the matrix +# +# 1. How to pick the super-diagonal entries [2, 6] +# +# 2. The sub-diagonal entries [4, 8] +# +# 99. Can you generalize this for any stride and shape combinations +# in the initial array? +# +# If you can, tell me, and maybe numpy.trace can be made faster :) +# + + +# +# Part 2 +# + +# Compute the tensor trace + +x = np.arange(5*5*5*5).reshape(5,5,5,5) + +s = 0 +for i in xrange(5): + for j in xrange(5): + s += x[j,i,j,i] + +# by striding and using .sum() + +y = as_strided(x, shape=(5, 5), strides=((5*5*5+5)*x.itemsize, + (5*5+1)*x.itemsize)) +s2 = y.sum() + +assert s == s2 diff --git a/advanced/advanced_numpy/auto_examples/stride-diagonals-answer.rst b/advanced/advanced_numpy/auto_examples/stride-diagonals-answer.rst new file mode 100644 index 0000000..a8bb498 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/stride-diagonals-answer.rst @@ -0,0 +1,11 @@ + + +.. _example_stride-diagonals-answer.py: + + + +**Python source code:** :download:`stride-diagonals-answer.py ` + +.. literalinclude:: stride-diagonals-answer.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/stride-diagonals.py b/advanced/advanced_numpy/auto_examples/stride-diagonals.py new file mode 100644 index 0000000..aca26ac --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/stride-diagonals.py @@ -0,0 +1,50 @@ +import numpy as np +from numpy.lib.stride_tricks import as_strided + +# +# Part 1 +# + +x = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]], dtype=np.int32) + +x_diag = as_strided(x, shape=(3,), strides=(TODO,)) +x_supdiag = TODO +x_subdiag = TODO + +# +# Mini-exercise: (assume C memory order) +# +# 0. How to pick diagonal entries of the matrix +# +# 1. How to pick the super-diagonal entries [2, 6] +# +# 2. The sub-diagonal entries [4, 8] +# +# 99. Can you generalize this for any stride and shape combinations +# in the initial array? +# +# If you can, tell me, and maybe numpy.trace can be made faster :) +# + + +# +# Part 2 +# + +# Compute the tensor trace + +x = np.arange(5*5*5*5).reshape(5,5,5,5) + +s = 0 +for i in xrange(5): + for j in xrange(5): + s += x[j,i,j,i] + +# by striding and using .sum() + +y = as_strided(x, shape=(5, 5), strides=(TODO, TODO)) +s2 = ... + +assert s == s2 diff --git a/advanced/advanced_numpy/auto_examples/stride-diagonals.rst b/advanced/advanced_numpy/auto_examples/stride-diagonals.rst new file mode 100644 index 0000000..7824b25 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/stride-diagonals.rst @@ -0,0 +1,11 @@ + + +.. _example_stride-diagonals.py: + + + +**Python source code:** :download:`stride-diagonals.py ` + +.. literalinclude:: stride-diagonals.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/stride-fakedims.py b/advanced/advanced_numpy/auto_examples/stride-fakedims.py new file mode 100644 index 0000000..8973e8b --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/stride-fakedims.py @@ -0,0 +1,14 @@ +import numpy as np +from numpy.lib.stride_tricks import as_strided + +x = np.array([1, 2, 3, 4], dtype=np.int8) + +# +# Mini-exercise: +# +# 1. How to create a new array that shares the data, but looks like +# +# array([[1, 2, 3, 4], +# [1, 2, 3, 4], +# [1, 2, 3, 4]], dtype=int8) +# diff --git a/advanced/advanced_numpy/auto_examples/stride-fakedims.rst b/advanced/advanced_numpy/auto_examples/stride-fakedims.rst new file mode 100644 index 0000000..9c0fb27 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/stride-fakedims.rst @@ -0,0 +1,11 @@ + + +.. _example_stride-fakedims.py: + + + +**Python source code:** :download:`stride-fakedims.py ` + +.. literalinclude:: stride-fakedims.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/stride_tricks.py b/advanced/advanced_numpy/auto_examples/stride_tricks.py new file mode 100644 index 0000000..940b0c1 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/stride_tricks.py @@ -0,0 +1,125 @@ +""" +Utilities that manipulate strides to achieve desirable effects. + + + + + + + + + + + + + + +""" +import numpy as np + +__all__ = ['broadcast_arrays'] + +class DummyArray(object): + """ Dummy object that just exists to hang __array_interface__ dictionaries + and possibly keep alive a reference to a base array. + """ + def __init__(self, interface, base=None): + self.__array_interface__ = interface + self.base = base + +def as_strided(x, shape=None, strides=None): + """ Make an ndarray from the given array with the given shape and strides. + """ + interface = dict(x.__array_interface__) + if shape is not None: + interface['shape'] = tuple(shape) + if strides is not None: + interface['strides'] = tuple(strides) + return np.asarray(DummyArray(interface, base=x)) + +def broadcast_arrays(*args): + """ + Broadcast any number of arrays against each other. + + Parameters + ---------- + `*args` : arrays + The arrays to broadcast. + + Returns + ------- + broadcasted : list of arrays + These arrays are views on the original arrays. They are typically not + contiguous. Furthermore, more than one element of a broadcasted array + may refer to a single memory location. If you need to write to the + arrays, make copies first. + + Examples + -------- + >>> x = np.array([[1,2,3]]) + >>> y = np.array([[1],[2],[3]]) + >>> np.broadcast_arrays(x, y) + [array([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]), array([[1, 1, 1], + [2, 2, 2], + [3, 3, 3]])] + + Here is a useful idiom for getting contiguous copies instead of + non-contiguous views. + + >>> map(np.array, np.broadcast_arrays(x, y)) + [array([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]), array([[1, 1, 1], + [2, 2, 2], + [3, 3, 3]])] + + """ + args = map(np.asarray, args) + shapes = [x.shape for x in args] + if len(set(shapes)) == 1: + # Common case where nothing needs to be broadcasted. + return args + shapes = [list(s) for s in shapes] + strides = [list(x.strides) for x in args] + nds = [len(s) for s in shapes] + biggest = max(nds) + # Go through each array and prepend dimensions of length 1 to each of the + # shapes in order to make the number of dimensions equal. + for i in range(len(args)): + diff = biggest - nds[i] + if diff > 0: + shapes[i] = [1] * diff + shapes[i] + strides[i] = [0] * diff + strides[i] + # Chech each dimension for compatibility. A dimension length of 1 is + # accepted as compatible with any other length. + common_shape = [] + for axis in range(biggest): + lengths = [s[axis] for s in shapes] + unique = set(lengths + [1]) + if len(unique) > 2: + # There must be at least two non-1 lengths for this axis. + raise ValueError("shape mismatch: two or more arrays have " + "incompatible dimensions on axis %r." % (axis,)) + elif len(unique) == 2: + # There is exactly one non-1 length. The common shape will take this + # value. + unique.remove(1) + new_length = unique.pop() + common_shape.append(new_length) + # For each array, if this axis is being broadcasted from a length of + # 1, then set its stride to 0 so that it repeats its data. + for i in range(len(args)): + if shapes[i][axis] == 1: + shapes[i][axis] = new_length + strides[i][axis] = 0 + else: + # Every array has a length of 1 on this axis. Strides can be left + # alone as nothing is broadcasted. + common_shape.append(1) + + # Construct the new arrays. + broadcasted = [as_strided(x, shape=sh, strides=st) for (x,sh,st) in + zip(args, shapes, strides)] + return broadcasted diff --git a/advanced/advanced_numpy/auto_examples/stride_tricks.rst b/advanced/advanced_numpy/auto_examples/stride_tricks.rst new file mode 100644 index 0000000..30b4d30 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/stride_tricks.rst @@ -0,0 +1,27 @@ + + +.. _example_stride_tricks.py: + + +Utilities that manipulate strides to achieve desirable effects. + + + + + + + + + + + + + + + + +**Python source code:** :download:`stride_tricks.py ` + +.. literalinclude:: stride_tricks.py + :lines: 18- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/view-colors.py b/advanced/advanced_numpy/auto_examples/view-colors.py new file mode 100644 index 0000000..99a14cd --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/view-colors.py @@ -0,0 +1,15 @@ +x = np.zeros((10, 10, 4), dtype=np.int8) +x[:,:,0] = 1 +x[:,:,1] = 2 +x[:,:,2] = 3 +x[:,:,3] = 4 + +# How to make a (10, 10) structured array with fields 'r', 'g', 'b', 'a', +# without copying? + +y = ... + +assert (y['r'] == 1).all() +assert (y['g'] == 2).all() +assert (y['b'] == 3).all() +assert (y['a'] == 4).all() diff --git a/advanced/advanced_numpy/auto_examples/view-colors.rst b/advanced/advanced_numpy/auto_examples/view-colors.rst new file mode 100644 index 0000000..c33cd62 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/view-colors.rst @@ -0,0 +1,11 @@ + + +.. _example_view-colors.py: + + + +**Python source code:** :download:`view-colors.py ` + +.. literalinclude:: view-colors.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/auto_examples/wavreader.py b/advanced/advanced_numpy/auto_examples/wavreader.py new file mode 100644 index 0000000..a459be6 --- /dev/null +++ b/advanced/advanced_numpy/auto_examples/wavreader.py @@ -0,0 +1,42 @@ +import sys +import numpy as np + +wav_header_dtype = np.dtype([ + ("chunk_id", (str, 4)), # flexible-sized scalar type, item size 4 + ("chunk_size", "` + +.. literalinclude:: wavreader.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/advanced_numpy/index.rst b/advanced/advanced_numpy/index.rst index c2fd053..ff907de 100644 --- a/advanced/advanced_numpy/index.rst +++ b/advanced/advanced_numpy/index.rst @@ -3,14 +3,13 @@ >>> np.random.seed(0) >>> from matplotlib import pyplot as plt - .. _advanced_numpy: ============== Numpy avanzado ============== -:autor: Pauli Virtanen +:Autor: Pauli Virtanen Numpy se encuentra en la base del montón de herramientas científicas de Python. Su propósito es simple: implementar operaciones eficientes sobre muchos @@ -36,15 +35,17 @@ Este tutorial pretende cubrir: .. topic:: Preerequisitos - * Numpy (>= 1.2; preferiblemente versiones más nuevas...) - * Cython (>= 0.12, para el ejemplo con Ufunc) - * PIL (usado en un par de ejemplos) + * Numpy (>= 1.2; preferiblemente versiones más nuevas...) + * Cython (>= 0.12, para el ejemplo con Ufunc) + * PIL (usado en un par de ejemplos) + +En esta sección numpy será importado de la siguiente forma -En esta sección numpy será importado de la siguiente forma:: +.. code-block:: python - >>> import numpy as np + >>> import numpy as np -.. contents:: Chapter contents +.. contents:: Contenido :local: :depth: 2 diff --git a/advanced/advanced_python/index.rst b/advanced/advanced_python/index.rst index f0a3f9f..1fe981d 100644 --- a/advanced/advanced_python/index.rst +++ b/advanced/advanced_python/index.rst @@ -5,7 +5,7 @@ ============================================================ Expresiones avanzadas en python (Advanced Python Constructs) ============================================================ -:autor: Zbigniew Jędrzejewski-Szmek +:Autor: Zbigniew Jędrzejewski-Szmek En este capítulo se tratan algunas características de Python que se podrían considerar como avanzadas --- en el sentido en que no todos los lenguajes @@ -36,8 +36,6 @@ sirven para resolver problemas reales y de que su uso es lo más simple posible. :local: :depth: 4 - - Iteradores, expresiones generadoras y generadores =============================================== diff --git a/advanced/image_processing/auto_examples/image_source_canny.py b/advanced/image_processing/auto_examples/image_source_canny.py new file mode 100644 index 0000000..49db734 --- /dev/null +++ b/advanced/image_processing/auto_examples/image_source_canny.py @@ -0,0 +1,225 @@ +'''canny.py - Canny Edge detector + +Reference: Canny, J., A Computational Approach To Edge Detection, IEEE Trans. + Pattern Analysis and Machine Intelligence, 8:679-714, 1986 + +Originally part of CellProfiler, code licensed under both GPL and BSD licenses. +Website: http://www.cellprofiler.org +Copyright (c) 2003-2009 Massachusetts Institute of Technology +Copyright (c) 2009-2011 Broad Institute +All rights reserved. +Original author: Lee Kamentsky + +''' + +import numpy as np +import scipy.ndimage as ndi +from scipy.ndimage import (gaussian_filter, convolve, + generate_binary_structure, binary_erosion, label) + + +def smooth_with_function_and_mask(image, function, mask): + """Smooth an image with a linear function, ignoring masked pixels + + Parameters + ---------- + image : array + The image to smooth + + function : callable + A function that takes an image and returns a smoothed image + + mask : array + Mask with 1's for significant pixels, 0 for masked pixels + + Notes + ------ + This function calculates the fractional contribution of masked pixels + by applying the function to the mask (which gets you the fraction of + the pixel data that's due to significant points). We then mask the image + and apply the function. The resulting values will be lower by the bleed-over + fraction, so you can recalibrate by dividing by the function on the mask + to recover the effect of smoothing from just the significant pixels. + """ + not_mask = np.logical_not(mask) + bleed_over = function(mask.astype(float)) + masked_image = np.zeros(image.shape, image.dtype) + masked_image[mask] = image[mask] + smoothed_image = function(masked_image) + output_image = smoothed_image / (bleed_over + np.finfo(float).eps) + return output_image + + +def canny(image, sigma, low_threshold, high_threshold, mask=None): + '''Edge filter an image using the Canny algorithm. + + Parameters + ----------- + image : array_like, dtype=float + The greyscale input image to detect edges on; should be normalized to 0.0 + to 1.0. + + sigma : float + The standard deviation of the Gaussian filter + + low_threshold : float + The lower bound for hysterisis thresholding (linking edges) + + high_threshold : float + The upper bound for hysterisis thresholding (linking edges) + + mask : array, dtype=bool, optional + An optional mask to limit the application of Canny to a certain area. + + Returns + ------- + output : array (image) + The binary edge map. + + References + ----------- + Canny, J., A Computational Approach To Edge Detection, IEEE Trans. + Pattern Analysis and Machine Intelligence, 8:679-714, 1986 + + William Green's Canny tutorial + http://www.pages.drexel.edu/~weg22/can_tut.html + ''' + # + # The steps involved: + # + # * Smooth using the Gaussian with sigma above. + # + # * Apply the horizontal and vertical Sobel operators to get the gradients + # within the image. The edge strength is the sum of the magnitudes + # of the gradients in each direction. + # + # * Find the normal to the edge at each point using the arctangent of the + # ratio of the Y sobel over the X sobel - pragmatically, we can + # look at the signs of X and Y and the relative magnitude of X vs Y + # to sort the points into 4 categories: horizontal, vertical, + # diagonal and antidiagonal. + # + # * Look in the normal and reverse directions to see if the values + # in either of those directions are greater than the point in question. + # Use interpolation to get a mix of points instead of picking the one + # that's the closest to the normal. + # + # * Label all points above the high threshold as edges. + # * Recursively label any point above the low threshold that is 8-connected + # to a labeled point as an edge. + # + # Regarding masks, any point touching a masked point will have a gradient + # that is "infected" by the masked point, so it's enough to erode the + # mask by one and then mask the output. We also mask out the border points + # because who knows what lies beyond the edge of the image? + # + if mask is None: + mask = np.ones(image.shape, dtype=bool) + fsmooth = lambda x: gaussian_filter(x, sigma, mode='constant') + smoothed = smooth_with_function_and_mask(image, fsmooth, mask) + jsobel = ndi.sobel(smoothed, axis=1) + isobel = ndi.sobel(smoothed, axis=0) + abs_isobel = np.abs(isobel) + abs_jsobel = np.abs(jsobel) + magnitude = np.hypot(isobel, jsobel) + + # + # Make the eroded mask. Setting the border value to zero will wipe + # out the image edges for us. + # + s = generate_binary_structure(2, 2) + eroded_mask = binary_erosion(mask, s, border_value=0) + eroded_mask = eroded_mask & (magnitude > 0) + # + #--------- Find local maxima -------------- + # + # Assign each point to have a normal of 0-45 degrees, 45-90 degrees, + # 90-135 degrees and 135-180 degrees. + # + local_maxima = np.zeros(image.shape,bool) + #----- 0 to 45 degrees ------ + pts_plus = (isobel >= 0) & (jsobel >= 0) & (abs_isobel >= abs_jsobel) + pts_minus = (isobel <= 0) & (jsobel <= 0) & (abs_isobel >= abs_jsobel) + pts = pts_plus | pts_minus + pts = eroded_mask & pts + # Get the magnitudes shifted left to make a matrix of the points to the + # right of pts. Similarly, shift left and down to get the points to the + # top right of pts. + c1 = magnitude[1:, :][pts[:-1, :]] + c2 = magnitude[1:, 1:][pts[:-1, :-1]] + m = magnitude[pts] + w = abs_jsobel[pts] / abs_isobel[pts] + c_plus = c2 * w + c1 * (1 - w) <= m + c1 = magnitude[:-1, :][pts[1:, :]] + c2 = magnitude[:-1, :-1][pts[1:, 1:]] + c_minus = c2 * w + c1 * (1 - w) <= m + local_maxima[pts] = c_plus & c_minus + #----- 45 to 90 degrees ------ + # Mix diagonal and vertical + # + pts_plus = (isobel >= 0) & (jsobel >= 0) & (abs_isobel <= abs_jsobel) + pts_minus = (isobel <= 0) & (jsobel <= 0) & (abs_isobel <= abs_jsobel) + pts = pts_plus | pts_minus + pts = eroded_mask & pts + c1 = magnitude[:, 1:][pts[:, :-1]] + c2 = magnitude[1:, 1:][pts[:-1, :-1]] + m = magnitude[pts] + w = abs_isobel[pts] / abs_jsobel[pts] + c_plus = c2 * w + c1 * (1 - w) <= m + c1 = magnitude[:, :-1][pts[:, 1:]] + c2 = magnitude[:-1, :-1][pts[1:, 1:]] + c_minus = c2 * w + c1 * (1 - w) <= m + local_maxima[pts] = c_plus & c_minus + #----- 90 to 135 degrees ------ + # Mix anti-diagonal and vertical + # + pts_plus = (isobel <= 0) & (jsobel >= 0) & (abs_isobel <= abs_jsobel) + pts_minus = (isobel >= 0) & (jsobel <= 0) & (abs_isobel <= abs_jsobel) + pts = pts_plus | pts_minus + pts = eroded_mask & pts + c1a = magnitude[:, 1:][pts[:, :-1]] + c2a = magnitude[:-1, 1:][pts[1:, :-1]] + m = magnitude[pts] + w = abs_isobel[pts] / abs_jsobel[pts] + c_plus = c2a * w + c1a * (1.0 - w) <= m + c1 = magnitude[:, :-1][pts[:, 1:]] + c2 = magnitude[1:, :-1][pts[:-1, 1:]] + c_minus = c2 * w + c1 * (1.0 - w) <= m + cc = np.logical_and(c_plus,c_minus) + local_maxima[pts] = c_plus & c_minus + #----- 135 to 180 degrees ------ + # Mix anti-diagonal and anti-horizontal + # + pts_plus = (isobel <= 0) & (jsobel >= 0) & (abs_isobel >= abs_jsobel) + pts_minus = (isobel >= 0) & (jsobel <= 0) & (abs_isobel >= abs_jsobel) + pts = pts_plus | pts_minus + pts = eroded_mask & pts + c1 = magnitude[:-1, :][pts[1:, :]] + c2 = magnitude[:-1, 1:][pts[1:, :-1]] + m = magnitude[pts] + w = abs_jsobel[pts] / abs_isobel[pts] + c_plus = c2 * w + c1 * (1 - w) <= m + c1 = magnitude[1:, :][pts[:-1, :]] + c2 = magnitude[1:,:-1][pts[:-1,1:]] + c_minus = c2 * w + c1 * (1 - w) <= m + local_maxima[pts] = c_plus & c_minus + # + #---- Create two masks at the two thresholds. + # + high_mask = local_maxima & (magnitude >= high_threshold) + low_mask = local_maxima & (magnitude >= low_threshold) + # + # Segment the low-mask, then only keep low-segments that have + # some high_mask component in them + # + labels,count = label(low_mask, np.ndarray((3, 3),bool)) + if count == 0: + return low_mask + + sums = (np.array(ndi.sum(high_mask,labels, + np.arange(count,dtype=np.int32) + 1), + copy=False, ndmin=1)) + good_label = np.zeros((count + 1,),bool) + good_label[1:] = sums > 0 + output_mask = good_label[labels] + return output_mask diff --git a/advanced/image_processing/auto_examples/image_source_canny.rst b/advanced/image_processing/auto_examples/image_source_canny.rst new file mode 100644 index 0000000..7c92beb --- /dev/null +++ b/advanced/image_processing/auto_examples/image_source_canny.rst @@ -0,0 +1,23 @@ + + +.. _example_image_source_canny.py: + +canny.py - Canny Edge detector + +Reference: Canny, J., A Computational Approach To Edge Detection, IEEE Trans. + Pattern Analysis and Machine Intelligence, 8:679-714, 1986 + +Originally part of CellProfiler, code licensed under both GPL and BSD licenses. +Website: http://www.cellprofiler.org +Copyright (c) 2003-2009 Massachusetts Institute of Technology +Copyright (c) 2009-2011 Broad Institute +All rights reserved. +Original author: Lee Kamentsky + + + +**Python source code:** :download:`image_source_canny.py ` + +.. literalinclude:: image_source_canny.py + :lines: 14- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/images/plot_GMM_1.png b/advanced/image_processing/auto_examples/images/plot_GMM_1.png new file mode 100644 index 0000000..c6ecdff Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_GMM_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_block_mean_1.png b/advanced/image_processing/auto_examples/images/plot_block_mean_1.png new file mode 100644 index 0000000..4a4d829 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_block_mean_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_blur_1.png b/advanced/image_processing/auto_examples/images/plot_blur_1.png new file mode 100644 index 0000000..db2e85e Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_blur_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_canny_1.png b/advanced/image_processing/auto_examples/images/plot_canny_1.png new file mode 100644 index 0000000..61f5dd1 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_canny_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_clean_morpho_1.png b/advanced/image_processing/auto_examples/images/plot_clean_morpho_1.png new file mode 100644 index 0000000..9951ac6 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_clean_morpho_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_denoising_1.png b/advanced/image_processing/auto_examples/images/plot_denoising_1.png new file mode 100644 index 0000000..6eb83b2 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_denoising_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_display_lena_1.png b/advanced/image_processing/auto_examples/images/plot_display_lena_1.png new file mode 100644 index 0000000..fa651df Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_display_lena_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_find_edges_1.png b/advanced/image_processing/auto_examples/images/plot_find_edges_1.png new file mode 100644 index 0000000..5a465d6 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_find_edges_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_find_object_1.png b/advanced/image_processing/auto_examples/images/plot_find_object_1.png new file mode 100644 index 0000000..16168d2 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_find_object_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_geom_lena_1.png b/advanced/image_processing/auto_examples/images/plot_geom_lena_1.png new file mode 100644 index 0000000..ed14380 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_geom_lena_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_granulo_1.png b/advanced/image_processing/auto_examples/images/plot_granulo_1.png new file mode 100644 index 0000000..ce2d4ef Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_granulo_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_greyscale_dilation_1.png b/advanced/image_processing/auto_examples/images/plot_greyscale_dilation_1.png new file mode 100644 index 0000000..0b28685 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_greyscale_dilation_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_histo_segmentation_1.png b/advanced/image_processing/auto_examples/images/plot_histo_segmentation_1.png new file mode 100644 index 0000000..d5c49e1 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_histo_segmentation_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_interpolation_lena_1.png b/advanced/image_processing/auto_examples/images/plot_interpolation_lena_1.png new file mode 100644 index 0000000..bb117b0 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_interpolation_lena_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_lena_1.png b/advanced/image_processing/auto_examples/images/plot_lena_1.png new file mode 100644 index 0000000..7df73a2 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_lena_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_lena_denoise_1.png b/advanced/image_processing/auto_examples/images/plot_lena_denoise_1.png new file mode 100644 index 0000000..bba6c51 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_lena_denoise_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_lena_tv_denoise_1.png b/advanced/image_processing/auto_examples/images/plot_lena_tv_denoise_1.png new file mode 100644 index 0000000..a55b710 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_lena_tv_denoise_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_measure_data_1.png b/advanced/image_processing/auto_examples/images/plot_measure_data_1.png new file mode 100644 index 0000000..e374a4d Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_measure_data_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_numpy_array_1.png b/advanced/image_processing/auto_examples/images/plot_numpy_array_1.png new file mode 100644 index 0000000..5129604 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_numpy_array_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_propagation_1.png b/advanced/image_processing/auto_examples/images/plot_propagation_1.png new file mode 100644 index 0000000..71131cb Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_propagation_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_radial_mean_1.png b/advanced/image_processing/auto_examples/images/plot_radial_mean_1.png new file mode 100644 index 0000000..66ddb14 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_radial_mean_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_sharpen_1.png b/advanced/image_processing/auto_examples/images/plot_sharpen_1.png new file mode 100644 index 0000000..d059199 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_sharpen_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_spectral_clustering_1.png b/advanced/image_processing/auto_examples/images/plot_spectral_clustering_1.png new file mode 100644 index 0000000..da7cdea Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_spectral_clustering_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_synthetic_data_1.png b/advanced/image_processing/auto_examples/images/plot_synthetic_data_1.png new file mode 100644 index 0000000..b0b307e Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_synthetic_data_1.png differ diff --git a/advanced/image_processing/auto_examples/images/plot_watershed_segmentation_1.png b/advanced/image_processing/auto_examples/images/plot_watershed_segmentation_1.png new file mode 100644 index 0000000..a87300e Binary files /dev/null and b/advanced/image_processing/auto_examples/images/plot_watershed_segmentation_1.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/image_source_canny.png b/advanced/image_processing/auto_examples/images/thumb/image_source_canny.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/image_source_canny.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_GMM.png b/advanced/image_processing/auto_examples/images/thumb/plot_GMM.png new file mode 100644 index 0000000..4e52bef Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_GMM.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_block_mean.png b/advanced/image_processing/auto_examples/images/thumb/plot_block_mean.png new file mode 100644 index 0000000..b89756d Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_block_mean.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_blur.png b/advanced/image_processing/auto_examples/images/thumb/plot_blur.png new file mode 100644 index 0000000..ea0a8ee Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_blur.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_canny.png b/advanced/image_processing/auto_examples/images/thumb/plot_canny.png new file mode 100644 index 0000000..77fc437 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_canny.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_clean_morpho.png b/advanced/image_processing/auto_examples/images/thumb/plot_clean_morpho.png new file mode 100644 index 0000000..781eded Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_clean_morpho.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_denoising.png b/advanced/image_processing/auto_examples/images/thumb/plot_denoising.png new file mode 100644 index 0000000..731da3e Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_denoising.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_display_lena.png b/advanced/image_processing/auto_examples/images/thumb/plot_display_lena.png new file mode 100644 index 0000000..8c53c92 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_display_lena.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_find_edges.png b/advanced/image_processing/auto_examples/images/thumb/plot_find_edges.png new file mode 100644 index 0000000..fba5601 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_find_edges.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_find_object.png b/advanced/image_processing/auto_examples/images/thumb/plot_find_object.png new file mode 100644 index 0000000..6e6079c Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_find_object.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_geom_lena.png b/advanced/image_processing/auto_examples/images/thumb/plot_geom_lena.png new file mode 100644 index 0000000..2ace9c9 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_geom_lena.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_granulo.png b/advanced/image_processing/auto_examples/images/thumb/plot_granulo.png new file mode 100644 index 0000000..0f99a25 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_granulo.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_greyscale_dilation.png b/advanced/image_processing/auto_examples/images/thumb/plot_greyscale_dilation.png new file mode 100644 index 0000000..cd39842 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_greyscale_dilation.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_histo_segmentation.png b/advanced/image_processing/auto_examples/images/thumb/plot_histo_segmentation.png new file mode 100644 index 0000000..53b6247 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_histo_segmentation.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_interpolation_lena.png b/advanced/image_processing/auto_examples/images/thumb/plot_interpolation_lena.png new file mode 100644 index 0000000..6dffcc8 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_interpolation_lena.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_lena.png b/advanced/image_processing/auto_examples/images/thumb/plot_lena.png new file mode 100644 index 0000000..9de5845 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_lena.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_lena_denoise.png b/advanced/image_processing/auto_examples/images/thumb/plot_lena_denoise.png new file mode 100644 index 0000000..1de045a Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_lena_denoise.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_lena_tv_denoise.png b/advanced/image_processing/auto_examples/images/thumb/plot_lena_tv_denoise.png new file mode 100644 index 0000000..454c535 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_lena_tv_denoise.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_measure_data.png b/advanced/image_processing/auto_examples/images/thumb/plot_measure_data.png new file mode 100644 index 0000000..099f65a Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_measure_data.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_numpy_array.png b/advanced/image_processing/auto_examples/images/thumb/plot_numpy_array.png new file mode 100644 index 0000000..61a391a Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_numpy_array.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_propagation.png b/advanced/image_processing/auto_examples/images/thumb/plot_propagation.png new file mode 100644 index 0000000..d5beb67 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_propagation.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_radial_mean.png b/advanced/image_processing/auto_examples/images/thumb/plot_radial_mean.png new file mode 100644 index 0000000..b7e88e4 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_radial_mean.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_sharpen.png b/advanced/image_processing/auto_examples/images/thumb/plot_sharpen.png new file mode 100644 index 0000000..c7a3186 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_sharpen.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_spectral_clustering.png b/advanced/image_processing/auto_examples/images/thumb/plot_spectral_clustering.png new file mode 100644 index 0000000..3a8c5ba Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_spectral_clustering.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_synthetic_data.png b/advanced/image_processing/auto_examples/images/thumb/plot_synthetic_data.png new file mode 100644 index 0000000..bcc206e Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_synthetic_data.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/plot_watershed_segmentation.png b/advanced/image_processing/auto_examples/images/thumb/plot_watershed_segmentation.png new file mode 100644 index 0000000..5068bad Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/plot_watershed_segmentation.png differ diff --git a/advanced/image_processing/auto_examples/images/thumb/tv_denoise.png b/advanced/image_processing/auto_examples/images/thumb/tv_denoise.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/image_processing/auto_examples/images/thumb/tv_denoise.png differ diff --git a/advanced/image_processing/auto_examples/index.rst b/advanced/image_processing/auto_examples/index.rst new file mode 100644 index 0000000..682fa84 --- /dev/null +++ b/advanced/image_processing/auto_examples/index.rst @@ -0,0 +1,166 @@ + +.. raw:: html + + + +Examples +======== + +.. _examples-index: +.. figure:: ./images/thumb/image_source_canny.png + :target: ./image_source_canny.html + + :ref:`example_image_source_canny.py` + +.. figure:: ./images/thumb/plot_GMM.png + :target: ./plot_GMM.html + + :ref:`example_plot_GMM.py` + +.. figure:: ./images/thumb/plot_block_mean.png + :target: ./plot_block_mean.html + + :ref:`example_plot_block_mean.py` + +.. figure:: ./images/thumb/plot_blur.png + :target: ./plot_blur.html + + :ref:`example_plot_blur.py` + +.. figure:: ./images/thumb/plot_canny.png + :target: ./plot_canny.html + + :ref:`example_plot_canny.py` + +.. figure:: ./images/thumb/plot_clean_morpho.png + :target: ./plot_clean_morpho.html + + :ref:`example_plot_clean_morpho.py` + +.. figure:: ./images/thumb/plot_denoising.png + :target: ./plot_denoising.html + + :ref:`example_plot_denoising.py` + +.. figure:: ./images/thumb/plot_display_lena.png + :target: ./plot_display_lena.html + + :ref:`example_plot_display_lena.py` + +.. figure:: ./images/thumb/plot_find_edges.png + :target: ./plot_find_edges.html + + :ref:`example_plot_find_edges.py` + +.. figure:: ./images/thumb/plot_find_object.png + :target: ./plot_find_object.html + + :ref:`example_plot_find_object.py` + +.. figure:: ./images/thumb/plot_geom_lena.png + :target: ./plot_geom_lena.html + + :ref:`example_plot_geom_lena.py` + +.. figure:: ./images/thumb/plot_granulo.png + :target: ./plot_granulo.html + + :ref:`example_plot_granulo.py` + +.. figure:: ./images/thumb/plot_greyscale_dilation.png + :target: ./plot_greyscale_dilation.html + + :ref:`example_plot_greyscale_dilation.py` + +.. figure:: ./images/thumb/plot_histo_segmentation.png + :target: ./plot_histo_segmentation.html + + :ref:`example_plot_histo_segmentation.py` + +.. figure:: ./images/thumb/plot_interpolation_lena.png + :target: ./plot_interpolation_lena.html + + :ref:`example_plot_interpolation_lena.py` + +.. figure:: ./images/thumb/plot_lena.png + :target: ./plot_lena.html + + :ref:`example_plot_lena.py` + +.. figure:: ./images/thumb/plot_lena_denoise.png + :target: ./plot_lena_denoise.html + + :ref:`example_plot_lena_denoise.py` + +.. figure:: ./images/thumb/plot_lena_tv_denoise.png + :target: ./plot_lena_tv_denoise.html + + :ref:`example_plot_lena_tv_denoise.py` + +.. figure:: ./images/thumb/plot_measure_data.png + :target: ./plot_measure_data.html + + :ref:`example_plot_measure_data.py` + +.. figure:: ./images/thumb/plot_numpy_array.png + :target: ./plot_numpy_array.html + + :ref:`example_plot_numpy_array.py` + +.. figure:: ./images/thumb/plot_propagation.png + :target: ./plot_propagation.html + + :ref:`example_plot_propagation.py` + +.. figure:: ./images/thumb/plot_radial_mean.png + :target: ./plot_radial_mean.html + + :ref:`example_plot_radial_mean.py` + +.. figure:: ./images/thumb/plot_sharpen.png + :target: ./plot_sharpen.html + + :ref:`example_plot_sharpen.py` + +.. figure:: ./images/thumb/plot_spectral_clustering.png + :target: ./plot_spectral_clustering.html + + :ref:`example_plot_spectral_clustering.py` + +.. figure:: ./images/thumb/plot_synthetic_data.png + :target: ./plot_synthetic_data.html + + :ref:`example_plot_synthetic_data.py` + +.. figure:: ./images/thumb/plot_watershed_segmentation.png + :target: ./plot_watershed_segmentation.html + + :ref:`example_plot_watershed_segmentation.py` + +.. figure:: ./images/thumb/tv_denoise.png + :target: ./tv_denoise.html + + :ref:`example_tv_denoise.py` + + +.. raw:: html + +
    + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_GMM.py b/advanced/image_processing/auto_examples/plot_GMM.py new file mode 100644 index 0000000..9c76055 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_GMM.py @@ -0,0 +1,44 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt +from sklearn.mixture import GMM + +np.random.seed(1) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l*np.random.random((2, n**2)) +im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 +im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + +mask = (im > im.mean()).astype(np.float) + + +img = mask + 0.3*np.random.randn(*mask.shape) + +hist, bin_edges = np.histogram(img, bins=60) +bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:]) + +classif = GMM(n_components=2) +classif.fit(img.reshape((img.size, 1))) + +threshold = np.mean(classif.means_) +binary_img = img > threshold + + +plt.figure(figsize=(11,4)) + +plt.subplot(131) +plt.imshow(img) +plt.axis('off') +plt.subplot(132) +plt.plot(bin_centers, hist, lw=2) +plt.axvline(0.5, color='r', ls='--', lw=2) +plt.text(0.57, 0.8, 'histogram', fontsize=20, transform = plt.gca().transAxes) +plt.yticks([]) +plt.subplot(133) +plt.imshow(binary_img, cmap=plt.cm.gray, interpolation='nearest') +plt.axis('off') + +plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_GMM.rst b/advanced/image_processing/auto_examples/plot_GMM.rst new file mode 100644 index 0000000..3425c00 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_GMM.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_GMM.py: + + + + +.. image:: images/plot_GMM_1.png + :align: center + + +**Python source code:** :download:`plot_GMM.py ` + +.. literalinclude:: plot_GMM.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_block_mean.py b/advanced/image_processing/auto_examples/plot_block_mean.py new file mode 100644 index 0000000..70c816b --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_block_mean.py @@ -0,0 +1,20 @@ +import numpy as np +import scipy +from scipy import ndimage +import matplotlib.pyplot as plt + +l = scipy.misc.lena() +sx, sy = l.shape +X, Y = np.ogrid[0:sx, 0:sy] + +regions = sy/6 * (X/4) + Y/6 +block_mean = ndimage.mean(l, labels=regions, + index=np.arange(1, regions.max() +1)) +block_mean.shape = (sx/4, sy/6) + +plt.figure(figsize=(5, 5)) +plt.imshow(block_mean, cmap=plt.cm.gray) +plt.axis('off') + +plt.show() + diff --git a/advanced/image_processing/auto_examples/plot_block_mean.rst b/advanced/image_processing/auto_examples/plot_block_mean.rst new file mode 100644 index 0000000..b9533c5 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_block_mean.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_block_mean.py: + + + + +.. image:: images/plot_block_mean_1.png + :align: center + + +**Python source code:** :download:`plot_block_mean.py ` + +.. literalinclude:: plot_block_mean.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_blur.py b/advanced/image_processing/auto_examples/plot_blur.py new file mode 100644 index 0000000..fc18bf2 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_blur.py @@ -0,0 +1,24 @@ +import scipy +from scipy import ndimage +import matplotlib.pyplot as plt + +lena = scipy.misc.lena() +blurred_lena = ndimage.gaussian_filter(lena, sigma=3) +very_blurred = ndimage.gaussian_filter(lena, sigma=5) +local_mean = ndimage.uniform_filter(lena, size=11) + +plt.figure(figsize=(9, 3)) +plt.subplot(131) +plt.imshow(blurred_lena, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(132) +plt.imshow(very_blurred, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(133) +plt.imshow(local_mean, cmap=plt.cm.gray) +plt.axis('off') + +plt.subplots_adjust(wspace=0, hspace=0., top=0.99, bottom=0.01, + left=0.01, right=0.99) + +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_blur.rst b/advanced/image_processing/auto_examples/plot_blur.rst new file mode 100644 index 0000000..735e6db --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_blur.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_blur.py: + + + + +.. image:: images/plot_blur_1.png + :align: center + + +**Python source code:** :download:`plot_blur.py ` + +.. literalinclude:: plot_blur.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_canny.py b/advanced/image_processing/auto_examples/plot_canny.py new file mode 100644 index 0000000..72f7b00 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_canny.py @@ -0,0 +1,34 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt +#from scikits.image.filter import canny +from image_source_canny import canny + +im = np.zeros((256, 256)) +im[64:-64, 64:-64] = 1 + +im = ndimage.rotate(im, 15, mode='constant') +im = ndimage.gaussian_filter(im, 8) + +im += 0.1*np.random.random(im.shape) + +edges = canny(im, 1, 0.4, 0.2) + +plt.figure(figsize=(12, 4)) + +plt.subplot(131) +plt.imshow(im, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(132) +plt.imshow(edges, cmap=plt.cm.gray) +plt.axis('off') + + +edges = canny(im, 3, 0.3, 0.2) +plt.subplot(133) +plt.imshow(edges, cmap=plt.cm.gray) +plt.axis('off') + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) + +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_canny.rst b/advanced/image_processing/auto_examples/plot_canny.rst new file mode 100644 index 0000000..ba76e43 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_canny.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_canny.py: + + + + +.. image:: images/plot_canny_1.png + :align: center + + +**Python source code:** :download:`plot_canny.py ` + +.. literalinclude:: plot_canny.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_clean_morpho.py b/advanced/image_processing/auto_examples/plot_clean_morpho.py new file mode 100644 index 0000000..ec4351e --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_clean_morpho.py @@ -0,0 +1,47 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt +from sklearn.mixture import GMM + +np.random.seed(1) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l*np.random.random((2, n**2)) +im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 +im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + +mask = (im > im.mean()).astype(np.float) + + +img = mask + 0.3*np.random.randn(*mask.shape) + +binary_img = img > 0.5 + +# Remove small white regions +open_img = ndimage.binary_opening(binary_img) +# Remove small black hole +close_img = ndimage.binary_closing(open_img) + +plt.figure(figsize=(12, 3)) + +l = 128 + +plt.subplot(141) +plt.imshow(binary_img[:l, :l], cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(142) +plt.imshow(open_img[:l, :l], cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(143) +plt.imshow(close_img[:l, :l], cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(144) +plt.imshow(mask[:l, :l], cmap=plt.cm.gray) +plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors='r') +plt.axis('off') + +plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) + +plt.show() + diff --git a/advanced/image_processing/auto_examples/plot_clean_morpho.rst b/advanced/image_processing/auto_examples/plot_clean_morpho.rst new file mode 100644 index 0000000..17d76c1 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_clean_morpho.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_clean_morpho.py: + + + + +.. image:: images/plot_clean_morpho_1.png + :align: center + + +**Python source code:** :download:`plot_clean_morpho.py ` + +.. literalinclude:: plot_clean_morpho.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_denoising.py b/advanced/image_processing/auto_examples/plot_denoising.py new file mode 100644 index 0000000..c780c2e --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_denoising.py @@ -0,0 +1,35 @@ +import numpy as np +import scipy +from scipy import ndimage +import matplotlib.pyplot as plt + +im = np.zeros((20, 20)) +im[5:-5, 5:-5] = 1 +im = ndimage.distance_transform_bf(im) +im_noise = im + 0.2*np.random.randn(*im.shape) + +im_med = ndimage.median_filter(im_noise, 3) + +plt.figure(figsize=(16, 5)) + +plt.subplot(141) +plt.imshow(im, interpolation='nearest') +plt.axis('off') +plt.title('Original image', fontsize=20) +plt.subplot(142) +plt.imshow(im_noise, interpolation='nearest', vmin=0, vmax=5) +plt.axis('off') +plt.title('Noisy image', fontsize=20) +plt.subplot(143) +plt.imshow(im_med, interpolation='nearest', vmin=0, vmax=5) +plt.axis('off') +plt.title('Median filter', fontsize=20) +plt.subplot(144) +plt.imshow(np.abs(im - im_med), cmap=plt.cm.hot, interpolation='nearest') +plt.axis('off') +plt.title('Error', fontsize=20) + + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) + +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_denoising.rst b/advanced/image_processing/auto_examples/plot_denoising.rst new file mode 100644 index 0000000..bb4c1b0 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_denoising.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_denoising.py: + + + + +.. image:: images/plot_denoising_1.png + :align: center + + +**Python source code:** :download:`plot_denoising.py ` + +.. literalinclude:: plot_denoising.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_display_lena.py b/advanced/image_processing/auto_examples/plot_display_lena.py new file mode 100644 index 0000000..7d1d5d4 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_display_lena.py @@ -0,0 +1,22 @@ +import scipy +import matplotlib.pyplot as plt + +l = scipy.misc.lena() + +plt.figure(figsize=(10, 3.6)) + +plt.subplot(131) +plt.imshow(l, cmap=plt.cm.gray) + +plt.subplot(132) +plt.imshow(l, cmap=plt.cm.gray, vmin=30, vmax=200) +plt.axis('off') + +plt.subplot(133) +plt.imshow(l, cmap=plt.cm.gray) +plt.contour(l, [60, 211]) +plt.axis('off') + +plt.subplots_adjust(wspace=0, hspace=0., top=0.99, bottom=0.01, left=0.05, + right=0.99) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_display_lena.rst b/advanced/image_processing/auto_examples/plot_display_lena.rst new file mode 100644 index 0000000..6b4b35e --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_display_lena.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_display_lena.py: + + + + +.. image:: images/plot_display_lena_1.png + :align: center + + +**Python source code:** :download:`plot_display_lena.py ` + +.. literalinclude:: plot_display_lena.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_find_edges.py b/advanced/image_processing/auto_examples/plot_find_edges.py new file mode 100644 index 0000000..37cce1a --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_find_edges.py @@ -0,0 +1,44 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt + +im = np.zeros((256, 256)) +im[64:-64, 64:-64] = 1 + +im = ndimage.rotate(im, 15, mode='constant') +im = ndimage.gaussian_filter(im, 8) + +sx = ndimage.sobel(im, axis=0, mode='constant') +sy = ndimage.sobel(im, axis=1, mode='constant') +sob = np.hypot(sx, sy) + +plt.figure(figsize=(16, 5)) +plt.subplot(141) +plt.imshow(im, cmap=plt.cm.gray) +plt.axis('off') +plt.title('square', fontsize=20) +plt.subplot(142) +plt.imshow(sx) +plt.axis('off') +plt.title('Sobel (x direction)', fontsize=20) +plt.subplot(143) +plt.imshow(sob) +plt.axis('off') +plt.title('Sobel filter', fontsize=20) + +im += 0.07*np.random.random(im.shape) + +sx = ndimage.sobel(im, axis=0, mode='constant') +sy = ndimage.sobel(im, axis=1, mode='constant') +sob = np.hypot(sx, sy) + +plt.subplot(144) +plt.imshow(sob) +plt.axis('off') +plt.title('Sobel for noisy image', fontsize=20) + + + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9) + +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_find_edges.rst b/advanced/image_processing/auto_examples/plot_find_edges.rst new file mode 100644 index 0000000..9276d0c --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_find_edges.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_find_edges.py: + + + + +.. image:: images/plot_find_edges_1.png + :align: center + + +**Python source code:** :download:`plot_find_edges.py ` + +.. literalinclude:: plot_find_edges.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_find_object.py b/advanced/image_processing/auto_examples/plot_find_object.py new file mode 100644 index 0000000..3e1439f --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_find_object.py @@ -0,0 +1,32 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt + +np.random.seed(1) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l*np.random.random((2, n**2)) +im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 +im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + +mask = im > im.mean() + +label_im, nb_labels = ndimage.label(mask) + +sizes = ndimage.sum(mask, label_im, range(nb_labels + 1)) +mask_size = sizes < 1000 +remove_pixel = mask_size[label_im] +label_im[remove_pixel] = 0 +labels = np.unique(label_im) +label_im = np.searchsorted(labels, label_im) + +slice_x, slice_y = ndimage.find_objects(label_im==4)[0] +roi = im[slice_x, slice_y] + +plt.figure(figsize=(4, 2)) +plt.axes([0, 0, 1, 1]) +plt.imshow(roi) +plt.axis('off') + +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_find_object.rst b/advanced/image_processing/auto_examples/plot_find_object.rst new file mode 100644 index 0000000..8474a99 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_find_object.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_find_object.py: + + + + +.. image:: images/plot_find_object_1.png + :align: center + + +**Python source code:** :download:`plot_find_object.py ` + +.. literalinclude:: plot_find_object.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_geom_lena.py b/advanced/image_processing/auto_examples/plot_geom_lena.py new file mode 100644 index 0000000..b7def4c --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_geom_lena.py @@ -0,0 +1,38 @@ +import numpy as np +import scipy +from scipy import ndimage +import matplotlib.pyplot as plt + +lena = scipy.misc.lena() +lx, ly = lena.shape +# Copping +crop_lena = lena[lx/4:-lx/4, ly/4:-ly/4] +# up <-> down flip +flip_ud_lena = np.flipud(lena) +# rotation +rotate_lena = ndimage.rotate(lena, 45) +rotate_lena_noreshape = ndimage.rotate(lena, 45, reshape=False) + +plt.figure(figsize=(12.5, 2.5)) + + +plt.subplot(151) +plt.imshow(lena, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(152) +plt.imshow(crop_lena, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(153) +plt.imshow(flip_ud_lena, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(154) +plt.imshow(rotate_lena, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(155) +plt.imshow(rotate_lena_noreshape, cmap=plt.cm.gray) +plt.axis('off') + +plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, + right=1) + +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_geom_lena.rst b/advanced/image_processing/auto_examples/plot_geom_lena.rst new file mode 100644 index 0000000..4b746cf --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_geom_lena.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_geom_lena.py: + + + + +.. image:: images/plot_geom_lena_1.png + :align: center + + +**Python source code:** :download:`plot_geom_lena.py ` + +.. literalinclude:: plot_geom_lena.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_granulo.py b/advanced/image_processing/auto_examples/plot_granulo.py new file mode 100644 index 0000000..8064c71 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_granulo.py @@ -0,0 +1,48 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt + +def disk_structure(n): + struct = np.zeros((2 * n + 1, 2 * n + 1)) + x, y = np.indices((2 * n + 1, 2 * n + 1)) + mask = (x - n)**2 + (y - n)**2 <= n**2 + struct[mask] = 1 + return struct.astype(np.bool) + + +def granulometry(data, sizes=None): + s = max(data.shape) + if sizes == None: + sizes = range(1, s/2, 2) + granulo = [ndimage.binary_opening(data, \ + structure=disk_structure(n)).sum() for n in sizes] + return granulo + + +np.random.seed(1) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l*np.random.random((2, n**2)) +im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 +im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + +mask = im > im.mean() + +granulo = granulometry(mask, sizes=np.arange(2, 19, 4)) + +plt.figure(figsize=(6, 2.2)) + +plt.subplot(121) +plt.imshow(mask, cmap=plt.cm.gray) +opened = ndimage.binary_opening(mask, structure=disk_structure(10)) +opened_more = ndimage.binary_opening(mask, structure=disk_structure(14)) +plt.contour(opened, [0.5], colors='b', linewidths=2) +plt.contour(opened_more, [0.5], colors='r', linewidths=2) +plt.axis('off') +plt.subplot(122) +plt.plot(np.arange(2, 19, 4), granulo, 'ok', ms=8) + + +plt.subplots_adjust(wspace=0.02, hspace=0.15, top=0.95, bottom=0.15, left=0, right=0.95) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_granulo.rst b/advanced/image_processing/auto_examples/plot_granulo.rst new file mode 100644 index 0000000..0cb51a6 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_granulo.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_granulo.py: + + + + +.. image:: images/plot_granulo_1.png + :align: center + + +**Python source code:** :download:`plot_granulo.py ` + +.. literalinclude:: plot_granulo.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_greyscale_dilation.py b/advanced/image_processing/auto_examples/plot_greyscale_dilation.py new file mode 100644 index 0000000..195c8fd --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_greyscale_dilation.py @@ -0,0 +1,33 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt + +im = np.zeros((64, 64)) +np.random.seed(2) +x, y = (63*np.random.random((2, 8))).astype(np.int) +im[x, y] = np.arange(8) + +bigger_points = ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) + +square = np.zeros((16, 16)) +square[4:-4, 4:-4] = 1 +dist = ndimage.distance_transform_bf(square) +dilate_dist = ndimage.grey_dilation(dist, size=(3, 3), \ + structure=np.ones((3, 3))) + +plt.figure(figsize=(12.5, 3)) +plt.subplot(141) +plt.imshow(im, interpolation='nearest', cmap=plt.cm.spectral) +plt.axis('off') +plt.subplot(142) +plt.imshow(bigger_points, interpolation='nearest', cmap=plt.cm.spectral) +plt.axis('off') +plt.subplot(143) +plt.imshow(dist, interpolation='nearest', cmap=plt.cm.spectral) +plt.axis('off') +plt.subplot(144) +plt.imshow(dilate_dist, interpolation='nearest', cmap=plt.cm.spectral) +plt.axis('off') + +plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_greyscale_dilation.rst b/advanced/image_processing/auto_examples/plot_greyscale_dilation.rst new file mode 100644 index 0000000..2fcb9e3 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_greyscale_dilation.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_greyscale_dilation.py: + + + + +.. image:: images/plot_greyscale_dilation_1.png + :align: center + + +**Python source code:** :download:`plot_greyscale_dilation.py ` + +.. literalinclude:: plot_greyscale_dilation.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_histo_segmentation.py b/advanced/image_processing/auto_examples/plot_histo_segmentation.py new file mode 100644 index 0000000..b1abe8b --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_histo_segmentation.py @@ -0,0 +1,39 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt + +np.random.seed(1) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l*np.random.random((2, n**2)) +im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 +im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + +mask = (im > im.mean()).astype(np.float) + +mask += 0.1 * im + +img = mask + 0.2*np.random.randn(*mask.shape) + +hist, bin_edges = np.histogram(img, bins=60) +bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:]) + +binary_img = img > 0.5 + +plt.figure(figsize=(11,4)) + +plt.subplot(131) +plt.imshow(img) +plt.axis('off') +plt.subplot(132) +plt.plot(bin_centers, hist, lw=2) +plt.axvline(0.5, color='r', ls='--', lw=2) +plt.text(0.57, 0.8, 'histogram', fontsize=20, transform = plt.gca().transAxes) +plt.yticks([]) +plt.subplot(133) +plt.imshow(binary_img, cmap=plt.cm.gray, interpolation='nearest') +plt.axis('off') + +plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_histo_segmentation.rst b/advanced/image_processing/auto_examples/plot_histo_segmentation.rst new file mode 100644 index 0000000..bbdfe9e --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_histo_segmentation.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_histo_segmentation.py: + + + + +.. image:: images/plot_histo_segmentation_1.png + :align: center + + +**Python source code:** :download:`plot_histo_segmentation.py ` + +.. literalinclude:: plot_histo_segmentation.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_interpolation_lena.py b/advanced/image_processing/auto_examples/plot_interpolation_lena.py new file mode 100644 index 0000000..3a3ab75 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_interpolation_lena.py @@ -0,0 +1,17 @@ +import scipy +import matplotlib.pyplot as plt + +l = scipy.misc.lena() + +plt.figure(figsize=(8, 4)) + +plt.subplot(121) +plt.imshow(l[200:220, 200:220], cmap=plt.cm.gray) +plt.axis('off') + +plt.subplot(122) +plt.imshow(l[200:220, 200:220], cmap=plt.cm.gray, interpolation='nearest') +plt.axis('off') + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_interpolation_lena.rst b/advanced/image_processing/auto_examples/plot_interpolation_lena.rst new file mode 100644 index 0000000..74fc36c --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_interpolation_lena.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_interpolation_lena.py: + + + + +.. image:: images/plot_interpolation_lena_1.png + :align: center + + +**Python source code:** :download:`plot_interpolation_lena.py ` + +.. literalinclude:: plot_interpolation_lena.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_lena.py b/advanced/image_processing/auto_examples/plot_lena.py new file mode 100644 index 0000000..64ffbda --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_lena.py @@ -0,0 +1,8 @@ +""" Small example to plot lena.""" +from scipy import misc +l = misc.lena() +misc.imsave('lena.png', l) # uses the Image module (PIL) + +import matplotlib.pyplot as plt +plt.imshow(l) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_lena.rst b/advanced/image_processing/auto_examples/plot_lena.rst new file mode 100644 index 0000000..f97fc11 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_lena.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_lena.py: + + Small example to plot lena. + + +.. image:: images/plot_lena_1.png + :align: center + + +**Python source code:** :download:`plot_lena.py ` + +.. literalinclude:: plot_lena.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_lena_denoise.py b/advanced/image_processing/auto_examples/plot_lena_denoise.py new file mode 100644 index 0000000..e9fc49b --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_lena_denoise.py @@ -0,0 +1,32 @@ +import numpy as np +import scipy +from scipy import ndimage +import matplotlib.pyplot as plt + +l = scipy.misc.lena() +l = l[230:290, 220:320] + +noisy = l + 0.4*l.std()*np.random.random(l.shape) + +gauss_denoised = ndimage.gaussian_filter(noisy, 2) +med_denoised = ndimage.median_filter(noisy, 3) + + +plt.figure(figsize=(12,2.8)) + +plt.subplot(131) +plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.axis('off') +plt.title('noisy', fontsize=20) +plt.subplot(132) +plt.imshow(gauss_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.axis('off') +plt.title('Gaussian filter', fontsize=20) +plt.subplot(133) +plt.imshow(med_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.axis('off') +plt.title('Median filter', fontsize=20) + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, + right=1) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_lena_denoise.rst b/advanced/image_processing/auto_examples/plot_lena_denoise.rst new file mode 100644 index 0000000..3a47468 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_lena_denoise.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_lena_denoise.py: + + + + +.. image:: images/plot_lena_denoise_1.png + :align: center + + +**Python source code:** :download:`plot_lena_denoise.py ` + +.. literalinclude:: plot_lena_denoise.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_lena_tv_denoise.py b/advanced/image_processing/auto_examples/plot_lena_tv_denoise.py new file mode 100644 index 0000000..e60b0d5 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_lena_tv_denoise.py @@ -0,0 +1,33 @@ +import numpy as np +import scipy +import matplotlib.pyplot as plt +from skimage.filter import tv_denoise + +l = scipy.misc.lena() +l = l[230:290, 220:320] + +noisy = l + 0.4*l.std()*np.random.random(l.shape) + +tv_denoised = tv_denoise(noisy, weight=10) + + +plt.figure(figsize=(12, 2.8)) + +plt.subplot(131) +plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.axis('off') +plt.title('noisy', fontsize=20) +plt.subplot(132) +plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.axis('off') +plt.title('TV denoising', fontsize=20) + +tv_denoised = tv_denoise(noisy, weight=50) +plt.subplot(133) +plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.axis('off') +plt.title('(more) TV denoising', fontsize=20) + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, + right=1) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_lena_tv_denoise.rst b/advanced/image_processing/auto_examples/plot_lena_tv_denoise.rst new file mode 100644 index 0000000..e21447d --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_lena_tv_denoise.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_lena_tv_denoise.py: + + + + +.. image:: images/plot_lena_tv_denoise_1.png + :align: center + + +**Python source code:** :download:`plot_lena_tv_denoise.py ` + +.. literalinclude:: plot_lena_tv_denoise.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_measure_data.py b/advanced/image_processing/auto_examples/plot_measure_data.py new file mode 100644 index 0000000..46f5eea --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_measure_data.py @@ -0,0 +1,35 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt + +np.random.seed(1) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l*np.random.random((2, n**2)) +im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 +im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + +mask = im > im.mean() + +label_im, nb_labels = ndimage.label(mask) + +sizes = ndimage.sum(mask, label_im, range(nb_labels + 1)) +mask_size = sizes < 1000 +remove_pixel = mask_size[label_im] +label_im[remove_pixel] = 0 +labels = np.unique(label_im) +label_clean = np.searchsorted(labels, label_im) + + +plt.figure(figsize=(6 ,3)) + +plt.subplot(121) +plt.imshow(label_im, cmap=plt.cm.spectral) +plt.axis('off') +plt.subplot(122) +plt.imshow(label_clean, vmax=nb_labels, cmap=plt.cm.spectral) +plt.axis('off') + +plt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_measure_data.rst b/advanced/image_processing/auto_examples/plot_measure_data.rst new file mode 100644 index 0000000..882827e --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_measure_data.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_measure_data.py: + + + + +.. image:: images/plot_measure_data_1.png + :align: center + + +**Python source code:** :download:`plot_measure_data.py ` + +.. literalinclude:: plot_measure_data.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_numpy_array.py b/advanced/image_processing/auto_examples/plot_numpy_array.py new file mode 100644 index 0000000..b352f19 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_numpy_array.py @@ -0,0 +1,20 @@ +import numpy as np +import scipy +import matplotlib.pyplot as plt + +lena = scipy.misc.lena() +lena[10:13, 20:23] +lena[100:120] = 255 + +lx, ly = lena.shape +X, Y = np.ogrid[0:lx, 0:ly] +mask = (X - lx/2)**2 + (Y - ly/2)**2 > lx*ly/4 +lena[mask] = 0 +lena[range(400), range(400)] = 255 + +plt.figure(figsize=(3, 3)) +plt.axes([0, 0, 1, 1]) +plt.imshow(lena, cmap=plt.cm.gray) +plt.axis('off') + +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_numpy_array.rst b/advanced/image_processing/auto_examples/plot_numpy_array.rst new file mode 100644 index 0000000..369ced3 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_numpy_array.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_numpy_array.py: + + + + +.. image:: images/plot_numpy_array_1.png + :align: center + + +**Python source code:** :download:`plot_numpy_array.py ` + +.. literalinclude:: plot_numpy_array.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_propagation.py b/advanced/image_processing/auto_examples/plot_propagation.py new file mode 100644 index 0000000..e0ab5b0 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_propagation.py @@ -0,0 +1,30 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt + +square = np.zeros((32, 32)) +square[10:-10, 10:-10] = 1 +np.random.seed(2) +x, y = (32*np.random.random((2, 20))).astype(np.int) +square[x, y] = 1 + +open_square = ndimage.binary_opening(square) + +eroded_square = ndimage.binary_erosion(square) +reconstruction = ndimage.binary_propagation(eroded_square, mask=square) + +plt.figure(figsize=(9.5, 3)) +plt.subplot(131) +plt.imshow(square, cmap=plt.cm.gray, interpolation='nearest') +plt.axis('off') +plt.subplot(132) +plt.imshow(open_square, cmap=plt.cm.gray, interpolation='nearest') +plt.axis('off') +plt.subplot(133) +plt.imshow(reconstruction, cmap=plt.cm.gray, interpolation='nearest') +plt.axis('off') + +plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) +plt.show() + + diff --git a/advanced/image_processing/auto_examples/plot_propagation.rst b/advanced/image_processing/auto_examples/plot_propagation.rst new file mode 100644 index 0000000..ee42316 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_propagation.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_propagation.py: + + + + +.. image:: images/plot_propagation_1.png + :align: center + + +**Python source code:** :download:`plot_propagation.py ` + +.. literalinclude:: plot_propagation.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_radial_mean.py b/advanced/image_processing/auto_examples/plot_radial_mean.py new file mode 100644 index 0000000..3db524e --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_radial_mean.py @@ -0,0 +1,21 @@ +import numpy as np +import scipy +from scipy import ndimage +import matplotlib.pyplot as plt + +l = scipy.misc.lena() +sx, sy = l.shape +X, Y = np.ogrid[0:sx, 0:sy] + + +r = np.hypot(X - sx/2, Y - sy/2) + +rbin = (20* r/r.max()).astype(np.int) +radial_mean = ndimage.mean(l, labels=rbin, index=np.arange(1, rbin.max() +1)) + +plt.figure(figsize=(5, 5)) +plt.axes([0, 0, 1, 1]) +plt.imshow(rbin, cmap=plt.cm.spectral) +plt.axis('off') + +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_radial_mean.rst b/advanced/image_processing/auto_examples/plot_radial_mean.rst new file mode 100644 index 0000000..123f6e1 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_radial_mean.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_radial_mean.py: + + + + +.. image:: images/plot_radial_mean_1.png + :align: center + + +**Python source code:** :download:`plot_radial_mean.py ` + +.. literalinclude:: plot_radial_mean.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_sharpen.py b/advanced/image_processing/auto_examples/plot_sharpen.py new file mode 100644 index 0000000..f7ad6a0 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_sharpen.py @@ -0,0 +1,25 @@ +import scipy +from scipy import ndimage +import matplotlib.pyplot as plt + +l = scipy.misc.lena() +blurred_l = ndimage.gaussian_filter(l, 3) + +filter_blurred_l = ndimage.gaussian_filter(blurred_l, 1) + +alpha = 30 +sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l) + +plt.figure(figsize=(12, 4)) + +plt.subplot(131) +plt.imshow(l, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(132) +plt.imshow(blurred_l, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(133) +plt.imshow(sharpened, cmap=plt.cm.gray) +plt.axis('off') + +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_sharpen.rst b/advanced/image_processing/auto_examples/plot_sharpen.rst new file mode 100644 index 0000000..3ab3010 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_sharpen.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_sharpen.py: + + + + +.. image:: images/plot_sharpen_1.png + :align: center + + +**Python source code:** :download:`plot_sharpen.py ` + +.. literalinclude:: plot_sharpen.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_spectral_clustering.py b/advanced/image_processing/auto_examples/plot_spectral_clustering.py new file mode 100644 index 0000000..20c462d --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_spectral_clustering.py @@ -0,0 +1,54 @@ +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.feature_extraction import image +from sklearn.cluster import spectral_clustering + +################################################################################ +l = 100 +x, y = np.indices((l, l)) + +center1 = (28, 24) +center2 = (40, 50) +center3 = (67, 58) +center4 = (24, 70) + +radius1, radius2, radius3, radius4 = 16, 14, 15, 14 + +circle1 = (x - center1[0])**2 + (y - center1[1])**2 < radius1**2 +circle2 = (x - center2[0])**2 + (y - center2[1])**2 < radius2**2 +circle3 = (x - center3[0])**2 + (y - center3[1])**2 < radius3**2 +circle4 = (x - center4[0])**2 + (y - center4[1])**2 < radius4**2 + +################################################################################ +# 4 circles +img = circle1 + circle2 + circle3 + circle4 +mask = img.astype(bool) +img = img.astype(float) + +img += 1 + 0.2*np.random.randn(*img.shape) + +# Convert the image into a graph with the value of the gradient on the +# edges. +graph = image.img_to_graph(img, mask=mask) + +# Take a decreasing function of the gradient: we take it weakly +# dependant from the gradient the segmentation is close to a voronoi +graph.data = np.exp(-graph.data / graph.data.std()) + +# Force the solver to be arpack, since amg is numerically +# unstable on this example +labels = spectral_clustering(graph, k=4) +label_im = -np.ones(mask.shape) +label_im[mask] = labels + +plt.figure(figsize=(6, 3)) +plt.subplot(121) +plt.imshow(img, cmap=plt.cm.spectral, interpolation='nearest') +plt.axis('off') +plt.subplot(122) +plt.imshow(label_im, cmap=plt.cm.spectral, interpolation='nearest') +plt.axis('off') + +plt.subplots_adjust(wspace=0, hspace=0., top=0.99, bottom=0.01, left=0.01, right=0.99) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_spectral_clustering.rst b/advanced/image_processing/auto_examples/plot_spectral_clustering.rst new file mode 100644 index 0000000..d2249bd --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_spectral_clustering.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_spectral_clustering.py: + + + + +.. image:: images/plot_spectral_clustering_1.png + :align: center + + +**Python source code:** :download:`plot_spectral_clustering.py ` + +.. literalinclude:: plot_spectral_clustering.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_synthetic_data.py b/advanced/image_processing/auto_examples/plot_synthetic_data.py new file mode 100644 index 0000000..68c74ae --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_synthetic_data.py @@ -0,0 +1,30 @@ +import numpy as np +from scipy import ndimage +import matplotlib.pyplot as plt + +np.random.seed(1) +n = 10 +l = 256 +im = np.zeros((l, l)) +points = l*np.random.random((2, n**2)) +im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 +im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + +mask = im > im.mean() + +label_im, nb_labels = ndimage.label(mask) + +plt.figure(figsize=(9,3)) + +plt.subplot(131) +plt.imshow(im) +plt.axis('off') +plt.subplot(132) +plt.imshow(mask, cmap=plt.cm.gray) +plt.axis('off') +plt.subplot(133) +plt.imshow(label_im, cmap=plt.cm.spectral) +plt.axis('off') + +plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_synthetic_data.rst b/advanced/image_processing/auto_examples/plot_synthetic_data.rst new file mode 100644 index 0000000..84c0151 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_synthetic_data.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_synthetic_data.py: + + + + +.. image:: images/plot_synthetic_data_1.png + :align: center + + +**Python source code:** :download:`plot_synthetic_data.py ` + +.. literalinclude:: plot_synthetic_data.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/plot_watershed_segmentation.py b/advanced/image_processing/auto_examples/plot_watershed_segmentation.py new file mode 100644 index 0000000..7a79dec --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_watershed_segmentation.py @@ -0,0 +1,34 @@ +import numpy as np +from skimage.morphology import watershed, is_local_maximum +import matplotlib.pyplot as plt +from scipy import ndimage + +# Generate an initial image with two overlapping circles +x, y = np.indices((80, 80)) +x1, y1, x2, y2 = 28, 28, 44, 52 +r1, r2 = 16, 20 +mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2 +mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2 +image = np.logical_or(mask_circle1, mask_circle2) +# Now we want to separate the two objects in image +# Generate the markers as local maxima of the distance +# to the background +distance = ndimage.distance_transform_edt(image) +local_maxi = is_local_maximum(distance, image, np.ones((3, 3))) +markers = ndimage.label(local_maxi)[0] +labels = watershed(-distance, markers, mask=image) + +plt.figure(figsize=(9, 3.5)) +plt.subplot(131) +plt.imshow(image, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(132) +plt.imshow(-distance, interpolation='nearest') +plt.axis('off') +plt.subplot(133) +plt.imshow(labels, cmap='spectral', interpolation='nearest') +plt.axis('off') + +plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, + right=1) +plt.show() diff --git a/advanced/image_processing/auto_examples/plot_watershed_segmentation.rst b/advanced/image_processing/auto_examples/plot_watershed_segmentation.rst new file mode 100644 index 0000000..1980b62 --- /dev/null +++ b/advanced/image_processing/auto_examples/plot_watershed_segmentation.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_watershed_segmentation.py: + + + + +.. image:: images/plot_watershed_segmentation_1.png + :align: center + + +**Python source code:** :download:`plot_watershed_segmentation.py ` + +.. literalinclude:: plot_watershed_segmentation.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/auto_examples/tv_denoise.py b/advanced/image_processing/auto_examples/tv_denoise.py new file mode 100644 index 0000000..b7fb732 --- /dev/null +++ b/advanced/image_processing/auto_examples/tv_denoise.py @@ -0,0 +1,268 @@ +import numpy as np + +def _tv_denoise_3d(im, weight=100, eps=2.e-4, keep_type=False, n_iter_max=200): + """ + Perform total-variation denoising on 3-D arrays + + Parameters + ---------- + im: ndarray + 3-D input data to be denoised + + weight: float, optional + denoising weight. The greater ``weight``, the more denoising (at + the expense of fidelity to ``input``) + + eps: float, optional + relative difference of the value of the cost function that determines + the stop criterion. The algorithm stops when: + + (E_(n-1) - E_n) < eps * E_0 + + keep_type: bool, optional (False) + whether the output has the same dtype as the input array. + keep_type is False by default, and the dtype of the output + is np.float + + n_iter_max: int, optional + maximal number of iterations used for the optimization. + + Returns + ------- + out: ndarray + denoised array + + Notes + ----- + Rudin, Osher and Fatemi algorithm + + Examples + --------- + First build synthetic noisy data + >>> x, y, z = np.ogrid[0:40, 0:40, 0:40] + >>> mask = (x -22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2 + >>> mask = mask.astype(np.float) + >>> mask += 0.2*np.random.randn(*mask.shape) + >>> res = tv_denoise_3d(mask, weight=100) + """ + im_type = im.dtype + if im_type is not np.float: + im = im.astype(np.float) + px = np.zeros_like(im) + py = np.zeros_like(im) + pz = np.zeros_like(im) + gx = np.zeros_like(im) + gy = np.zeros_like(im) + gz = np.zeros_like(im) + d = np.zeros_like(im) + i = 0 + while i < n_iter_max: + d = - px - py - pz + d[1:] += px[:-1] + d[:, 1:] += py[:, :-1] + d[:, :, 1:] += pz[:, :, :-1] + + out = im + d + E = (d**2).sum() + + gx[:-1] = np.diff(out, axis=0) + gy[:, :-1] = np.diff(out, axis=1) + gz[:, :, :-1] = np.diff(out, axis=2) + norm = np.sqrt(gx**2 + gy**2 + gz**2) + E += weight * norm.sum() + norm *= 0.5 / weight + norm += 1. + px -= 1./6.*gx + px /= norm + py -= 1./6.*gy + py /= norm + pz -= 1/6.*gz + pz /= norm + E /= float(im.size) + if i == 0: + E_init = E + E_previous = E + else: + if np.abs(E_previous - E) < eps * E_init: + break + else: + E_previous = E + i += 1 + if keep_type: + return out.astype(im_type) + else: + return out + +def _tv_denoise_2d(im, weight=50, eps=2.e-4, keep_type=False, n_iter_max=200): + """ + Perform total-variation denoising + + Parameters + ---------- + im: ndarray + input data to be denoised + + weight: float, optional + denoising weight. The greater ``weight``, the more denoising (at + the expense of fidelity to ``input``) + + eps: float, optional + relative difference of the value of the cost function that determines + the stop criterion. The algorithm stops when: + + (E_(n-1) - E_n) < eps * E_0 + + keep_type: bool, optional (False) + whether the output has the same dtype as the input array. + keep_type is False by default, and the dtype of the output + is np.float + + n_iter_max: int, optional + maximal number of iterations used for the optimization. + + Returns + ------- + out: ndarray + denoised array + + Notes + ----- + The principle of total variation denoising is explained in + http://en.wikipedia.org/wiki/Total_variation_denoising + + This code is an implementation of the algorithm of Rudin, Fatemi and Osher + that was proposed by Chambolle in [1]_. + + References + ---------- + + .. [1] A. Chambolle, An algorithm for total variation minimization and + applications, Journal of Mathematical Imaging and Vision, + Springer, 2004, 20, 89-97. + + Examples + --------- + >>> import scipy + >>> lena = scipy.misc.lena().astype(np.float) + >>> lena += 0.5 * lena.std()*np.random.randn(*lena.shape) + >>> denoised_lena = tv_denoise(lena, weight=60.0) + """ + im_type = im.dtype + if im_type is not np.float: + im = im.astype(np.float) + px = np.zeros_like(im) + py = np.zeros_like(im) + gx = np.zeros_like(im) + gy = np.zeros_like(im) + d = np.zeros_like(im) + i = 0 + while i < n_iter_max: + d = -px -py + d[1:] += px[:-1] + d[:, 1:] += py[:, :-1] + + out = im + d + E = (d**2).sum() + gx[:-1] = np.diff(out, axis=0) + gy[:, :-1] = np.diff(out, axis=1) + norm = np.sqrt(gx**2 + gy**2) + E += weight * norm.sum() + norm *= 0.5 / weight + norm += 1 + px -= 0.25*gx + px /= norm + py -= 0.25*gy + py /= norm + E /= float(im.size) + if i == 0: + E_init = E + E_previous = E + else: + if np.abs(E_previous - E) < eps * E_init: + break + else: + E_previous = E + i += 1 + if keep_type: + return out.astype(im_type) + else: + return out + +def tv_denoise(im, weight=50, eps=2.e-4, keep_type=False, n_iter_max=200): + """ + Perform total-variation denoising on 2-d and 3-d images + + Parameters + ---------- + im: ndarray (2d or 3d) of ints, uints or floats + input data to be denoised. `im` can be of any numeric type, + but it is cast into an ndarray of floats for the computation + of the denoised image. + + weight: float, optional + denoising weight. The greater ``weight``, the more denoising (at + the expense of fidelity to ``input``) + + eps: float, optional + relative difference of the value of the cost function that + determines the stop criterion. The algorithm stops when: + + (E_(n-1) - E_n) < eps * E_0 + + keep_type: bool, optional (False) + whether the output has the same dtype as the input array. + keep_type is False by default, and the dtype of the output + is np.float + + n_iter_max: int, optional + maximal number of iterations used for the optimization. + + Returns + ------- + out: ndarray + denoised array + + + Notes + ----- + The principle of total variation denoising is explained in + http://en.wikipedia.org/wiki/Total_variation_denoising + + The principle of total variation denoising is to minimize the + total variation of the image, which can be roughly described as + the integral of the norm of the image gradient. Total variation + denoising tends to produce "cartoon-like" images, that is, + piecewise-constant images. + + This code is an implementation of the algorithm of Rudin, Fatemi and Osher + that was proposed by Chambolle in [1]_. + + References + ---------- + + .. [1] A. Chambolle, An algorithm for total variation minimization and + applications, Journal of Mathematical Imaging and Vision, + Springer, 2004, 20, 89-97. + + Examples + --------- + >>> import scipy + >>> # 2D example using lena + >>> lena = scipy.misc.lena().astype(np.float) + >>> lena += 0.5 * lena.std()*np.random.randn(*lena.shape) + >>> denoised_lena = tv_denoise(lena, weight=60) + >>> # 3D example on synthetic data + >>> x, y, z = np.ogrid[0:40, 0:40, 0:40] + >>> mask = (x -22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2 + >>> mask = mask.astype(np.float) + >>> mask += 0.2*np.random.randn(*mask.shape) + >>> res = tv_denoise_3d(mask, weight=100) + """ + + if im.ndim == 2: + return _tv_denoise_2d(im, weight, eps, keep_type, n_iter_max) + elif im.ndim == 3: + return _tv_denoise_3d(im, weight, eps, keep_type, n_iter_max) + else: + raise ValueError('only 2-d and 3-d images may be denoised with this function') + diff --git a/advanced/image_processing/auto_examples/tv_denoise.rst b/advanced/image_processing/auto_examples/tv_denoise.rst new file mode 100644 index 0000000..af55651 --- /dev/null +++ b/advanced/image_processing/auto_examples/tv_denoise.rst @@ -0,0 +1,11 @@ + + +.. _example_tv_denoise.py: + + + +**Python source code:** :download:`tv_denoise.py ` + +.. literalinclude:: tv_denoise.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/image_processing/examples/plot_lena.py b/advanced/image_processing/examples/plot_lena.py index 8ec077a..64ffbda 100644 --- a/advanced/image_processing/examples/plot_lena.py +++ b/advanced/image_processing/examples/plot_lena.py @@ -3,5 +3,6 @@ l = misc.lena() misc.imsave('lena.png', l) # uses the Image module (PIL) -import pylab as pl -pl.imshow(l) +import matplotlib.pyplot as plt +plt.imshow(l) +plt.show() diff --git a/advanced/image_processing/examples/plot_lena_tv_denoise.py b/advanced/image_processing/examples/plot_lena_tv_denoise.py index 401e718..e60b0d5 100644 --- a/advanced/image_processing/examples/plot_lena_tv_denoise.py +++ b/advanced/image_processing/examples/plot_lena_tv_denoise.py @@ -1,8 +1,7 @@ import numpy as np import scipy import matplotlib.pyplot as plt -# from scikits.image.filter import tv_denoise -from tv_denoise import tv_denoise +from skimage.filter import tv_denoise l = scipy.misc.lena() l = l[230:290, 220:320] diff --git a/advanced/image_processing/examples/plot_spectral_clustering.py b/advanced/image_processing/examples/plot_spectral_clustering.py index 3aa466e..20c462d 100644 --- a/advanced/image_processing/examples/plot_spectral_clustering.py +++ b/advanced/image_processing/examples/plot_spectral_clustering.py @@ -34,11 +34,11 @@ # Take a decreasing function of the gradient: we take it weakly # dependant from the gradient the segmentation is close to a voronoi -graph.data = np.exp(-graph.data/graph.data.std()) +graph.data = np.exp(-graph.data / graph.data.std()) # Force the solver to be arpack, since amg is numerically # unstable on this example -labels = spectral_clustering(graph, n_clusters=4, mode='arpack') +labels = spectral_clustering(graph, k=4) label_im = -np.ones(mask.shape) label_im[mask] = labels diff --git a/advanced/image_processing/examples/plot_watershed_segmentation.py b/advanced/image_processing/examples/plot_watershed_segmentation.py new file mode 100644 index 0000000..7a79dec --- /dev/null +++ b/advanced/image_processing/examples/plot_watershed_segmentation.py @@ -0,0 +1,34 @@ +import numpy as np +from skimage.morphology import watershed, is_local_maximum +import matplotlib.pyplot as plt +from scipy import ndimage + +# Generate an initial image with two overlapping circles +x, y = np.indices((80, 80)) +x1, y1, x2, y2 = 28, 28, 44, 52 +r1, r2 = 16, 20 +mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2 +mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2 +image = np.logical_or(mask_circle1, mask_circle2) +# Now we want to separate the two objects in image +# Generate the markers as local maxima of the distance +# to the background +distance = ndimage.distance_transform_edt(image) +local_maxi = is_local_maximum(distance, image, np.ones((3, 3))) +markers = ndimage.label(local_maxi)[0] +labels = watershed(-distance, markers, mask=image) + +plt.figure(figsize=(9, 3.5)) +plt.subplot(131) +plt.imshow(image, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(132) +plt.imshow(-distance, interpolation='nearest') +plt.axis('off') +plt.subplot(133) +plt.imshow(labels, cmap='spectral', interpolation='nearest') +plt.axis('off') + +plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, + right=1) +plt.show() diff --git a/advanced/image_processing/index.rst b/advanced/image_processing/index.rst index fa63a4b..424f8e3 100644 --- a/advanced/image_processing/index.rst +++ b/advanced/image_processing/index.rst @@ -2,35 +2,33 @@ >>> import numpy as np >>> np.random.seed(0) - ============================================================= Manipulación y procesamiento de imágenes usando Numpy y Scipy ============================================================= -:autores: Emmanuelle Gouillart, Gaël Varoquaux +:Autores: Emmanuelle Gouillart, Gaël Varoquaux .. topic:: - Imagen = array numérico en 2-D - - (o 3-D: TC, IRM, 2D + tiempo; 4-D, ...) + Imagen = array numérico en 2-D (o 3-D: TC, IRM, 2D + tiempo; 4-D, ...) - Aquí, **imagen == array Numpy** ``np.array`` + Aquí, **imagen == array Numpy** ``np.array`` **Herramientas usadas en este tutorial**: * ``numpy``: manipulación básica de arrays -* ``scipy``: ``scipy.ndimage`` submódulo dedicado a procesamiento de imágenes - (imágenes n-dimensionales). Ver http://docs.scipy.org/doc/scipy/reference/tutorial/ndimage.html :: +* ``scipy``: ``scipy.ndimage`` submódulo dedicado a procesamiento de imágenes (imágenes n-dimensionales). Ver http://docs.scipy.org/doc/scipy/reference/tutorial/ndimage.html - >>> from scipy import ndimage + .. code-block:: python + + >>> from scipy import ndimage * algunos ejemplos usan librerías especializadas que hacen uso de ``np.array``: - * `Scikit Image `_ + * `Scikit Image `_ - * `scikit-learn `_ + * `scikit-learn `_ **Tareas comunes en procesamiento de imágenes**: @@ -50,7 +48,6 @@ Manipulación y procesamiento de imágenes usando Numpy y Scipy * ... - Existen módulos más potentes y completos: * `OpenCV `_ @@ -62,12 +59,10 @@ Existen módulos más potentes y completos: * muchos más... -.. contents:: Contenidos del capítulo +.. contents:: Contenido :local: :depth: 4 - - Abriendo y escribiendo archivos de imágenes =========================================== @@ -77,116 +72,130 @@ Escribiendo un array a un archivo: :lines: 2- .. image:: examples/lena.png - :align: center - :scale: 50 + :align: center + :scale: 50 +Creando un array numpy desde un archivo de imagen -Creando un array numpy desde un archivo de imagen:: +.. code-block:: python - >>> lena = misc.imread('lena.png') - >>> type(lena) - - >>> lena.shape, lena.dtype - ((512, 512), dtype('uint8')) + >>> lena = misc.imread('lena.png') + >>> type(lena) + + >>> lena.shape, lena.dtype + ((512, 512), dtype('uint8')) dtype es uint8 para imágenes de 8-bits (0-255) -Abriendo archivos `raw` (de cámara, imágenes 3-D) :: +Abriendo archivos `raw` (de cámara, imágenes 3-D) - >>> l.tofile('lena.raw') # Creación de un fichero raw - >>> lena_from_raw = np.fromfile('lena.raw', dtype=np.int64) - >>> lena_from_raw.shape - (262144,) - >>> lena_from_raw.shape = (512, 512) - >>> import os - >>> os.remove('lena.raw') +.. code-block:: python + + >>> l.tofile('lena.raw') # Creación de un fichero raw + >>> lena_from_raw = np.fromfile('lena.raw', dtype=np.int64) + >>> lena_from_raw.shape + (262144,) + >>> lena_from_raw.shape = (512, 512) + >>> import os + >>> os.remove('lena.raw') Necesitas saber la forma y el dtype (tipo de dato) de la imagen (de qué forma separar los bytes de datos). Para conjuntos de datos de gran tamaño se puede usar ``np.memmap``, que -sirve para `mapear` en memoria estos datos:: +sirve para `mapear` en memoria estos datos + +.. code-block:: python - >>> lena_memmap = np.memmap('lena.raw', dtype=np.int64, shape=(512, 512)) + >>> lena_memmap = np.memmap('lena.raw', dtype=np.int64, shape=(512, 512)) (los datos son leídos desde el archivo, pero no son cargados en la memoria) -Trabajando en una lista de archivos de imágenes:: +Trabajando en una lista de archivos de imágenes - >>> for i in range(10): - ... im = np.random.random_integers(0, 255, 10000).reshape((100, 100)) - ... misc.imsave('random_%02d.png' % i, im) - >>> from glob import glob - >>> filelist = glob('random*.png') - >>> filelist.sort() +.. code-block:: python + + >>> for i in range(10): + ... im = np.random.random_integers(0, 255, 10000).reshape((100, 100)) + ... misc.imsave('random_%02d.png' % i, im) + >>> from glob import glob + >>> filelist = glob('random*.png') + >>> filelist.sort() Mostrando imágenes ================== -Se puede usar ``matplotlib`` e ``imshow`` para mostrar una imagen dentro de una -``figura matplotlib``:: +Se puede usar ``matplotlib`` e ``imshow`` para mostrar una imagen dentro de una ``figura matplotlib`` + +.. code-block:: python - >>> l = scipy.lena() - >>> import matplotlib.pyplot as plt - >>> plt.imshow(l, cmap=plt.cm.gray) - + >>> l = scipy.lena() + >>> import matplotlib.pyplot as plt + >>> plt.imshow(l, cmap=plt.cm.gray) + -Podemos incrementar el contraste ajustando los valores mínimos y máximos:: +Podemos incrementar el contraste ajustando los valores mínimos y máximos - >>> plt.imshow(l, cmap=plt.cm.gray, vmin=30, vmax=200) - - >>> # Remove axes and ticks - >>> plt.axis('off') - (-0.5, 511.5, 511.5, -0.5) +.. code-block:: python -Podemos dibujar las líneas de contorno:: + >>> plt.imshow(l, cmap=plt.cm.gray, vmin=30, vmax=200) + + >>> # Remove axes and ticks + >>> plt.axis('off') + (-0.5, 511.5, 511.5, -0.5) - >>> plt.contour(l, [60, 211]) - +Podemos dibujar las líneas de contorno +.. code-block:: python + + >>> plt.contour(l, [60, 211]) + .. figure:: auto_examples/images/plot_display_lena_1.png - :scale: 100 - :target: auto_examples/plot_display_lena.html + :scale: 100 + :target: auto_examples/plot_display_lena.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] Para hacer una inspección detallada de variaciones de intensidad podemos usar -``interpolation='nearest'``:: +``interpolation='nearest'`` + +.. code-block:: python - >>> plt.imshow(l[200:220, 200:220], cmap=plt.cm.gray) - >>> plt.imshow(l[200:220, 200:220], cmap=plt.cm.gray, interpolation='nearest') + >>> plt.imshow(l[200:220, 200:220], cmap=plt.cm.gray) + >>> plt.imshow(l[200:220, 200:220], cmap=plt.cm.gray, interpolation='nearest') .. figure:: auto_examples/images/plot_interpolation_lena_1.png - :scale: 80 - :target: auto_examples/plot_interpolation_lena.html + :scale: 80 + :target: auto_examples/plot_interpolation_lena.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] -A veces, otros paquetes usan paquetes o `toolkits` para visualización (GTK, Qt):: +A veces, otros paquetes usan paquetes o `toolkits` para visualización (GTK, Qt) - >>> import scikits.image.io as im_io - >>> im_io.use_plugin('gtk', 'imshow') - >>> im_io.imshow(l) +.. code-block:: python + + >>> import scikits.image.io as im_io + >>> im_io.use_plugin('gtk', 'imshow') + >>> im_io.imshow(l) .. topic:: Visualización en 3-D: Mayavi - Ver :ref:`mayavi-label` y :ref:`mayavi-voldata-label`. + Ver :ref:`mayavi-label` y :ref:`mayavi-voldata-label`. - * Widget para planos de imagen - - * Isosuperficies + * Widget para planos de imagen - * ... + * Isosuperficies - .. image:: ../3d_plotting/ipw.png - :align: center - :scale: 65 + * ... + .. image:: ../3d_plotting/ipw.png + :align: center + :scale: 65 Manipulaciones básicas ====================== @@ -194,99 +203,91 @@ Manipulaciones básicas Las imágenes las leemos usando arrays numpy: ¡Podemos usar toda la maquinaria ``numpy``! .. image:: axis_convention.png - :align: center - :scale: 65 - -:: - - >>> lena = scipy.lena() - >>> lena[0, 40] - 166 - >>> # Slicing - >>> lena[10:13, 20:23] - array([[158, 156, 157], - [157, 155, 155], - [157, 157, 158]]) - >>> lena[100:120] = 255 - >>> - >>> lx, ly = lena.shape - >>> X, Y = np.ogrid[0:lx, 0:ly] - >>> mask = (X - lx/2)**2 + (Y - ly/2)**2 > lx*ly/4 - >>> # Masks - >>> lena[mask] = 0 - >>> # Fancy indexing - >>> lena[range(400), range(400)] = 255 + :align: center + :scale: 65 + +.. code-block:: python + + >>> lena = scipy.lena() + >>> lena[0, 40] + 166 + >>> # Slicing + >>> lena[10:13, 20:23] + array([[158, 156, 157], + [157, 155, 155], + [157, 157, 158]]) + >>> lena[100:120] = 255 + >>> + >>> lx, ly = lena.shape + >>> X, Y = np.ogrid[0:lx, 0:ly] + >>> mask = (X - lx/2)**2 + (Y - ly/2)**2 > lx*ly/4 + >>> # Masks + >>> lena[mask] = 0 + >>> # Fancy indexing + >>> lena[range(400), range(400)] = 255 .. figure:: auto_examples/images/plot_numpy_array_1.png - :scale: 100 - :target: auto_examples/plot_numpy_array.html + :scale: 100 + :target: auto_examples/plot_numpy_array.html .. only:: html - [:ref:`Python source code `] - + [:ref:`Python source code `] Información estadística ----------------------- -:: - - >>> lena = scipy.lena() - >>> lena.mean() - 124.04678344726562 - >>> lena.max(), lena.min() - (245, 25) +.. code-block:: python + >>> lena = scipy.lena() + >>> lena.mean() + 124.04678344726562 + >>> lena.max(), lena.min() + (245, 25) ``np.histogram`` .. topic:: - **Ejercicio 1** - - * Abrimos el logo ``scikit-image`` como imagen - (http://scikit-image.org/_static/scikits_image_logo.png), o una - imagen que tengas en tu computadora. + **Ejercicio 1** - * Recortar una parte significativa de la imagen, por ejemplo, el círculo - con la python en el logo. + * Abrimos el logo ``scikit-image`` como imagen (http://scikit-image.org/_static/scikits_image_logo.png), o una imagen que tengas en tu computadora. - * Mostrar el array de la imagen usando ``matlplotlib``. Cambia el método de interpolación - y haz zoom para ver la diferencia. + * Recortar una parte significativa de la imagen, por ejemplo, el círculo con la python en el logo. - * Transforma tu imagen a escala de grises. + * Mostrar el array de la imagen usando ``matlplotlib``. Cambia el método de interpolación y haz zoom para ver la diferencia. - * Incrementa el contraste de la imagen cambiando sus valores máximo y mínimo. - **Optional**: usa ``scipy.stats.scoreatpercentile`` - (¡lee el docstring!) para saturar un 5% los píxeles más oscuros y un 5% - los píxeles más claros. + * Transforma tu imagen a escala de grises. - * Guarda el array a los diferentes formatos de imagen (png, jpg, tiff) + * Incrementa el contraste de la imagen cambiando sus valores máximo y mínimo. + **Optional**: usa ``scipy.stats.scoreatpercentile`` (¡lee el docstring!) para saturar un 5% los píxeles más oscuros y un 5% los píxeles más claros. - .. image:: scikits_image_logo.png - :align: center + * Guarda el array a los diferentes formatos de imagen (png, jpg, tiff) + .. image:: scikits_image_logo.png + :align: center Transformaciones geométricas ---------------------------- -:: - - >>> lena = scipy.lena() - >>> lx, ly = lena.shape - >>> # Recorte de la imagen - >>> crop_lena = lena[lx/4:-lx/4, ly/4:-ly/4] - >>> # up <-> down flip - >>> flip_ud_lena = np.flipud(lena) - >>> # rotación - >>> rotate_lena = ndimage.rotate(lena, 45) - >>> rotate_lena_noreshape = ndimage.rotate(lena, 45, reshape=False) + +.. code-block:: python + + >>> lena = scipy.lena() + >>> lx, ly = lena.shape + >>> # Recorte de la imagen + >>> crop_lena = lena[lx/4:-lx/4, ly/4:-ly/4] + >>> # up <-> down flip + >>> flip_ud_lena = np.flipud(lena) + >>> # rotación + >>> rotate_lena = ndimage.rotate(lena, 45) + >>> rotate_lena_noreshape = ndimage.rotate(lena, 45, reshape=False) .. figure:: auto_examples/images/plot_geom_lena_1.png - :scale: 80 - :target: auto_examples/plot_geom_lena.html + :scale: 80 + :target: auto_examples/plot_geom_lena.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] Filtrado de imágenes ==================== @@ -297,102 +298,115 @@ valores de los pixeles vecinos. Vecindad: cuadrado (selecciona el tamaño), círculo o *elementos estructurados* más complejos*. .. image:: kernels.png - :align: center + :align: center Desenfoque/suavizado -------------------- -**Filtro gaussiano** de ``scipy.ndimage``:: +**Filtro gaussiano** de ``scipy.ndimage`` - >>> from scipy import misc - >>> lena = misc.lena() - >>> blurred_lena = ndimage.gaussian_filter(lena, sigma=3) - >>> very_blurred = ndimage.gaussian_filter(lena, sigma=5) +.. code-block:: python -**Filtro uniforme** :: + >>> from scipy import misc + >>> lena = misc.lena() + >>> blurred_lena = ndimage.gaussian_filter(lena, sigma=3) + >>> very_blurred = ndimage.gaussian_filter(lena, sigma=5) - >>> local_mean = ndimage.uniform_filter(lena, size=11) +**Filtro uniforme** + +.. code-block:: python + + >>> local_mean = ndimage.uniform_filter(lena, size=11) .. figure:: auto_examples/images/plot_blur_1.png - :scale: 80 - :target: auto_examples/plot_blur.html + :scale: 80 + :target: auto_examples/plot_blur.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] enfoque/refinamiento (`sharpening`) ----------------------------------- -Enfocar una imagen borrosa:: +Enfocar una imagen borrosa + +.. code-block:: python + + >>> from scipy import misc + >>> lena = misc.lena() + >>> blurred_l = ndimage.gaussian_filter(lena, 3) - >>> from scipy import misc - >>> lena = misc.lena() - >>> blurred_l = ndimage.gaussian_filter(lena, 3) +Incrementamos el peso de los bordes agregando una aproximación del laplaciano -Incrementamos el peso de los bordes agregando una aproximación del laplaciano:: +.. code-block:: python - >>> filter_blurred_l = ndimage.gaussian_filter(blurred_l, 1) - >>> alpha = 30 - >>> sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l) + >>> filter_blurred_l = ndimage.gaussian_filter(blurred_l, 1) + >>> alpha = 30 + >>> sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l) .. figure:: auto_examples/images/plot_sharpen_1.png - :scale: 100 - :target: auto_examples/plot_sharpen.html + :scale: 100 + :target: auto_examples/plot_sharpen.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] Reduciendo ruido ---------------- -Imagen de Lena con ruido:: +Imagen de Lena con ruido - >>> from scipy import misc - >>> l = misc.lena() - >>> l = l[230:310, 210:350] - >>> noisy = l + 0.4*l.std()*np.random.random(l.shape) +.. code-block:: python -Un **filtro gaussiano** suaviza la imagen `eliminando` el ruido... además de los bordes:: + >>> from scipy import misc + >>> l = misc.lena() + >>> l = l[230:310, 210:350] + >>> noisy = l + 0.4*l.std()*np.random.random(l.shape) - >>> gauss_denoised = ndimage.gaussian_filter(noisy, 2) +Un **filtro gaussiano** suaviza la imagen `eliminando` el ruido... además de los bordes -La mayoría de los filtros lineales isotrópicos locales -(``ndimage.uniform_filter``) desenfocan la imagen. +.. code-block:: python -Un **filtro de mediana** conserva mejor los bordes:: + >>> gauss_denoised = ndimage.gaussian_filter(noisy, 2) - >>> med_denoised = ndimage.median_filter(noisy, 3) +La mayoría de los filtros lineales isotrópicos locales (``ndimage.uniform_filter``) desenfocan la imagen. + +Un **filtro de mediana** conserva mejor los bordes + +.. code-block:: python + + >>> med_denoised = ndimage.median_filter(noisy, 3) .. figure:: auto_examples/images/plot_lena_denoise_1.png - :scale: 60 - :target: auto_examples/plot_lena_denoise.html + :scale: 60 + :target: auto_examples/plot_lena_denoise.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] + +Filtro de mediana: mejor resultado para zonas de frontera rectas (**baja curvatura**) -Filtro de mediana: mejor resultado para zonas de frontera rectas (**baja curvatura**):: +.. code-block:: python - >>> im = np.zeros((20, 20)) - >>> im[5:-5, 5:-5] = 1 - >>> im = ndimage.distance_transform_bf(im) - >>> im_noise = im + 0.2*np.random.randn(*im.shape) - >>> im_med = ndimage.median_filter(im_noise, 3) + >>> im = np.zeros((20, 20)) + >>> im[5:-5, 5:-5] = 1 + >>> im = ndimage.distance_transform_bf(im) + >>> im_noise = im + 0.2*np.random.randn(*im.shape) + >>> im_med = ndimage.median_filter(im_noise, 3) .. figure:: auto_examples/images/plot_denoising_1.png - :scale: 60 - :target: auto_examples/plot_denoising.html + :scale: 60 + :target: auto_examples/plot_denoising.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] - -Otros filtros de rango: ``ndimage.maximum_filter``, -``ndimage.percentile_filter`` +Otros filtros de rango: ``ndimage.maximum_filter``, ``ndimage.percentile_filter`` Otros filtros no lineales locales: Wiener (``scipy.signal.wiener``), etc. @@ -401,37 +415,34 @@ Otros filtros no lineales locales: Wiener (``scipy.signal.wiener``), etc. **Reducción de ruido de variación total (TV, Total Variation)**. Encuentra una nueva imagen donde la variación total de la imagen (integral de la norma L1 del gradiente) es minimizada al avez que el resultado se mantiene cercano a la imagen -medida:: +medida + +.. code-block:: python - >>> from skimage.filter import tv_denoise - >>> tv_denoised = tv_denoise(noisy, weight=10) - >>> # More denoising (to the expense of fidelity to data) - >>> tv_denoised = tv_denoise(noisy, weight=50) + >>> from skimage.filter import tv_denoise + >>> tv_denoised = tv_denoise(noisy, weight=10) + >>> # More denoising (to the expense of fidelity to data) + >>> tv_denoised = tv_denoise(noisy, weight=50) .. figure:: auto_examples/images/plot_lena_tv_denoise_1.png - :scale: 60 - :target: auto_examples/plot_lena_tv_denoise.html + :scale: 60 + :target: auto_examples/plot_lena_tv_denoise.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] .. topic:: - Ejercicio 2: Reducción de ruido - - * Creamos una imagen binaria (de unos y ceros) con varios objetos (círculos, - elipses, cuadrados o formas aleatorias). + Ejercicio 2: Reducción de ruido - * Añadimos algo de ruido (e.g., 20% de ruido) + * Creamos una imagen binaria (de unos y ceros) con varios objetos (círculos, elipses, cuadrados o formas aleatorias). - * Elige tres métodos para reducir el ruido de la imagen: - filtro gaussiano, filtro de la media y el filtro de variación - total. + * Añadimos algo de ruido (e.g., 20% de ruido) - * Compara los histogramas de las tres imágenes a las que se ha aplicado una reducción de ruido. - ¿Qué histograma es el más cercano al de la imagen original (imagen libre de ruido)? + * Elige tres métodos para reducir el ruido de la imagen: filtro gaussiano, filtro de la media y el filtro de variación total. + * Compara los histogramas de las tres imágenes a las que se ha aplicado una reducción de ruido. ¿Qué histograma es el más cercano al de la imagen original (imagen libre de ruido)? Morfología matemática --------------------- @@ -441,142 +452,150 @@ Ver http://en.wikipedia.org/wiki/Mathematical_morphology Prueba una imagen con una forma simple (un **elemento con estructura**) y modifica esta imagen de acuerdo a como se ajuste o no a la imagen. -**Elemento con estructura**:: +**Elemento con estructura** - >>> el = ndimage.generate_binary_structure(2, 1) - >>> el - array([[False, True, False], - [ True, True, True], - [False, True, False]], dtype=bool) - >>> el.astype(np.int) - array([[0, 1, 0], - [1, 1, 1], - [0, 1, 0]]) +.. code-block:: python -.. image:: diamond_kernel.png - :align: center - -**Erosión** = filtro mínimo. Reemplaza el valor de un pixel por el valor mínimo del elemento estructurado:: - - >>> a = np.zeros((7,7), dtype=np.int) - >>> a[1:6, 2:5] = 1 - >>> a - array([[0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 0, 0, 0, 0, 0]]) - >>> ndimage.binary_erosion(a).astype(a.dtype) - array([[0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 1, 0, 0, 0], - [0, 0, 0, 1, 0, 0, 0], - [0, 0, 0, 1, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0]]) - >>> #Erosion elimina objectos más pequeños que la estructura - >>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) - array([[0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0]]) + >>> el = ndimage.generate_binary_structure(2, 1) + >>> el + array([[False, True, False], + [ True, True, True], + [False, True, False]], dtype=bool) + >>> el.astype(np.int) + array([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]]) +.. image:: diamond_kernel.png + :align: center + +**Erosión** = filtro mínimo. Reemplaza el valor de un pixel por el valor mínimo del elemento estructurado + +.. code-block:: python + + >>> a = np.zeros((7,7), dtype=np.int) + >>> a[1:6, 2:5] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.binary_erosion(a).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> #Erosion elimina objectos más pequeños que la estructura + >>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) .. image:: morpho_mat.png - :align: center + :align: center +**Dilatación**: filtro máximo -**Dilatación**: filtro máximo:: +.. code-block:: python - >>> a = np.zeros((5, 5)) - >>> a[2, 2] = 1 - >>> a - array([[ 0., 0., 0., 0., 0.], - [ 0., 0., 0., 0., 0.], - [ 0., 0., 1., 0., 0.], - [ 0., 0., 0., 0., 0.], - [ 0., 0., 0., 0., 0.]]) - >>> ndimage.binary_dilation(a).astype(a.dtype) - array([[ 0., 0., 0., 0., 0.], - [ 0., 0., 1., 0., 0.], - [ 0., 1., 1., 1., 0.], - [ 0., 0., 1., 0., 0.], - [ 0., 0., 0., 0., 0.]]) + >>> a = np.zeros((5, 5)) + >>> a[2, 2] = 1 + >>> a + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(a).astype(a.dtype) + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.]]) +También funciona para imágenes en escala de grises -También funciona para imágenes en escala de grises:: +.. code-block:: python - >>> np.random.seed(2) - >>> x, y = (63*np.random.random((2, 8))).astype(np.int) - >>> im[x, y] = np.arange(8) + >>> np.random.seed(2) + >>> x, y = (63*np.random.random((2, 8))).astype(np.int) + >>> im[x, y] = np.arange(8) - >>> bigger_points = ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) - - >>> square = np.zeros((16, 16)) - >>> square[4:-4, 4:-4] = 1 - >>> dist = ndimage.distance_transform_bf(square) - >>> dilate_dist = ndimage.grey_dilation(dist, size=(3, 3), \ - ... structure=np.ones((3, 3))) + >>> bigger_points = ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) + >>> square = np.zeros((16, 16)) + >>> square[4:-4, 4:-4] = 1 + >>> dist = ndimage.distance_transform_bf(square) + >>> dilate_dist = ndimage.grey_dilation(dist, size=(3, 3), \ + ... structure=np.ones((3, 3))) .. figure:: auto_examples/images/plot_greyscale_dilation_1.png - :scale: 40 - :target: auto_examples/plot_greyscale_dilation.html + :scale: 40 + :target: auto_examples/plot_greyscale_dilation.html .. only:: html - [:ref:`Python source code `] - -**Opening (Apertura)**: erosión + dilatación:: - - >>> a = np.zeros((5,5), dtype=np.int) - >>> a[1:4, 1:4] = 1; a[4, 4] = 1 - >>> a - array([[0, 0, 0, 0, 0], - [0, 1, 1, 1, 0], - [0, 1, 1, 1, 0], - [0, 1, 1, 1, 0], - [0, 0, 0, 0, 1]]) - >>> # Opening removes small objects - >>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(np.int) - array([[0, 0, 0, 0, 0], - [0, 1, 1, 1, 0], - [0, 1, 1, 1, 0], - [0, 1, 1, 1, 0], - [0, 0, 0, 0, 0]]) - >>> # Opening can also smooth corners - >>> ndimage.binary_opening(a).astype(np.int) - array([[0, 0, 0, 0, 0], - [0, 0, 1, 0, 0], - [0, 1, 1, 1, 0], - [0, 0, 1, 0, 0], - [0, 0, 0, 0, 0]]) - -**Aplicación (Application)**: eliminar ruido:: - - >>> square = np.zeros((32, 32)) - >>> square[10:-10, 10:-10] = 1 - >>> np.random.seed(2) - >>> x, y = (32*np.random.random((2, 20))).astype(np.int) - >>> square[x, y] = 1 - - >>> open_square = ndimage.binary_opening(square) - - >>> eroded_square = ndimage.binary_erosion(square) - >>> reconstruction = ndimage.binary_propagation(eroded_square, mask=square) + [:ref:`Python source code `] + +**Opening (Apertura)**: erosión + dilatación + +.. code-block:: python + + >>> a = np.zeros((5,5), dtype=np.int) + >>> a[1:4, 1:4] = 1; a[4, 4] = 1 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 1]]) + >>> # Opening removes small objects + >>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(np.int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Opening can also smooth corners + >>> ndimage.binary_opening(a).astype(np.int) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + +**Aplicación (Application)**: eliminar ruido + +.. code-block:: python + + >>> square = np.zeros((32, 32)) + >>> square[10:-10, 10:-10] = 1 + >>> np.random.seed(2) + >>> x, y = (32*np.random.random((2, 20))).astype(np.int) + >>> square[x, y] = 1 + + >>> open_square = ndimage.binary_opening(square) + + >>> eroded_square = ndimage.binary_erosion(square) + >>> reconstruction = ndimage.binary_propagation(eroded_square, mask=square) .. figure:: auto_examples/images/plot_propagation_1.png - :scale: 40 - :target: auto_examples/plot_propagation.html + :scale: 40 + :target: auto_examples/plot_propagation.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] **Cierre (Closing)**: dilatación + erosión @@ -586,52 +605,54 @@ manteniendo la misma topología Existen muchas otras operaciones matemáticas de morfología: ``hit and miss transform``, tophat, etc. - Extracción de patrones ====================== Detección de borde ------------------ -Datos sintéticos:: +Datos sintéticos - >>> im = np.zeros((256, 256)) - >>> im[64:-64, 64:-64] = 1 - >>> - >>> im = ndimage.rotate(im, 15, mode='constant') - >>> im = ndimage.gaussian_filter(im, 8) +.. code-block:: python -Usa un **operador gradiente** (**Sobel**) para encontrar altas variaciones de intensidad:: + >>> im = np.zeros((256, 256)) + >>> im[64:-64, 64:-64] = 1 + >>> + >>> im = ndimage.rotate(im, 15, mode='constant') + >>> im = ndimage.gaussian_filter(im, 8) - >>> sx = ndimage.sobel(im, axis=0, mode='constant') - >>> sy = ndimage.sobel(im, axis=1, mode='constant') - >>> sob = np.hypot(sx, sy) +Usa un **operador gradiente** (**Sobel**) para encontrar altas variaciones de intensidad + +.. code-block:: python + + >>> sx = ndimage.sobel(im, axis=0, mode='constant') + >>> sy = ndimage.sobel(im, axis=1, mode='constant') + >>> sob = np.hypot(sx, sy) .. figure:: auto_examples/images/plot_find_edges_1.png - :scale: 40 - :target: auto_examples/plot_find_edges.html + :scale: 40 + :target: auto_examples/plot_find_edges.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] **Filtro de Canny** -:: +.. code-block:: python - >>> from skimage.filter import canny - >>> im += 0.1*np.random.random(im.shape) - >>> edges = canny(im, 1, 0.4, 0.2) # not enough smoothing - >>> edges = canny(im, 3, 0.3, 0.2) # better parameters + >>> from skimage.filter import canny + >>> im += 0.1*np.random.random(im.shape) + >>> edges = canny(im, 1, 0.4, 0.2) # not enough smoothing + >>> edges = canny(im, 3, 0.3, 0.2) # better parameters .. figure:: auto_examples/images/plot_canny_1.png - :scale: 40 - :target: auto_examples/plot_canny.html + :scale: 40 + :target: auto_examples/plot_canny.html .. only:: html - [:ref:`Python source code `] - + [:ref:`Python source code `] Se necesitan ajustar varios parámetros... riesgo de sobreajuste. @@ -640,350 +661,357 @@ Segmentación * Segmentación **basada en histograma** (sin información espacial) -:: + .. code-block:: python - >>> n = 10 - >>> l = 256 - >>> im = np.zeros((l, l)) - >>> np.random.seed(1) - >>> points = l*np.random.random((2, n**2)) - >>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 - >>> im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + >>> n = 10 + >>> l = 256 + >>> im = np.zeros((l, l)) + >>> np.random.seed(1) + >>> points = l*np.random.random((2, n**2)) + >>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 + >>> im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) - >>> mask = (im > im.mean()).astype(np.float) - >>> mask += 0.1 * im - >>> img = mask + 0.2*np.random.randn(*mask.shape) + >>> mask = (im > im.mean()).astype(np.float) + >>> mask += 0.1 * im + >>> img = mask + 0.2*np.random.randn(*mask.shape) - >>> hist, bin_edges = np.histogram(img, bins=60) - >>> bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:]) + >>> hist, bin_edges = np.histogram(img, bins=60) + >>> bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:]) - >>> binary_img = img > 0.5 + >>> binary_img = img > 0.5 .. figure:: auto_examples/images/plot_histo_segmentation_1.png - :scale: 65 - :target: auto_examples/plot_histo_segmentation.html + :scale: 65 + :target: auto_examples/plot_histo_segmentation.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] + +Umbral automático: usa el modelo de mezcla gaussiano -Umbral automático: usa el modelo de mezcla gaussiano:: +.. code-block:: python - >>> mask = (im > im.mean()).astype(np.float) - >>> mask += 0.1 * im - >>> img = mask + 0.3*np.random.randn(*mask.shape) + >>> mask = (im > im.mean()).astype(np.float) + >>> mask += 0.1 * im + >>> img = mask + 0.3*np.random.randn(*mask.shape) - >>> from sklearn.mixture import GMM - >>> classif = GMM(n_components=2) - >>> classif.fit(img.reshape((img.size, 1))) # doctest: +ELLIPSIS - GMM(...) + >>> from sklearn.mixture import GMM + >>> classif = GMM(n_components=2) + >>> classif.fit(img.reshape((img.size, 1))) # doctest: +ELLIPSIS + GMM(...) - >>> classif.means - array([[ 0.9353155 ], - [-0.02966039]]) - >>> np.sqrt(classif.covarsi).ravel() - array([ 0.35074631, 0.28225327]) - >>> classif.weights - array([ 0.40989799, 0.59010201]) - >>> threshold = np.mean(classif.means) - >>> binary_img = img > threshold + >>> classif.means + array([[ 0.9353155 ], + [-0.02966039]]) + >>> np.sqrt(classif.covarsi).ravel() + array([ 0.35074631, 0.28225327]) + >>> classif.weights + array([ 0.40989799, 0.59010201]) + >>> threshold = np.mean(classif.means) + >>> binary_img = img > threshold .. image:: image_GMM.png - :align: center - :scale: 100 + :align: center + :scale: 100 -Usamos morfología matemática para limpiar el resultado:: +Usamos morfología matemática para limpiar el resultado - >>> # Elimina pequeñas regiones blancas - >>> open_img = ndimage.binary_opening(binary_img) - >>> # Elimina el pequeño agujero negro - >>> close_img = ndimage.binary_closing(open_img) +.. code-block:: python + + >>> # Elimina pequeñas regiones blancas + >>> open_img = ndimage.binary_opening(binary_img) + >>> # Elimina el pequeño agujero negro + >>> close_img = ndimage.binary_closing(open_img) .. figure:: auto_examples/images/plot_clean_morpho_1.png - :scale: 65 - :target: auto_examples/plot_clean_morpho.html + :scale: 65 + :target: auto_examples/plot_clean_morpho.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] .. topic:: **Ejercicio** - :class: green + :class: green + + Revisa que las operaciones de reconstrucción (erosión + propagación) produzcan un mejor resultado que apertura/cierre (`opening/closing`) - Revisa que las operaciones de reconstrucción (erosión + propagación) - produzcan un mejor resultado que apertura/cierre (`opening/closing`):: + .. code-block:: python - >>> eroded_img = ndimage.binary_erosion(binary_img) - >>> reconstruct_img = ndimage.binary_propagation(eroded_img, mask=binary_img) - >>> tmp = np.logical_not(reconstruct_img) - >>> eroded_tmp = ndimage.binary_erosion(tmp) - >>> reconstruct_final = np.logical_not(ndimage.binary_propagation(eroded_tmp, mask=tmp)) - >>> np.abs(mask - close_img).mean() - 0.014678955078125 - >>> np.abs(mask - reconstruct_final).mean() - 0.0042572021484375 + >>> eroded_img = ndimage.binary_erosion(binary_img) + >>> reconstruct_img = ndimage.binary_propagation(eroded_img, mask=binary_img) + >>> tmp = np.logical_not(reconstruct_img) + >>> eroded_tmp = ndimage.binary_erosion(tmp) + >>> reconstruct_final = np.logical_not(ndimage.binary_propagation(eroded_tmp, mask=tmp)) + >>> np.abs(mask - close_img).mean() + 0.014678955078125 + >>> np.abs(mask - reconstruct_final).mean() + 0.0042572021484375 .. topic:: **Ejercicio** - :class: green - - Revisa cómo un primer paso de reducción de ruido (filtro de mediana, - variación total) modifica el histograma y revisa que la segmentación - basada en histograma resultante es más exacta. - -* Segmentación **basada en gráficos**: usa información espacial. - -* Segmentación de **línea divisoria** (o segmentación **watershed**) - -:: - - >>> from skimage.morphology import watershed, is_local_maximum - >>> - >>> # Generate an initial image with two overlapping circles - >>> x, y = np.indices((80, 80)) - >>> x1, y1, x2, y2 = 28, 28, 44, 52 - >>> r1, r2 = 16, 20 - >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2 - >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2 - >>> image = np.logical_or(mask_circle1, mask_circle2) - >>> # Now we want to separate the two objects in image - >>> # Generate the markers as local maxima of the distance - >>> # to the background - >>> from scipy import ndimage - >>> distance = ndimage.distance_transform_edt(image) - >>> local_maxi = is_local_maximum(distance, image, np.ones((3, 3))) - >>> markers = ndimage.label(local_maxi)[0] - >>> labels = watershed(-distance, markers, mask=image) + :class: green + + Revisa cómo un primer paso de reducción de ruido (filtro de mediana, variación total) modifica el histograma y revisa que la segmentación basada en histograma resultante es más exacta. + + * Segmentación **basada en gráficos**: usa información espacial. + + * Segmentación de **línea divisoria** (o segmentación **watershed**) + + .. code-block:: python + + >>> from skimage.morphology import watershed, is_local_maximum + >>> + >>> # Generate an initial image with two overlapping circles + >>> x, y = np.indices((80, 80)) + >>> x1, y1, x2, y2 = 28, 28, 44, 52 + >>> r1, r2 = 16, 20 + >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2 + >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2 + >>> image = np.logical_or(mask_circle1, mask_circle2) + >>> # Now we want to separate the two objects in image + >>> # Generate the markers as local maxima of the distance + >>> # to the background + >>> from scipy import ndimage + >>> distance = ndimage.distance_transform_edt(image) + >>> local_maxi = is_local_maximum(distance, image, np.ones((3, 3))) + >>> markers = ndimage.label(local_maxi)[0] + >>> labels = watershed(-distance, markers, mask=image) .. figure:: auto_examples/images/plot_watershed_segmentation_1.png - :scale: 70 - :target: auto_examples/plot_watershed_segmentation.html - + :scale: 70 + :target: auto_examples/plot_watershed_segmentation.html Segmentation **Spectral clustering** (cortes normalizados) +.. code-block:: python -:: - - >>> from sklearn.feature_extraction import image - >>> from sklearn.cluster import spectral_clustering + >>> from sklearn.feature_extraction import image + >>> from sklearn.cluster import spectral_clustering - >>> l = 100 - >>> x, y = np.indices((l, l)) + >>> l = 100 + >>> x, y = np.indices((l, l)) - >>> center1 = (28, 24) - >>> center2 = (40, 50) - >>> center3 = (67, 58) - >>> center4 = (24, 70) - >>> radius1, radius2, radius3, radius4 = 16, 14, 15, 14 + >>> center1 = (28, 24) + >>> center2 = (40, 50) + >>> center3 = (67, 58) + >>> center4 = (24, 70) + >>> radius1, radius2, radius3, radius4 = 16, 14, 15, 14 - >>> circle1 = (x - center1[0])**2 + (y - center1[1])**2 < radius1**2 - >>> circle2 = (x - center2[0])**2 + (y - center2[1])**2 < radius2**2 - >>> circle3 = (x - center3[0])**2 + (y - center3[1])**2 < radius3**2 - >>> circle4 = (x - center4[0])**2 + (y - center4[1])**2 < radius4**2 + >>> circle1 = (x - center1[0])**2 + (y - center1[1])**2 < radius1**2 + >>> circle2 = (x - center2[0])**2 + (y - center2[1])**2 < radius2**2 + >>> circle3 = (x - center3[0])**2 + (y - center3[1])**2 < radius3**2 + >>> circle4 = (x - center4[0])**2 + (y - center4[1])**2 < radius4**2 - >>> # 4 círculos - >>> img = circle1 + circle2 + circle3 + circle4 - >>> mask = img.astype(bool) - >>> img = img.astype(float) + >>> # 4 círculos + >>> img = circle1 + circle2 + circle3 + circle4 + >>> mask = img.astype(bool) + >>> img = img.astype(float) - >>> img += 1 + 0.2*np.random.randn(*img.shape) - >>> # Convierte la imagen en un gráfico con el valor del gradiente - >>> # en los bordes. - >>> graph = image.img_to_graph(img, mask=mask) + >>> img += 1 + 0.2*np.random.randn(*img.shape) + >>> # Convierte la imagen en un gráfico con el valor del gradiente + >>> # en los bordes. + >>> graph = image.img_to_graph(img, mask=mask) - >>> # Usa una función decreciente del gradiente: we take it weakly - >>> # dependant from the gradient the segmentation is close to a voronoi - >>> graph.data = np.exp(-graph.data/graph.data.std()) - - >>> labels = spectral_clustering(graph, k=4, mode='arpack') - >>> label_im = -np.ones(mask.shape) - >>> label_im[mask] = labels + >>> # Usa una función decreciente del gradiente: we take it weakly + >>> # dependant from the gradient the segmentation is close to a voronoi + >>> graph.data = np.exp(-graph.data/graph.data.std()) + >>> labels = spectral_clustering(graph, k=4, mode='arpack') + >>> label_im = -np.ones(mask.shape) + >>> label_im[mask] = labels .. image:: image_spectral_clustering.png - :align: center - + :align: center Midiendo propiedades de objetos: ``ndimage.measurements`` ========================================================= -Synthetic data:: +Synthetic data + +.. code-block:: python - >>> n = 10 - >>> l = 256 - >>> im = np.zeros((l, l)) - >>> points = l*np.random.random((2, n**2)) - >>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 - >>> im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) - >>> mask = im > im.mean() + >>> n = 10 + >>> l = 256 + >>> im = np.zeros((l, l)) + >>> points = l*np.random.random((2, n**2)) + >>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 + >>> im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + >>> mask = im > im.mean() * **Análisis de componentes conectados** -Etiqueta de componentes conectados: ``ndimage.label``:: + Etiqueta de componentes conectados: ``ndimage.label`` - >>> label_im, nb_labels = ndimage.label(mask) - >>> nb_labels # how many regions? - 23 - >>> plt.imshow(label_im) # doctest: +ELLIPSIS - + .. code-block:: python -.. figure:: auto_examples/images/plot_synthetic_data_1.png - :scale: 90 - :target: auto_examples/plot_synthetic_data.html + >>> label_im, nb_labels = ndimage.label(mask) + >>> nb_labels # how many regions? + 23 + >>> plt.imshow(label_im) # doctest: +ELLIPSIS + -.. only:: html + .. figure:: auto_examples/images/plot_synthetic_data_1.png + :scale: 90 + :target: auto_examples/plot_synthetic_data.html + + .. only:: html + + [:ref:`Python source code `] + + Calcula tamaño, valor medio, etcétera, de cada región - [:ref:`Python source code `] + .. code-block:: python -Calcula tamaño, valor medio, etcétera, de cada región:: + >>> sizes = ndimage.sum(mask, label_im, range(nb_labels + 1)) + >>> mean_vals = ndimage.sum(im, label_im, range(1, nb_labels + 1)) - >>> sizes = ndimage.sum(mask, label_im, range(nb_labels + 1)) - >>> mean_vals = ndimage.sum(im, label_im, range(1, nb_labels + 1)) + Limpia componentes conectados pequeños -Limpia componentes conectados pequeños:: + .. code-block:: python - >>> mask_size = sizes < 1000 - >>> remove_pixel = mask_size[label_im] - >>> remove_pixel.shape - (256, 256) - >>> label_im[remove_pixel] = 0 - >>> plt.imshow(label_im) # doctest: +ELLIPSIS - + >>> mask_size = sizes < 1000 + >>> remove_pixel = mask_size[label_im] + >>> remove_pixel.shape + (256, 256) + >>> label_im[remove_pixel] = 0 + >>> plt.imshow(label_im) # doctest: +ELLIPSIS + -Ahora reasignamos etiquetas con ``np.searchsorted``:: + Ahora reasignamos etiquetas con ``np.searchsorted`` - >>> labels = np.unique(label_im) - >>> label_im = np.searchsorted(labels, label_im) + .. code-block:: python -.. figure:: auto_examples/images/plot_measure_data_1.png - :scale: 90 + >>> labels = np.unique(label_im) + >>> label_im = np.searchsorted(labels, label_im) + + .. figure:: auto_examples/images/plot_measure_data_1.png + :scale: 90 :target: auto_examples/plot_measure_data.html -.. only:: html + .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] -Encuentra una región de interes del objeto:: + Encuentra una región de interes del objeto - >>> slice_x, slice_y = ndimage.find_objects(label_im==4)[0] - >>> roi = im[slice_x, slice_y] - >>> plt.imshow(roi) # doctest: +ELLIPSIS - + .. code-block:: python -.. figure:: auto_examples/images/plot_find_object_1.png - :scale: 130 - :target: auto_examples/plot_find_object.html + >>> slice_x, slice_y = ndimage.find_objects(label_im==4)[0] + >>> roi = im[slice_x, slice_y] + >>> plt.imshow(roi) # doctest: +ELLIPSIS + -.. only:: html + .. figure:: auto_examples/images/plot_find_object_1.png + :scale: 130 + :target: auto_examples/plot_find_object.html - [:ref:`Python source code `] + .. only:: html -Otras mediciones espaciales: ``ndimage.center_of_mass``, -``ndimage.maximum_position``, etc. + [:ref:`Python source code `] + +Otras mediciones espaciales: ``ndimage.center_of_mass``, ``ndimage.maximum_position``, etc. Pueden ser usadas fuera del limitado campo de acción de las aplicaciones de segmentación. -Ejemplo: bloque promedio:: +Ejemplo: bloque promedio + +.. code-block:: python - >>> from scipy import misc - >>> l = misc.lena() - >>> sx, sy = l.shape - >>> X, Y = np.ogrid[0:sx, 0:sy] - >>> regions = sy/6 * (X/4) + Y/6 # note that we use broadcasting - >>> block_mean = ndimage.mean(l, labels=regions, index=np.arange(1, - ... regions.max() +1)) - >>> block_mean.shape = (sx/4, sy/6) + >>> from scipy import misc + >>> l = misc.lena() + >>> sx, sy = l.shape + >>> X, Y = np.ogrid[0:sx, 0:sy] + >>> regions = sy/6 * (X/4) + Y/6 # note that we use broadcasting + >>> block_mean = ndimage.mean(l, labels=regions, index=np.arange(1, + ... regions.max() +1)) + >>> block_mean.shape = (sx/4, sy/6) .. figure:: auto_examples/images/plot_block_mean_1.png - :scale: 70 - :target: auto_examples/plot_block_mean.html + :scale: 70 + :target: auto_examples/plot_block_mean.html .. only:: html - [:ref:`Python source code `] + [:ref:`Python source code `] -Cuando las regiones son bloques regulares, es más eficiente usar -`stride tricks` (:ref:`stride-manipulation-label`). +Cuando las regiones son bloques regulares, es más eficiente usar `stride tricks` (:ref:`stride-manipulation-label`). -Bloques no espaciados regularmente: promedio radial:: +Bloques no espaciados regularmente: promedio radial - >>> sx, sy = l.shape - >>> X, Y = np.ogrid[0:sx, 0:sy] - >>> r = np.hypot(X - sx/2, Y - sy/2) - >>> rbin = (20* r/r.max()).astype(np.int) - >>> radial_mean = ndimage.mean(l, labels=rbin, index=np.arange(1, rbin.max() +1)) +.. code-block:: python + + >>> sx, sy = l.shape + >>> X, Y = np.ogrid[0:sx, 0:sy] + >>> r = np.hypot(X - sx/2, Y - sy/2) + >>> rbin = (20* r/r.max()).astype(np.int) + >>> radial_mean = ndimage.mean(l, labels=rbin, index=np.arange(1, rbin.max() +1)) .. figure:: auto_examples/images/plot_radial_mean_1.png - :scale: 70 - :target: auto_examples/plot_radial_mean.html + :scale: 70 + :target: auto_examples/plot_radial_mean.html .. only:: html - [:ref:`Python source code `] - + [:ref:`Python source code `] .. topic:: - Ejercicio: segmentación + Ejercicio: segmentación - * Leemos la imagen de las monedas desde skimage (skimage.data.coins) como un array - o desde https://github.com/scikits-image/scikits-image/raw/master/skimage/data/coins.png + * Leemos la imagen de las monedas desde skimage (skimage.data.coins) como un array o desde https://github.com/scikits-image/scikits-image/raw/master/skimage/data/coins.png - * Mostramos el histograma e intentamos hacer una segmentación del histograma. + * Mostramos el histograma e intentamos hacer una segmentación del histograma. - * Intenta con dos métodos de segmentación: un método basado en bordes usando - ``skimage.filter.canny`` y ``scipy.ndimage.binary_fill_holes`` - y un método basado en regiones ``skimage.morphology.watershed`` - y ``skimage.filter.sobel`` para calcular un mapa de elevaciones. + * Intenta con dos métodos de segmentación: un método basado en bordes usando ``skimage.filter.canny`` y ``scipy.ndimage.binary_fill_holes`` y un método basado en regiones ``skimage.morphology.watershed`` y ``skimage.filter.sobel`` para calcular un mapa de elevaciones. - * Calcula el tamaño de las monedas. + * Calcula el tamaño de las monedas. -.. image:: coins.png - :align: center + .. image:: coins.png + :align: center * **Otras mediciones** -Función de correlación, espectro de Fourier/wavelet, etc. - -Un ejemplo con morfología matemática: **granulometría** -(http://en.wikipedia.org/wiki/Granulometry_%28morphology%29) - -:: - - >>> def disk_structure(n): - ... struct = np.zeros((2 * n + 1, 2 * n + 1)) - ... x, y = np.indices((2 * n + 1, 2 * n + 1)) - ... mask = (x - n)**2 + (y - n)**2 <= n**2 - ... struct[mask] = 1 - ... return struct.astype(np.bool) - ... - >>> - >>> def granulometry(data, sizes=None): - ... s = max(data.shape) - ... if sizes == None: - ... sizes = range(1, s/2, 2) - ... granulo = [ndimage.binary_opening(data, \ - ... structure=disk_structure(n)).sum() for n in sizes] - ... return granulo - ... - >>> - >>> np.random.seed(1) - >>> n = 10 - >>> l = 256 - >>> im = np.zeros((l, l)) - >>> points = l*np.random.random((2, n**2)) - >>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 - >>> im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) - >>> - >>> mask = im > im.mean() - >>> - >>> granulo = granulometry(mask, sizes=np.arange(2, 19, 4)) - -.. figure:: auto_examples/images/plot_granulo_1.png - :scale: 100 - :target: auto_examples/plot_granulo.html - -.. only:: html - - [:ref:`Python source code `] + Función de correlación, espectro de Fourier/wavelet, etc. + + Un ejemplo con morfología matemática: **granulometría** (http://en.wikipedia.org/wiki/Granulometry_%28morphology%29) + + .. code-block:: python + + >>> def disk_structure(n): + ... struct = np.zeros((2 * n + 1, 2 * n + 1)) + ... x, y = np.indices((2 * n + 1, 2 * n + 1)) + ... mask = (x - n)**2 + (y - n)**2 <= n**2 + ... struct[mask] = 1 + ... return struct.astype(np.bool) + ... + >>> + >>> def granulometry(data, sizes=None): + ... s = max(data.shape) + ... if sizes == None: + ... sizes = range(1, s/2, 2) + ... granulo = [ndimage.binary_opening(data, \ + ... structure=disk_structure(n)).sum() for n in sizes] + ... return granulo + ... + >>> + >>> np.random.seed(1) + >>> n = 10 + >>> l = 256 + >>> im = np.zeros((l, l)) + >>> points = l*np.random.random((2, n**2)) + >>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 + >>> im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + >>> + >>> mask = im > im.mean() + >>> + >>> granulo = granulometry(mask, sizes=np.arange(2, 19, 4)) + + .. figure:: auto_examples/images/plot_granulo_1.png + :scale: 100 + :target: auto_examples/plot_granulo.html + + .. only:: html + + [:ref:`Python source code `] diff --git a/advanced/index.rst b/advanced/index.rst index 140882d..12bb1a7 100644 --- a/advanced/index.rst +++ b/advanced/index.rst @@ -1,47 +1,19 @@ Temas avanzados =================================================================== -.. raw:: html +Esta parte de *Scipy lecture notes* está dedicado al uso avanzado. Para reforzar los conocimientos del competente programador Python para ser un experto e introducirlo en varios temas específicos. - +.. include:: ../includes/big_toc_css.rst +.. include:: ../tune_toc.rst .. toctree:: - :maxdepth: 3 advanced_python/index.rst advanced_numpy/index.rst @@ -50,7 +22,4 @@ Temas avanzados scipy_sparse/index.rst image_processing/index.rst mathematical_optimization/index.rst - traits/index.rst - 3d_plotting/index.rst - sympy.rst - scikit-learn/index.rst + interfacing_with_c/interfacing_with_c.rst diff --git a/advanced/interfacing_with_c/ctypes/cos_module.py b/advanced/interfacing_with_c/ctypes/cos_module.py new file mode 100644 index 0000000..a2dad8c --- /dev/null +++ b/advanced/interfacing_with_c/ctypes/cos_module.py @@ -0,0 +1,16 @@ +""" Example of wrapping cos function from math.h using ctypes. """ + +import ctypes +from ctypes.util import find_library + +# find and load the library +libm = ctypes.cdll.LoadLibrary(find_library('m')) +# set the argument type +libm.cos.argtypes = [ctypes.c_double] +# set the return type +libm.cos.restype = ctypes.c_double + + +def cos_func(arg): + ''' Wrapper for cos from math.h ''' + return libm.cos(arg) diff --git a/advanced/interfacing_with_c/ctypes_numpy/cos_doubles.c b/advanced/interfacing_with_c/ctypes_numpy/cos_doubles.c new file mode 120000 index 0000000..f2d10ab --- /dev/null +++ b/advanced/interfacing_with_c/ctypes_numpy/cos_doubles.c @@ -0,0 +1 @@ +../numpy_shared/cos_doubles.c \ No newline at end of file diff --git a/advanced/interfacing_with_c/ctypes_numpy/cos_doubles.h b/advanced/interfacing_with_c/ctypes_numpy/cos_doubles.h new file mode 120000 index 0000000..4b58a1b --- /dev/null +++ b/advanced/interfacing_with_c/ctypes_numpy/cos_doubles.h @@ -0,0 +1 @@ +../numpy_shared/cos_doubles.h \ No newline at end of file diff --git a/advanced/interfacing_with_c/ctypes_numpy/cos_doubles.py b/advanced/interfacing_with_c/ctypes_numpy/cos_doubles.py new file mode 100644 index 0000000..d487ac1 --- /dev/null +++ b/advanced/interfacing_with_c/ctypes_numpy/cos_doubles.py @@ -0,0 +1,21 @@ +""" Example of wrapping a C library function that accepts a C double array as + input using the numpy.ctypeslib. """ + +import numpy as np +import numpy.ctypeslib as npct +from ctypes import c_int + +# input type for the cos_doubles function +# must be a double array, with single dimension that is contiguous +array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS') + +# load the library, using numpy mechanisms +libcd = npct.load_library("libcos_doubles", ".") + +# setup the return typs and argument types +libcd.cos_doubles.restype = None +libcd.cos_doubles.argtypes = [array_1d_double, array_1d_double, c_int] + + +def cos_doubles_func(in_array, out_array): + return libcd.cos_doubles(in_array, out_array, len(in_array)) diff --git a/advanced/interfacing_with_c/ctypes_numpy/makefile b/advanced/interfacing_with_c/ctypes_numpy/makefile new file mode 100644 index 0000000..c9d2357 --- /dev/null +++ b/advanced/interfacing_with_c/ctypes_numpy/makefile @@ -0,0 +1,10 @@ +m.PHONY : clean + +libcos_doubles.so : cos_doubles.o + gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o + +cos_doubles.o : cos_doubles.c + gcc -c -fPIC cos_doubles.c -o cos_doubles.o + +clean : + -rm -vf libcos_doubles.so cos_doubles.o cos_doubles.pyc diff --git a/advanced/interfacing_with_c/ctypes_numpy/test_cos_doubles.png b/advanced/interfacing_with_c/ctypes_numpy/test_cos_doubles.png new file mode 120000 index 0000000..bf98de6 --- /dev/null +++ b/advanced/interfacing_with_c/ctypes_numpy/test_cos_doubles.png @@ -0,0 +1 @@ +../numpy_shared/test_cos_doubles.png \ No newline at end of file diff --git a/advanced/interfacing_with_c/ctypes_numpy/test_cos_doubles.py b/advanced/interfacing_with_c/ctypes_numpy/test_cos_doubles.py new file mode 120000 index 0000000..1e10f46 --- /dev/null +++ b/advanced/interfacing_with_c/ctypes_numpy/test_cos_doubles.py @@ -0,0 +1 @@ +../numpy_shared/test_cos_doubles.py \ No newline at end of file diff --git a/advanced/interfacing_with_c/cython/cos_module.pyx b/advanced/interfacing_with_c/cython/cos_module.pyx new file mode 100644 index 0000000..0d8b3f1 --- /dev/null +++ b/advanced/interfacing_with_c/cython/cos_module.pyx @@ -0,0 +1,7 @@ +""" Example of wrapping cos function from math.h using Cython. """ + +cdef extern from "math.h": + double cos(double arg) + +def cos_func(arg): + return cos(arg) diff --git a/advanced/interfacing_with_c/cython/setup.py b/advanced/interfacing_with_c/cython/setup.py new file mode 100644 index 0000000..76f1c7c --- /dev/null +++ b/advanced/interfacing_with_c/cython/setup.py @@ -0,0 +1,7 @@ +from distutils.core import setup, Extension +from Cython.Distutils import build_ext + +setup( + cmdclass={'build_ext': build_ext}, + ext_modules=[Extension("cos_module", ["cos_module.pyx"])] +) diff --git a/advanced/interfacing_with_c/cython_numpy/_cos_doubles.pyx b/advanced/interfacing_with_c/cython_numpy/_cos_doubles.pyx new file mode 100644 index 0000000..0c1056a --- /dev/null +++ b/advanced/interfacing_with_c/cython_numpy/_cos_doubles.pyx @@ -0,0 +1,21 @@ +""" Example of wrapping a C function that takes C double arrays as input using + the Numpy declarations from Cython """ + +# import both numpy and the Cython declarations for numpy +import numpy as np +cimport numpy as np + +# if you want to use the Numpy-C-API from Cython +# (not strictly necessary for this example) +np.import_array() + +# cdefine the signature of our c function +cdef extern from "cos_doubles.h": + void cos_doubles (double * in_array, double * out_array, int size) + +# create the wrapper code, with numpy type annotations +def cos_doubles_func(np.ndarray[double, ndim=1, mode="c"] in_array not None, + np.ndarray[double, ndim=1, mode="c"] out_array not None): + cos_doubles( np.PyArray_DATA(in_array), + np.PyArray_DATA(out_array), + in_array.shape[0]) diff --git a/advanced/interfacing_with_c/cython_numpy/cos_doubles.c b/advanced/interfacing_with_c/cython_numpy/cos_doubles.c new file mode 120000 index 0000000..f2d10ab --- /dev/null +++ b/advanced/interfacing_with_c/cython_numpy/cos_doubles.c @@ -0,0 +1 @@ +../numpy_shared/cos_doubles.c \ No newline at end of file diff --git a/advanced/interfacing_with_c/cython_numpy/cos_doubles.h b/advanced/interfacing_with_c/cython_numpy/cos_doubles.h new file mode 120000 index 0000000..4b58a1b --- /dev/null +++ b/advanced/interfacing_with_c/cython_numpy/cos_doubles.h @@ -0,0 +1 @@ +../numpy_shared/cos_doubles.h \ No newline at end of file diff --git a/advanced/interfacing_with_c/cython_numpy/setup.py b/advanced/interfacing_with_c/cython_numpy/setup.py new file mode 100644 index 0000000..929ec91 --- /dev/null +++ b/advanced/interfacing_with_c/cython_numpy/setup.py @@ -0,0 +1,10 @@ +from distutils.core import setup, Extension +import numpy +from Cython.Distutils import build_ext + +setup( + cmdclass={'build_ext': build_ext}, + ext_modules=[Extension("cos_doubles", + sources=["_cos_doubles.pyx", "cos_doubles.c"], + include_dirs=[numpy.get_include()])], +) diff --git a/advanced/interfacing_with_c/cython_numpy/test_cos_doubles.png b/advanced/interfacing_with_c/cython_numpy/test_cos_doubles.png new file mode 120000 index 0000000..bf98de6 --- /dev/null +++ b/advanced/interfacing_with_c/cython_numpy/test_cos_doubles.png @@ -0,0 +1 @@ +../numpy_shared/test_cos_doubles.png \ No newline at end of file diff --git a/advanced/interfacing_with_c/cython_numpy/test_cos_doubles.py b/advanced/interfacing_with_c/cython_numpy/test_cos_doubles.py new file mode 120000 index 0000000..1e10f46 --- /dev/null +++ b/advanced/interfacing_with_c/cython_numpy/test_cos_doubles.py @@ -0,0 +1 @@ +../numpy_shared/test_cos_doubles.py \ No newline at end of file diff --git a/advanced/interfacing_with_c/cython_simple/cos_module.pyx b/advanced/interfacing_with_c/cython_simple/cos_module.pyx new file mode 100644 index 0000000..594e0eb --- /dev/null +++ b/advanced/interfacing_with_c/cython_simple/cos_module.pyx @@ -0,0 +1,6 @@ +""" Simpler example of wrapping cos function from math.h using Cython. """ + +from libc.math cimport cos + +def cos_func(arg): + return cos(arg) diff --git a/advanced/interfacing_with_c/cython_simple/setup.py b/advanced/interfacing_with_c/cython_simple/setup.py new file mode 100644 index 0000000..76f1c7c --- /dev/null +++ b/advanced/interfacing_with_c/cython_simple/setup.py @@ -0,0 +1,7 @@ +from distutils.core import setup, Extension +from Cython.Distutils import build_ext + +setup( + cmdclass={'build_ext': build_ext}, + ext_modules=[Extension("cos_module", ["cos_module.pyx"])] +) diff --git a/advanced/interfacing_with_c/interfacing_with_c.rst b/advanced/interfacing_with_c/interfacing_with_c.rst new file mode 100644 index 0000000..4fcc5d0 --- /dev/null +++ b/advanced/interfacing_with_c/interfacing_with_c.rst @@ -0,0 +1,889 @@ +================== +Interfacing with C +================== + +:author: Valentin Haenel + +.. TODO:: + + * Download links + * Timing? + * Additional documentation + * What about overflow? + +.. topic:: Foreword + +This chapter contains an *introduction* to the many different routes for making +your native code (primarliy ``C/C++``) available from Python, a process +commonly referred to *wrapping*. The goal of this chapter is to give you a +flavour of what technologies exist and what their respective merits and +shortcomings are, so that you can select the appropriate one for your specific +needs. In any case, once you do start wrapping, you almost certainly will want +to consult the respective documentation for your selected technique. + +.. contents:: Chapters contents + :local: + :depth: 1 + +Introduction +============ + +This chapter covers the following techniques: + +* `Python-C-Api `_ +* `Ctypes `_ +* `SWIG (Simplified Wrapper and Interface Generator) `_ +* `Cython `_ + +These four techniques are perhaps the most well known ones, of which Cython is +probably the most advanced one and the one you should consider using first. The +others are also important, if you want to understand the wrapping problem from +different angles. Having said that, there are other alternatives out there, +but having understood the basics of the ones above, you will be in a position +to evaluate the technique of your choice to see if it fits your needs. + +The following criteria may be useful when evaluating a technology: + +* Are additional libraries required? +* Is the code autogenerated? +* Does it need to be compiled? +* Is there good support for interacting with Numpy arrays? +* Does it support C++? + +Before you set out, you should consider your use case. When interfacing with +native code, there are usually two use-cases that come up: + +* Existing code in C/C++ that needs to be leveraged, either because it already + exists, or because it is faster. +* Python code too slow, push inner loops to native code + +Each technology is demonstrated by wrapping the ``cos`` function from +``math.h``. While this is a mostly a trivial example, it should serve us well +to demonstrate the basics of the wrapping solution. Since each technique also +includes some form of Numpy support, this is also demonstrated using an +example where the cosine is computed on some kind of array. + +Last but not least, two small warnings: + +* All of these techniques may crash (segmentation fault) the Python + interpreter, which is (usually) due to bugs in the C code. +* All the examples have been done on Linux, they *should* be possible on other + operating systems. +* You will need a C compiler for most of the examples. + + +Python-C-Api +============ + +The `Python-C-API `_ is the backbone of the +standard Python interpreter (a.k.a *CPython*). Using this API it is possible to +write Python extension module in C and C++. Obviously, these extension modules +can, by virtue of language compatibility, call any function written in C or +C++. + +When using the Python-C-API, one usually writes much boilerplate code, first to +parse the arguments that were given to a function, and later to construct the +return type. + +**Advantages** + +* Requires no additional libraries +* Lots of low-level control +* Entirely usable from C++ + +**Disadvantages** + +* May requires a substantial amount of effort +* Much overhead in the code +* Must be compiled +* High maintenance cost +* No forward compatibility across Python versions as C-Api changes + +.. note:: + + The Python-C-Api example here serves mainly for didactic reasons. Many of + the other techniques actually depend on this, so it is good to have a + high-level understanding of how it works. In 99% of the use-cases you will + be better off, using an alternative technique. + +Example +------- + +The following C-extension module, make the ``cos`` function from the standard +math library available to Python: + +.. literalinclude:: python_c_api/cos_module.c + :language: c + +As you can see, there is much boilerplate, both to «massage» the arguments and +return types into place and for the module initialisation. Although some of +this is amortised, as the extension grows, the boilerplate required for each +function(s) remains. + +The standard python build system ``distutils`` supports compiling C-extensions +from a ``setup.py``, which is rather convenient: + +.. literalinclude:: python_c_api/setup.py + :language: python + +This can be compiled: + +.. sourcecode:: console + + $ cd advanced/interfacing_with_c/python_c_api + + $ ls + cos_module.c setup.py + + $ python setup.py build_ext --inplace + running build_ext + building 'cos_module' extension + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o + gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/python_c_api/cos_module.so + + $ ls + build/ cos_module.c cos_module.so setup.py + +* ``build_ext`` is to build extension modules +* ``--inplace`` will output the compiled extension module into the current directory + +The file ``cos_module.so`` contains the compiled extension, which we can now load in the IPython interpreter: + +.. sourcecode:: ipython + + In [1]: import cos_module + + In [2]: cos_module? + Type: module + String Form: + File: /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/python_c_api/cos_module.so + Docstring: + + In [3]: dir(cos_module) + Out[3]: ['__doc__', '__file__', '__name__', '__package__', 'cos_func'] + + In [4]: cos_module.cos_func(1.0) + Out[4]: 0.5403023058681398 + + In [5]: cos_module.cos_func(0.0) + Out[5]: 1.0 + + In [6]: cos_module.cos_func(3.14159265359) + Out[7]: -1.0 + +Now let's see how robust this is: + +.. sourcecode:: ipython + + In [10]: cos_module.cos_func('foo') + --------------------------------------------------------------------------- + TypeError Traceback (most recent call last) + in () + ----> 1 cos_module.cos_func('foo') + + TypeError: a float is required + +Numpy Support +------------- + +Analog to the Python-C-API, Numpy, which is itself implemented as a +C-extension, comes with the `Numpy-C-API +`_. This API can be used +to create and manipulate Numpy arrays from C, when writing a custom +C-extension. See also: :ref:`advanced_numpy`_. + +The following example shows how to pass Numpy arrays as arguments to functions +and how to iterate over Numpy arrays using the (old) Numpy-C-Api. It simply +takes an array as argument applies the cosine function from the ``math.h`` and +returns a resulting new array. + +.. literalinclude:: numpy_c_api/cos_module_np.c + :language: c + +To compile this we can use distutils again. However we need to be sure to +include the Numpy headers by using :func:`numpy.get_include`. + +.. literalinclude:: numpy_c_api/setup.py + :language: python + +To convince ourselves if this does actually works, we run the following test +script: + +.. literalinclude:: numpy_c_api/test_cos_module_np.py + :language: numpy + +And this should result in the following figure: + +.. image:: numpy_c_api/test_cos_module_np.png + :scale: 50 + +Ctypes +====== + +`Ctypes `_ is a *foreign +function library* for Python. It provides C compatible data types, and allows +calling functions in DLLs or shared libraries. It can be used to wrap these +libraries in pure Python. + +**Advantages** + +* Part of the Python standard library +* Does not need to be compiled +* Wrapping code entirely in Python + +**Disadvantages** + +* Requires code to be wrapped to be available as a shared library + (roughly speaking ``*.dll`` in Windows ``*.so`` in Linux and ``*.dylib`` in Mac OSX.) +* No good support for C++ + +Example +------- + +As advertised, the wrapper code is in pure Python. + +.. literalinclude:: ctypes/cos_module.py + :language: python + +* Finding and loading the library may vary depending on your operating system, + check `the documentation + `_ + for details +* This may be somewhat deceptive, since the math library exists in compiled + form on the system already. If you were to wrap a in-house library, you would + have to compile it first, which may or may not require some additional effort. + +We may now use this, as before: + +.. sourcecode:: ipython + + In [1]: import cos_module + + In [2]: cos_module? + Type: module + String Form: + File: /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/ctypes/cos_module.py + Docstring: + + In [3]: dir(cos_module) + Out[3]: + ['__builtins__', + '__doc__', + '__file__', + '__name__', + '__package__', + 'cos_func', + 'ctypes', + 'find_library', + 'libm'] + + In [4]: cos_module.cos_func(1.0) + Out[4]: 0.5403023058681398 + + In [5]: cos_module.cos_func(0.0) + Out[5]: 1.0 + + In [6]: cos_module.cos_func(3.14159265359) + Out[6]: -1.0 + +As with the previous example, this code is somewhat robust, although the error +message is not quite as helpful, since it does not tell us what the type should be. + +.. sourcecode:: ipython + + In [7]: cos_module.cos_func('foo') + --------------------------------------------------------------------------- + ArgumentError Traceback (most recent call last) + in () + ----> 1 cos_module.cos_func('foo') + + /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/ctypes/cos_module.py in cos_func(arg) + 12 def cos_func(arg): + 13 ''' Wrapper for cos from math.h ''' + ---> 14 return libm.cos(arg) + + ArgumentError: argument 1: : wrong type + +Numpy Support +------------- + +Numpy contains some support for interfacing with ctypes. In particular there is +support for exporting certain attributes of a Numpy array as ctypes data-types +and there are functions to convert from C arrays to Numpy arrays and back. + +.. XXX Should use :mod: and :class: + +For more information, consult the corresponding section in the `Numpy Cookbook +`_ and the API documentation for +`numpy.ndarray.ctypes `_ +and `numpy.ctypeslib `_. + +For the following example, let's consider a C function in a library that takes +an input and an output array, computes the cosine of the input array and +stores the result in the output_array. + +The library consists of the following header file (although this is not +strictly needed for this example, we list it for completeness): + +.. literalinclude:: ctypes_numpy/cos_doubles.h + :language: c + +The function implementation resides in the following C source file: + +.. literalinclude:: ctypes_numpy/cos_doubles.c + :language: c + +And since the library is pure C, we can't use ``distutils`` to compile it, but +must use a combination of ``make`` and ``gcc``: + +.. literalinclude:: ctypes_numpy/makefile + :language: make + +We can then compile this (on Linux) into the shared library +``libcos_doubles.so``: + +.. sourcecode:: console + + $ ls + cos_doubles.c cos_doubles.h cos_doubles.py makefile test_cos_doubles.py + $ make + gcc -c -fPIC cos_doubles.c -o cos_doubles.o + gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o + $ ls + cos_doubles.c cos_doubles.o libcos_doubles.so* test_cos_doubles.py + cos_doubles.h cos_doubles.py makefile + +Now we can proceed to wrap this library via ctypes with direct support for +(certain kinds of) Numpy arrays: + +.. literalinclude:: ctypes_numpy/cos_doubles.py + :language: numpy + +* Note the inherent limitation of contiguous single dimensional Numpy arrays, + since the C functions requires this kind of buffer. +* Also note that the output array must be preallocated, for example with + :func:`numpy.zeros` and the function will write into it's buffer. +* Although the original signature of the ``cos_doubles`` function is ``ARRAY, + ARRAY, int`` the final ``cos_doubles_func`` takes only two Numpy arrays as + arguments. + +And, as before, we convince ourselves that it worked: + +.. literalinclude:: ctypes_numpy/test_cos_doubles.py + :language: numpy + +.. image:: ctypes_numpy/test_cos_doubles.png + :scale: 50 + +SWIG +==== + +`SWIG `_, the Simplified Wrapper Interface Generator, +is a software development tool that connects programs written in C and C++ +with a variety of high-level programming languages, including Python. The +important thing with SWIG is, that it can autogenerate the wrapper code for you. +While this is an advantage in terms of development time, it can also be a +burden. The generated file tend to be quite large and may not be too human +readable and the multiple levels of indirection which are a result of +the wrapping process, may be a bit tricky to understand. + +.. note:: + + The autogenerated C code uses the Python-C-Api. + +**Advantages** + +* Can automatically wrap entire libraries given the headers +* Works nicely with C++ + +**Disadvantages** + +* Autogenerates enormous files +* Hard to debug if something goes wrong +* Steep learning curve + +Example +------- + +Let's imagine that our ``cos`` function lives in a ``cos_module`` which has +been written in ``c`` and consists of the source file ``cos_module.c``: + +.. literalinclude:: swig/cos_module.c + :language: c + +and the header file ``cos_module.h``: + +.. literalinclude:: swig/cos_module.h + :language: c + +And our goal is to expose the ``cos_func`` to Python. To achieve this with +SWIG, we must write an *interface file* which contains the instructions for SWIG. + +.. literalinclude:: swig/cos_module.i + :language: c + +As you can see, not too much code is needed here. For this simple example it is +enough to simply include the header file in the interface file, to expose the +function to Python. However, SWIG does allow for more fine grained +inclusion/exclusion of functions found in header files, check the documentation +for details. + +Generating the compiled wrappers is a two stage process: + +#. Run the ``swig`` executable on the interface file to generate the files + ``cos_module_wrap.c``, which is the source file for the autogenerated Python + C-extension and ``cos_module.py``, which is the autogenerated pure python + module. + +#. Compile the ``cos_module_wrap.c`` into the ``_cos_module.so``. Luckily, + ``distutils`` knows how to handle SWIG interface files, so that our + ``setup.py`` is simply: + +.. literalinclude:: swig/setup.py + :language: python + +.. sourcecode:: console + + $ cd advanced/interfacing_with_c/swig + + $ ls + cos_module.c cos_module.h cos_module.i setup.py + + $ python setup.py build_ext --inplace + running build_ext + building '_cos_module' extension + swigging cos_module.i to cos_module_wrap.c + swig -python -o cos_module_wrap.c cos_module.i + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module_wrap.c -o build/temp.linux-x86_64-2.7/cos_module_wrap.o + gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o build/temp.linux-x86_64-2.7/cos_module_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/swig/_cos_module.so + + $ ls + build/ cos_module.c cos_module.h cos_module.i cos_module.py _cos_module.so* cos_module_wrap.c setup.py + +We can now load and execute the ``cos_module`` as we have done in the previous examples: + +.. sourcecode:: ipython + + In [1]: import cos_module + + In [2]: cos_module? + Type: module + String Form: + File: /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/swig/cos_module.py + Docstring: + + In [3]: dir(cos_module) + Out[3]: + ['__builtins__', + '__doc__', + '__file__', + '__name__', + '__package__', + '_cos_module', + '_newclass', + '_object', + '_swig_getattr', + '_swig_property', + '_swig_repr', + '_swig_setattr', + '_swig_setattr_nondynamic', + 'cos_func'] + + In [4]: cos_module.cos_func(1.0) + Out[4]: 0.5403023058681398 + + In [5]: cos_module.cos_func(0.0) + Out[5]: 1.0 + + In [6]: cos_module.cos_func(3.14159265359) + Out[6]: -1.0 + +Again we test for robustness, and we see that we get a better error message +(although, strictly speaking in Python there is no ``double`` type): + +.. sourcecode:: ipython + + In [7]: cos_module.cos_func('foo') + --------------------------------------------------------------------------- + TypeError Traceback (most recent call last) + in () + ----> 1 cos_module.cos_func('foo') + + TypeError: in method 'cos_func', argument 1 of type 'double' + +Numpy Support +------------- + +Numpy provides `support for SWIG +`_ with the ``numpy.i`` +file. This interface file defines various so-called *typemaps* which support +conversion between Numpy arrays and C-Arrays. In the following example we will +take a quick look at how such typemaps work in practice. + +We have the same ``cos_doubles`` function as in the ctypes example: + +.. literalinclude:: swig_numpy/cos_doubles.h + :language: c + +.. literalinclude:: swig_numpy/cos_doubles.c + :language: c + +This is wrapped as ``cos_doubles_func`` using the following SWIG interface +file: + +.. literalinclude:: swig_numpy/cos_doubles.i + :language: c + +* To use the Numpy typemaps, we need include the ``numpy.i`` file. +* Observe the call to ``import_array()`` which we encountered already in the + Numpy-C-API example. +* Since the type maps only support the signature ``ARRAY, SIZE`` we need to + wrap the ``cos_doubles`` as ``cos_doubles_func`` which takes two arrays + including sizes as input. +* As opposed to the simple SWIG example, we don't include the ``cos_doubles.h`` + header, There is nothing there that we wish to expose to Python since we + expose the functionality through ``cos_doubles_func``. + +And, as before we can use distutils to wrap this: + +.. literalinclude:: swig_numpy/setup.py + :language: python + +As previously, we need to use ``include_dirs`` to specify the location. + +.. sourcecode:: console + + $ ls + cos_doubles.c cos_doubles.h cos_doubles.i numpy.i setup.py test_cos_doubles.py + $ python setup.py build_ext -i + running build_ext + building '_cos_doubles' extension + swigging cos_doubles.i to cos_doubles_wrap.c + swig -python -o cos_doubles_wrap.c cos_doubles.i + cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found. + cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found. + cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found. + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-x86_64-2.7/cos_doubles.o + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles_wrap.c -o build/temp.linux-x86_64-2.7/cos_doubles_wrap.o + In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1722, + from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17, + from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15, + from cos_doubles_wrap.c:2706: + /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" + gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_doubles.o build/temp.linux-x86_64-2.7/cos_doubles_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/swig_numpy/_cos_doubles.so + $ ls + build/ cos_doubles.h cos_doubles.py cos_doubles_wrap.c setup.py + cos_doubles.c cos_doubles.i _cos_doubles.so* numpy.i test_cos_doubles.py + +And, as before, we convince ourselves that it worked: + +.. literalinclude:: swig_numpy/test_cos_doubles.py + :language: numpy + +.. image:: swig_numpy/test_cos_doubles.png + :scale: 50 + + +Cython +====== + +`Cython `_ is both a Python-like language for writing +C-extensions and an advanced compiler for this language. The Cython *language* +is a superset of Python, which comes with additional constructs that allow you +call C functions and annotate variables and class attributes with c types. In +this sense one could also call it a *Python with types*. + +In addition to the basic use case of wrapping native code, Cython supports an +additional use-case, namely interactive optimization. Basically, one starts out +with a pure-Python script and incrementally adds Cython types to the bottleneck +code to optimize only those code paths that really matter. + +In this sense it is quite similar to SWIG, since the code can be autogenerated +but in a sense it also quite similar to ctypes since the wrapping code can +(almost) be written in Python. + +While others solutions that autogenerate code can be quite difficult to debug +(for example SWIG) Cython comes with an extension to the GNU debugger that +helps debug Python, Cython and C code. + +.. note:: + + The autogenerated C code uses the Python-C-Api. + +**Advantages** + +* Python like language for writing C-extensions +* Autogenerated code +* Supports incremental optimization +* Includes a GNU debugger extension +* Support for C++ (Since version 0.13) + +**Disadvantages** + +* Must be compiled +* Requires an additional library ( but only at build time, at this problem can be + overcome by shipping the generated C files) + +Example +------- + +The main Cython code for our ``cos_module`` is contained in the file +``cos_module.pyx``: + +.. literalinclude:: cython/cos_module.pyx + :language: cython + +Note the additional keywords such as ``cdef`` and ``extern``. Also the +``cos_func`` is then pure Python. + +Again we can use the standard ``distutils`` module, but this time we need some +additional pieces from the ``Cython.Distutils``: + +.. literalinclude:: cython/setup.py + +Compiling this: + +.. sourcecode:: console + + $ cd advanced/interfacing_with_c/cython + $ ls + cos_module.pyx setup.py + $ python setup.py build_ext --inplace + running build_ext + cythoning cos_module.pyx to cos_module.c + building 'cos_module' extension + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/cos_module.o + gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/cython/cos_module.so + $ ls + build/ cos_module.c cos_module.pyx cos_module.so* setup.py + +And running it: + +.. sourcecode:: ipython + + In [1]: import cos_module + + In [2]: cos_module? + Type: module + String Form: + File: /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/cython/cos_module.so + Docstring: + + In [3]: dir(cos_module) + Out[3]: + ['__builtins__', + '__doc__', + '__file__', + '__name__', + '__package__', + '__test__', + 'cos_func'] + + In [4]: cos_module.cos_func(1.0) + Out[4]: 0.5403023058681398 + + In [5]: cos_module.cos_func(0.0) + Out[5]: 1.0 + + In [6]: cos_module.cos_func(3.14159265359) + Out[6]: -1.0 + +And, testing a little for robustness, we can see that we get good error messages: + +.. sourcecode:: ipython + + In [7]: cos_module.cos_func('foo') + --------------------------------------------------------------------------- + TypeError Traceback (most recent call last) + in () + ----> 1 cos_module.cos_func('foo') + + /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/cython/cos_module.so in cos_module.cos_func (cos_module.c:506)() + + TypeError: a float is required + + +Additionally, it is worth noting that ``Cython`` ships with complete +declarations for the C math library, which simplifies the code above to become: + +.. literalinclude:: cython_simple/cos_module.pyx + :language: cython + +In this case the ``cimport`` statement is used to import the ``cos`` function. + +Numpy Support +------------- + +Cython has support for Numpy via the ``numpy.pyx`` file which allows you to add +the Numpy array type to your Cython code. I.e. like specifying that variable +``i`` is of type ``int``, you can specify that variable ``a`` is of type +``numpy.ndarray`` with a given ``dtype``. Also certain optimizations such as +bounds checking are supported. Look at the corresponding section in the `Cython +documentation `_. In case you +want to pass Numpy arrays as C arrays to your Cython wrapped C functions, there +is a section about this in the `Cython wiki +`_. + +In the following example, we will show how to wrap the familiar ``cos_doubles`` +function using Cython. + +.. literalinclude:: cython_numpy/cos_doubles.h + :language: c + +.. literalinclude:: cython_numpy/cos_doubles.c + :language: c + +This is wrapped as ``cos_doubles_func`` using the following Cython code: + +.. literalinclude:: cython_numpy/_cos_doubles.pyx + :language: cython + +And can be compiled using ``distutils``: + +.. literalinclude:: cython_numpy/setup.py + :language: python + +* As with the previous compiled Numpy examples, we need the ``include_dirs`` option. + +.. sourcecode:: console + + $ ls + cos_doubles.c cos_doubles.h _cos_doubles.pyx setup.py test_cos_doubles.py + $ python setup.py build_ext -i + running build_ext + cythoning _cos_doubles.pyx to _cos_doubles.c + building 'cos_doubles' extension + creating build + creating build/temp.linux-x86_64-2.7 + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c _cos_doubles.c -o build/temp.linux-x86_64-2.7/_cos_doubles.o + In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1722, + from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17, + from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15, + from _cos_doubles.c:253: + /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" + /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/__ufunc_api.h:236: warning: ‘_import_umath’ defined but not used + gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-x86_64-2.7/cos_doubles.o + gcc -pthread -shared build/temp.linux-x86_64-2.7/_cos_doubles.o build/temp.linux-x86_64-2.7/cos_doubles.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/cython_numpy/cos_doubles.so + $ ls + build/ _cos_doubles.c cos_doubles.c cos_doubles.h _cos_doubles.pyx cos_doubles.so* setup.py test_cos_doubles.py + +And, as before, we convince ourselves that it worked: + +.. literalinclude:: cython_numpy/test_cos_doubles.py + :language: numpy + +.. image:: cython_numpy/test_cos_doubles.png + :scale: 50 + + + +Summary +======= + +In this section four different techniques for interfacing with native code +have been presented. The table below roughly summarizes some of the aspects of +the techniques. + +============ =============== ========= ============= ============= +x Part of CPython Compiled Autogenerated Numpy Support +============ =============== ========= ============= ============= +Python-C-Api ``True`` ``True`` ``False`` ``True`` +Ctypes ``True`` ``False`` ``False`` ``True`` +Swig ``False`` ``True`` ``True`` ``True`` +Cython ``False`` ``True`` ``True`` ``True`` +============ =============== ========= ============= ============= + +Of all three presented techniques, Cython is the most modern and advanced. In +particular, the ability to optimize code incrementally by adding types to your +Python code is unique. + +Further Reading and References +============================== + +* `Gaël Varoquaux's blog post about avoiding data copies + `_ provides some insight on how to + handle memory management cleverly. If you ever run into issues with large + datasets, this is a reference to come back to for some inspiration. + +Exercises +========= + +Since this is a brand new section, the exercises are considered more as +pointers as to what to look at next, so pick the ones that you find more +interesting. If you have good ideas for exercises, please let us know! + +#. Download the source code for each example and compile and run them on your + machine. +#. Make trivial changes to each example and convince yourself that this works. ( + E.g. change ``cos`` for ``sin``.) +#. Most of the examples, especially the ones involving Numpy may still be + fragile and respond badly to input errors. Look for ways to crash the + examples, figure what the problem is and devise a potential solution. + Here are some ideas: + + #. Numerical overflow. + #. Input and output arrays that have different lengths. + #. Multidimensional array. + #. Empty array + #. Arrays with non-``double`` types + +#. Use the ``%timeit`` IPython magic to measure the execution time of the + various solutions + + +Python-C-API +------------ + +#. Modify the Numpy example such that the function takes two input arguments, where + the second is the preallocated output array, making it similar to the other Numpy examples. +#. Modify the example such that the function only takes a single input array + and modifies this in place. +#. Try to fix the example to use the new `Numpy iterator protocol + `_. If you + manage to obtain a working solution, please submit a pull-request on github. +#. You may have noticed, that the Numpy-C-API example is the only Numpy example + that does not wrap ``cos_doubles`` but instead applies the ``cos`` function + directly to the elements of the Numpy array. Does this have any advantages + over the other techniques. +#. Can you wrap ``cos_doubles`` using only the Numpy-C-API. You may need to + ensure that the arrays have the correct type, are one dimensional and + contiguous in memory. + +Ctypes +------ + +#. Modify the Numpy example such that ``cos_doubles_func`` handles the preallocation for + you, thus making it more like the Numpy-C-API example. + +SWIG +---- + +#. Look at the code that SWIG autogenerates, how much of it do you + understand? +#. Modify the Numpy example such that ``cos_doubles_func`` handles the preallocation for + you, thus making it more like the Numpy-C-API example. +#. Modify the ``cos_doubles`` C function so that it returns an allocated array. + Can you wrap this using SWIG typemaps? If not, why not? Is there a + workaround for this specific situation? (Hint: you know the size of the + output array, so it may be possible to construct a Numpy array from the + returned ``double *``.) + +Cython +------ + +#. Look at the code that Cython autogenartes. Take a closer look at some of the + comments that Cython inserts. What do you see? +#. Look at the section `Working with Numpy + `_ from the Cython + documentation to learn how to incrementally optimize a pure python script that uses Numpy. +#. Modify the Numpy example such that ``cos_doubles_func`` handles the preallocation for + you, thus making it more like the Numpy-C-API example. diff --git a/advanced/interfacing_with_c/numpy_c_api/cos_module_np.c b/advanced/interfacing_with_c/numpy_c_api/cos_module_np.c new file mode 100644 index 0000000..b8bfaf2 --- /dev/null +++ b/advanced/interfacing_with_c/numpy_c_api/cos_module_np.c @@ -0,0 +1,82 @@ +/* Example of wrapping the cos function from math.h using the Numpy-C-API. */ + +#include +#include +#include + +/* wrapped cosine function */ +static PyObject* cos_func_np(PyObject* self, PyObject* args) +{ + + PyArrayObject *in_array; + PyObject *out_array; + NpyIter *in_iter; + NpyIter *out_iter; + NpyIter_IterNextFunc *in_iternext; + NpyIter_IterNextFunc *out_iternext; + + /* parse single numpy array argument */ + if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &in_array)) + return NULL; + + /* construct the output array, like the input array */ + out_array = PyArray_NewLikeArray(in_array, NPY_ANYORDER, NULL, 0); + if (out_array == NULL) + return NULL; + + /* create the iterators */ + in_iter = NpyIter_New(in_array, NPY_ITER_READONLY, NPY_KEEPORDER, + NPY_NO_CASTING, NULL); + if (in_iter == NULL) + goto fail; + + out_iter = NpyIter_New((PyArrayObject *)out_array, NPY_ITER_READWRITE, + NPY_KEEPORDER, NPY_NO_CASTING, NULL); + if (out_iter == NULL) { + NpyIter_Deallocate(in_iter); + goto fail; + } + + in_iternext = NpyIter_GetIterNext(in_iter, NULL); + out_iternext = NpyIter_GetIterNext(out_iter, NULL); + if (in_iternext == NULL || out_iternext == NULL) { + NpyIter_Deallocate(in_iter); + NpyIter_Deallocate(out_iter); + goto fail; + } + double ** in_dataptr = (double **) NpyIter_GetDataPtrArray(in_iter); + double ** out_dataptr = (double **) NpyIter_GetDataPtrArray(out_iter); + + /* iterate over the arrays */ + do { + **out_dataptr = cos(**in_dataptr); + } while(in_iternext(in_iter) && out_iternext(out_iter)); + + /* clean up and return the result */ + NpyIter_Deallocate(in_iter); + NpyIter_Deallocate(out_iter); + Py_INCREF(out_array); + return out_array; + + /* in case bad things happen */ + fail: + Py_XDECREF(out_array); + return NULL; +} + +/* define functions in module */ +static PyMethodDef CosMethods[] = +{ + {"cos_func_np", cos_func_np, METH_VARARGS, + "evaluate the cosine on a numpy array"}, + {NULL, NULL, 0, NULL} +}; + +/* module initialization */ +PyMODINIT_FUNC +initcos_module_np(void) +{ + (void) Py_InitModule("cos_module_np", CosMethods); + /* IMPORTANT: this must be called */ + import_array(); +} diff --git a/advanced/interfacing_with_c/numpy_c_api/setup.py b/advanced/interfacing_with_c/numpy_c_api/setup.py new file mode 100644 index 0000000..5eae0f0 --- /dev/null +++ b/advanced/interfacing_with_c/numpy_c_api/setup.py @@ -0,0 +1,9 @@ +from distutils.core import setup, Extension +import numpy + +# define the extension module +cos_module_np = Extension('cos_module_np', sources=['cos_module_np.c'], + include_dirs=[numpy.get_include()]) + +# run the setup +setup(ext_modules=[cos_module_np]) diff --git a/advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.png b/advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.png new file mode 100644 index 0000000..cd5e636 Binary files /dev/null and b/advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.png differ diff --git a/advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.py b/advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.py new file mode 100644 index 0000000..f075840 --- /dev/null +++ b/advanced/interfacing_with_c/numpy_c_api/test_cos_module_np.py @@ -0,0 +1,8 @@ +import cos_module_np +import numpy as np +import pylab + +x = np.arange(0, 2 * np.pi, 0.1) +y = cos_module_np.cos_func_np(x) +pylab.plot(x, y) +pylab.show() diff --git a/advanced/interfacing_with_c/numpy_shared/cos_doubles.c b/advanced/interfacing_with_c/numpy_shared/cos_doubles.c new file mode 100644 index 0000000..396159e --- /dev/null +++ b/advanced/interfacing_with_c/numpy_shared/cos_doubles.c @@ -0,0 +1,10 @@ +#include + +/* Compute the cosine of each element in in_array, storing the result in + * out_array. */ +void cos_doubles(double * in_array, double * out_array, int size){ + int i; + for(i=0;i +#include + +/* wrapped cosine function */ +static PyObject* cos_func(PyObject* self, PyObject* args) +{ + double value; + double answer; + + /* parse the input, from python float to c double */ + if (!PyArg_ParseTuple(args, "d", &value)) + return NULL; + /* if the above function returns -1, an appropriate Python exception will + * have been set, and the function simply returns NULL + */ + + /* call cos from libm */ + answer = cos(value); + + /* construct the output from cos, from c double to python float */ + return Py_BuildValue("f", answer); +} + +/* define functions in module */ +static PyMethodDef CosMethods[] = +{ + {"cos_func", cos_func, METH_VARARGS, "evaluate the cosine"}, + {NULL, NULL, 0, NULL} +}; + +/* module initialization */ +PyMODINIT_FUNC + +initcos_module(void) +{ + (void) Py_InitModule("cos_module", CosMethods); +} diff --git a/advanced/interfacing_with_c/python_c_api/setup.py b/advanced/interfacing_with_c/python_c_api/setup.py new file mode 100644 index 0000000..56433ee --- /dev/null +++ b/advanced/interfacing_with_c/python_c_api/setup.py @@ -0,0 +1,7 @@ +from distutils.core import setup, Extension + +# define the extension module +cos_module = Extension('cos_module', sources=['cos_module.c']) + +# run the setup +setup(ext_modules=[cos_module]) diff --git a/advanced/interfacing_with_c/swig/cos_module.c b/advanced/interfacing_with_c/swig/cos_module.c new file mode 100644 index 0000000..657d925 --- /dev/null +++ b/advanced/interfacing_with_c/swig/cos_module.c @@ -0,0 +1,5 @@ +#include + +double cos_func(double arg){ + return cos(arg); +} diff --git a/advanced/interfacing_with_c/swig/cos_module.h b/advanced/interfacing_with_c/swig/cos_module.h new file mode 100644 index 0000000..f4020f4 --- /dev/null +++ b/advanced/interfacing_with_c/swig/cos_module.h @@ -0,0 +1 @@ +double cos_func(double arg); diff --git a/advanced/interfacing_with_c/swig/cos_module.i b/advanced/interfacing_with_c/swig/cos_module.i new file mode 100644 index 0000000..7e89d32 --- /dev/null +++ b/advanced/interfacing_with_c/swig/cos_module.i @@ -0,0 +1,11 @@ +/* Example of wrapping cos function from math.h using SWIG. */ + +%module cos_module +%{ + /* the resulting C file should be built as a python extension */ + #define SWIG_FILE_WITH_INIT + /* Includes the header in the wrapper code */ + #include "cos_module.h" +%} +/* Parse the header file to generate wrappers */ +%include "cos_module.h" diff --git a/advanced/interfacing_with_c/swig/setup.py b/advanced/interfacing_with_c/swig/setup.py new file mode 100644 index 0000000..6c7706d --- /dev/null +++ b/advanced/interfacing_with_c/swig/setup.py @@ -0,0 +1,4 @@ +from distutils.core import setup, Extension + +setup(ext_modules=[Extension("_cos_module", + sources=["cos_module.c", "cos_module.i"])]) diff --git a/advanced/interfacing_with_c/swig_numpy/cos_doubles.c b/advanced/interfacing_with_c/swig_numpy/cos_doubles.c new file mode 120000 index 0000000..f2d10ab --- /dev/null +++ b/advanced/interfacing_with_c/swig_numpy/cos_doubles.c @@ -0,0 +1 @@ +../numpy_shared/cos_doubles.c \ No newline at end of file diff --git a/advanced/interfacing_with_c/swig_numpy/cos_doubles.h b/advanced/interfacing_with_c/swig_numpy/cos_doubles.h new file mode 120000 index 0000000..4b58a1b --- /dev/null +++ b/advanced/interfacing_with_c/swig_numpy/cos_doubles.h @@ -0,0 +1 @@ +../numpy_shared/cos_doubles.h \ No newline at end of file diff --git a/advanced/interfacing_with_c/swig_numpy/cos_doubles.i b/advanced/interfacing_with_c/swig_numpy/cos_doubles.i new file mode 100644 index 0000000..0c81cdb --- /dev/null +++ b/advanced/interfacing_with_c/swig_numpy/cos_doubles.i @@ -0,0 +1,30 @@ +/* Example of wrapping a C function that takes a C double array as input using + * numpy typemaps for SWIG. */ + +%module cos_doubles +%{ + /* the resulting C file should be built as a python extension */ + #define SWIG_FILE_WITH_INIT + /* Includes the header in the wrapper code */ + #include "cos_doubles.h" +%} + +/* include the numpy typemaps */ +%include "numpy.i" +/* need this for correct module initialization */ +%init %{ + import_array(); +%} + +/* typemaps for the two arrays, the second will be modified in-place */ +%apply (double* IN_ARRAY1, int DIM1) {(double * in_array, int size_in)} +%apply (double* INPLACE_ARRAY1, int DIM1) {(double * out_array, int size_out)} + +/* Wrapper for cos_doubles that massages the types */ +%inline %{ + /* takes as input two numpy arrays */ + void cos_doubles_func(double * in_array, int size_in, double * out_array, int size_out) { + /* calls the original funcion, providing only the size of the first */ + cos_doubles(in_array, out_array, size_in); + } +%} diff --git a/advanced/interfacing_with_c/swig_numpy/numpy.i b/advanced/interfacing_with_c/swig_numpy/numpy.i new file mode 100644 index 0000000..4de4a20 --- /dev/null +++ b/advanced/interfacing_with_c/swig_numpy/numpy.i @@ -0,0 +1,1579 @@ +/* -*- C -*- (not really, but good for syntax highlighting) */ +#ifdef SWIGPYTHON + +%{ +#ifndef SWIG_FILE_WITH_INIT +# define NO_IMPORT_ARRAY +#endif +#include "stdio.h" +#include +%} + +/**********************************************************************/ + +/* The following code originally appeared in + * enthought/kiva/agg/src/numeric.i written by Eric Jones. It was + * translated from C++ to C by John Hunter. Bill Spotz has modified + * it to fix some minor bugs, upgrade from Numeric to numpy (all + * versions), add some comments and functionality, and convert from + * direct code insertion to SWIG fragments. + */ + +%fragment("NumPy_Macros", "header") +{ +/* Macros to extract array attributes. + */ +%#define is_array(a) ((a) && PyArray_Check((PyArrayObject *)a)) +%#define array_type(a) (int)(PyArray_TYPE(a)) +%#define array_numdims(a) (((PyArrayObject *)a)->nd) +%#define array_dimensions(a) (((PyArrayObject *)a)->dimensions) +%#define array_size(a,i) (((PyArrayObject *)a)->dimensions[i]) +%#define array_data(a) (((PyArrayObject *)a)->data) +%#define array_is_contiguous(a) (PyArray_ISCONTIGUOUS(a)) +%#define array_is_native(a) (PyArray_ISNOTSWAPPED(a)) +%#define array_is_fortran(a) (PyArray_ISFORTRAN(a)) +} + +/**********************************************************************/ + +%fragment("NumPy_Utilities", "header") +{ + /* Given a PyObject, return a string describing its type. + */ + const char* pytype_string(PyObject* py_obj) { + if (py_obj == NULL ) return "C NULL value"; + if (py_obj == Py_None ) return "Python None" ; + if (PyCallable_Check(py_obj)) return "callable" ; + if (PyString_Check( py_obj)) return "string" ; + if (PyInt_Check( py_obj)) return "int" ; + if (PyFloat_Check( py_obj)) return "float" ; + if (PyDict_Check( py_obj)) return "dict" ; + if (PyList_Check( py_obj)) return "list" ; + if (PyTuple_Check( py_obj)) return "tuple" ; + if (PyModule_Check( py_obj)) return "module" ; +%#if PY_MAJOR_VERSION < 3 + if (PyFile_Check( py_obj)) return "file" ; + if (PyInstance_Check(py_obj)) return "instance" ; +%#endif + + return "unkown type"; + } + + /* Given a NumPy typecode, return a string describing the type. + */ + const char* typecode_string(int typecode) { + static const char* type_names[25] = {"bool", "byte", "unsigned byte", + "short", "unsigned short", "int", + "unsigned int", "long", "unsigned long", + "long long", "unsigned long long", + "float", "double", "long double", + "complex float", "complex double", + "complex long double", "object", + "string", "unicode", "void", "ntypes", + "notype", "char", "unknown"}; + return typecode < 24 ? type_names[typecode] : type_names[24]; + } + + /* Make sure input has correct numpy type. Allow character and byte + * to match. Also allow int and long to match. This is deprecated. + * You should use PyArray_EquivTypenums() instead. + */ + int type_match(int actual_type, int desired_type) { + return PyArray_EquivTypenums(actual_type, desired_type); + } +} + +/**********************************************************************/ + +%fragment("NumPy_Object_to_Array", "header", + fragment="NumPy_Backward_Compatibility", + fragment="NumPy_Macros", + fragment="NumPy_Utilities") +{ + /* Given a PyObject pointer, cast it to a PyArrayObject pointer if + * legal. If not, set the python error string appropriately and + * return NULL. + */ + PyArrayObject* obj_to_array_no_conversion(PyObject* input, int typecode) + { + PyArrayObject* ary = NULL; + if (is_array(input) && (typecode == NPY_NOTYPE || + PyArray_EquivTypenums(array_type(input), typecode))) + { + ary = (PyArrayObject*) input; + } + else if is_array(input) + { + const char* desired_type = typecode_string(typecode); + const char* actual_type = typecode_string(array_type(input)); + PyErr_Format(PyExc_TypeError, + "Array of type '%s' required. Array of type '%s' given", + desired_type, actual_type); + ary = NULL; + } + else + { + const char * desired_type = typecode_string(typecode); + const char * actual_type = pytype_string(input); + PyErr_Format(PyExc_TypeError, + "Array of type '%s' required. A '%s' was given", + desired_type, actual_type); + ary = NULL; + } + return ary; + } + + /* Convert the given PyObject to a NumPy array with the given + * typecode. On success, return a valid PyArrayObject* with the + * correct type. On failure, the python error string will be set and + * the routine returns NULL. + */ + PyArrayObject* obj_to_array_allow_conversion(PyObject* input, int typecode, + int* is_new_object) + { + PyArrayObject* ary = NULL; + PyObject* py_obj; + if (is_array(input) && (typecode == NPY_NOTYPE || + PyArray_EquivTypenums(array_type(input),typecode))) + { + ary = (PyArrayObject*) input; + *is_new_object = 0; + } + else + { + py_obj = PyArray_FROMANY(input, typecode, 0, 0, NPY_DEFAULT); + /* If NULL, PyArray_FromObject will have set python error value.*/ + ary = (PyArrayObject*) py_obj; + *is_new_object = 1; + } + return ary; + } + + /* Given a PyArrayObject, check to see if it is contiguous. If so, + * return the input pointer and flag it as not a new object. If it is + * not contiguous, create a new PyArrayObject using the original data, + * flag it as a new object and return the pointer. + */ + PyArrayObject* make_contiguous(PyArrayObject* ary, int* is_new_object, + int min_dims, int max_dims) + { + PyArrayObject* result; + if (array_is_contiguous(ary)) + { + result = ary; + *is_new_object = 0; + } + else + { + result = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*)ary, + array_type(ary), + min_dims, + max_dims); + *is_new_object = 1; + } + return result; + } + + /* Given a PyArrayObject, check to see if it is Fortran-contiguous. + * If so, return the input pointer, but do not flag it as not a new + * object. If it is not Fortran-contiguous, create a new + * PyArrayObject using the original data, flag it as a new object + * and return the pointer. + */ + PyArrayObject* make_fortran(PyArrayObject* ary, int* is_new_object, + int min_dims, int max_dims) + { + PyArrayObject* result; + if (array_is_fortran(ary)) + { + result = ary; + *is_new_object = 0; + } + else + { + Py_INCREF(ary->descr); + result = (PyArrayObject*) PyArray_FromArray(ary, ary->descr, NPY_FORTRAN); + *is_new_object = 1; + } + return result; + } + + /* Convert a given PyObject to a contiguous PyArrayObject of the + * specified type. If the input object is not a contiguous + * PyArrayObject, a new one will be created and the new object flag + * will be set. + */ + PyArrayObject* obj_to_array_contiguous_allow_conversion(PyObject* input, + int typecode, + int* is_new_object) + { + int is_new1 = 0; + int is_new2 = 0; + PyArrayObject* ary2; + PyArrayObject* ary1 = obj_to_array_allow_conversion(input, typecode, + &is_new1); + if (ary1) + { + ary2 = make_contiguous(ary1, &is_new2, 0, 0); + if ( is_new1 && is_new2) + { + Py_DECREF(ary1); + } + ary1 = ary2; + } + *is_new_object = is_new1 || is_new2; + return ary1; + } + + /* Convert a given PyObject to a Fortran-ordered PyArrayObject of the + * specified type. If the input object is not a Fortran-ordered + * PyArrayObject, a new one will be created and the new object flag + * will be set. + */ + PyArrayObject* obj_to_array_fortran_allow_conversion(PyObject* input, + int typecode, + int* is_new_object) + { + int is_new1 = 0; + int is_new2 = 0; + PyArrayObject* ary2; + PyArrayObject* ary1 = obj_to_array_allow_conversion(input, typecode, + &is_new1); + if (ary1) + { + ary2 = make_fortran(ary1, &is_new2, 0, 0); + if (is_new1 && is_new2) + { + Py_DECREF(ary1); + } + ary1 = ary2; + } + *is_new_object = is_new1 || is_new2; + return ary1; + } + +} /* end fragment */ + + +/**********************************************************************/ + +%fragment("NumPy_Array_Requirements", "header", + fragment="NumPy_Backward_Compatibility", + fragment="NumPy_Macros") +{ + /* Test whether a python object is contiguous. If array is + * contiguous, return 1. Otherwise, set the python error string and + * return 0. + */ + int require_contiguous(PyArrayObject* ary) + { + int contiguous = 1; + if (!array_is_contiguous(ary)) + { + PyErr_SetString(PyExc_TypeError, + "Array must be contiguous. A non-contiguous array was given"); + contiguous = 0; + } + return contiguous; + } + + /* Require that a numpy array is not byte-swapped. If the array is + * not byte-swapped, return 1. Otherwise, set the python error string + * and return 0. + */ + int require_native(PyArrayObject* ary) + { + int native = 1; + if (!array_is_native(ary)) + { + PyErr_SetString(PyExc_TypeError, + "Array must have native byteorder. " + "A byte-swapped array was given"); + native = 0; + } + return native; + } + + /* Require the given PyArrayObject to have a specified number of + * dimensions. If the array has the specified number of dimensions, + * return 1. Otherwise, set the python error string and return 0. + */ + int require_dimensions(PyArrayObject* ary, int exact_dimensions) + { + int success = 1; + if (array_numdims(ary) != exact_dimensions) + { + PyErr_Format(PyExc_TypeError, + "Array must have %d dimensions. Given array has %d dimensions", + exact_dimensions, array_numdims(ary)); + success = 0; + } + return success; + } + + /* Require the given PyArrayObject to have one of a list of specified + * number of dimensions. If the array has one of the specified number + * of dimensions, return 1. Otherwise, set the python error string + * and return 0. + */ + int require_dimensions_n(PyArrayObject* ary, int* exact_dimensions, int n) + { + int success = 0; + int i; + char dims_str[255] = ""; + char s[255]; + for (i = 0; i < n && !success; i++) + { + if (array_numdims(ary) == exact_dimensions[i]) + { + success = 1; + } + } + if (!success) + { + for (i = 0; i < n-1; i++) + { + sprintf(s, "%d, ", exact_dimensions[i]); + strcat(dims_str,s); + } + sprintf(s, " or %d", exact_dimensions[n-1]); + strcat(dims_str,s); + PyErr_Format(PyExc_TypeError, + "Array must have %s dimensions. Given array has %d dimensions", + dims_str, array_numdims(ary)); + } + return success; + } + + /* Require the given PyArrayObject to have a specified shape. If the + * array has the specified shape, return 1. Otherwise, set the python + * error string and return 0. + */ + int require_size(PyArrayObject* ary, npy_intp* size, int n) + { + int i; + int success = 1; + int len; + char desired_dims[255] = "["; + char s[255]; + char actual_dims[255] = "["; + for(i=0; i < n;i++) + { + if (size[i] != -1 && size[i] != array_size(ary,i)) + { + success = 0; + } + } + if (!success) + { + for (i = 0; i < n; i++) + { + if (size[i] == -1) + { + sprintf(s, "*,"); + } + else + { + sprintf(s, "%ld,", (long int)size[i]); + } + strcat(desired_dims,s); + } + len = strlen(desired_dims); + desired_dims[len-1] = ']'; + for (i = 0; i < n; i++) + { + sprintf(s, "%ld,", (long int)array_size(ary,i)); + strcat(actual_dims,s); + } + len = strlen(actual_dims); + actual_dims[len-1] = ']'; + PyErr_Format(PyExc_TypeError, + "Array must have shape of %s. Given array has shape of %s", + desired_dims, actual_dims); + } + return success; + } + + /* Require the given PyArrayObject to to be FORTRAN ordered. If the + * the PyArrayObject is already FORTRAN ordered, do nothing. Else, + * set the FORTRAN ordering flag and recompute the strides. + */ + int require_fortran(PyArrayObject* ary) + { + int success = 1; + int nd = array_numdims(ary); + int i; + if (array_is_fortran(ary)) return success; + /* Set the FORTRAN ordered flag */ + ary->flags = NPY_FARRAY; + /* Recompute the strides */ + ary->strides[0] = ary->strides[nd-1]; + for (i=1; i < nd; ++i) + ary->strides[i] = ary->strides[i-1] * array_size(ary,i-1); + return success; + } +} + +/* Combine all NumPy fragments into one for convenience */ +%fragment("NumPy_Fragments", "header", + fragment="NumPy_Backward_Compatibility", + fragment="NumPy_Macros", + fragment="NumPy_Utilities", + fragment="NumPy_Object_to_Array", + fragment="NumPy_Array_Requirements") { } + +/* End John Hunter translation (with modifications by Bill Spotz) + */ + +/* %numpy_typemaps() macro + * + * This macro defines a family of 41 typemaps that allow C arguments + * of the form + * + * (DATA_TYPE IN_ARRAY1[ANY]) + * (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) + * (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) + * + * (DATA_TYPE IN_ARRAY2[ANY][ANY]) + * (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + * (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) + * (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + * (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) + * + * (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) + * (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) + * (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) + * (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) + * (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) + * + * (DATA_TYPE INPLACE_ARRAY1[ANY]) + * (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) + * (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) + * + * (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) + * (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + * (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) + * (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + * (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) + * + * (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) + * (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) + * (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) + * (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) + * (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) + * + * (DATA_TYPE ARGOUT_ARRAY1[ANY]) + * (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) + * (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) + * + * (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) + * + * (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) + * + * (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) + * (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) + * + * (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) + * (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) + * (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) + * (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) + * + * (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) + * (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) + * (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) + * (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) + * + * where "DATA_TYPE" is any type supported by the NumPy module, and + * "DIM_TYPE" is any int-like type suitable for specifying dimensions. + * The difference between "ARRAY" typemaps and "FARRAY" typemaps is + * that the "FARRAY" typemaps expect FORTRAN ordering of + * multidimensional arrays. In python, the dimensions will not need + * to be specified (except for the "DATA_TYPE* ARGOUT_ARRAY1" + * typemaps). The IN_ARRAYs can be a numpy array or any sequence that + * can be converted to a numpy array of the specified type. The + * INPLACE_ARRAYs must be numpy arrays of the appropriate type. The + * ARGOUT_ARRAYs will be returned as new numpy arrays of the + * appropriate type. + * + * These typemaps can be applied to existing functions using the + * %apply directive. For example: + * + * %apply (double* IN_ARRAY1, int DIM1) {(double* series, int length)}; + * double prod(double* series, int length); + * + * %apply (int DIM1, int DIM2, double* INPLACE_ARRAY2) + * {(int rows, int cols, double* matrix )}; + * void floor(int rows, int cols, double* matrix, double f); + * + * %apply (double IN_ARRAY3[ANY][ANY][ANY]) + * {(double tensor[2][2][2] )}; + * %apply (double ARGOUT_ARRAY3[ANY][ANY][ANY]) + * {(double low[2][2][2] )}; + * %apply (double ARGOUT_ARRAY3[ANY][ANY][ANY]) + * {(double upp[2][2][2] )}; + * void luSplit(double tensor[2][2][2], + * double low[2][2][2], + * double upp[2][2][2] ); + * + * or directly with + * + * double prod(double* IN_ARRAY1, int DIM1); + * + * void floor(int DIM1, int DIM2, double* INPLACE_ARRAY2, double f); + * + * void luSplit(double IN_ARRAY3[ANY][ANY][ANY], + * double ARGOUT_ARRAY3[ANY][ANY][ANY], + * double ARGOUT_ARRAY3[ANY][ANY][ANY]); + */ + +%define %numpy_typemaps(DATA_TYPE, DATA_TYPECODE, DIM_TYPE) + +/************************/ +/* Input Array Typemaps */ +/************************/ + +/* Typemap suite for (DATA_TYPE IN_ARRAY1[ANY]) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE IN_ARRAY1[ANY]) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE IN_ARRAY1[ANY]) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[1] = { $1_dim0 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 1) || + !require_size(array, size, 1)) SWIG_fail; + $1 = ($1_ltype) array_data(array); +} +%typemap(freearg) + (DATA_TYPE IN_ARRAY1[ANY]) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[1] = { -1 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 1) || + !require_size(array, size, 1)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = (DIM_TYPE) array_size(array,0); +} +%typemap(freearg) + (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[1] = {-1}; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 1) || + !require_size(array, size, 1)) SWIG_fail; + $1 = (DIM_TYPE) array_size(array,0); + $2 = (DATA_TYPE*) array_data(array); +} +%typemap(freearg) + (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DATA_TYPE IN_ARRAY2[ANY][ANY]) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE IN_ARRAY2[ANY][ANY]) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE IN_ARRAY2[ANY][ANY]) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[2] = { $1_dim0, $1_dim1 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 2) || + !require_size(array, size, 2)) SWIG_fail; + $1 = ($1_ltype) array_data(array); +} +%typemap(freearg) + (DATA_TYPE IN_ARRAY2[ANY][ANY]) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[2] = { -1, -1 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 2) || + !require_size(array, size, 2)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = (DIM_TYPE) array_size(array,0); + $3 = (DIM_TYPE) array_size(array,1); +} +%typemap(freearg) + (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[2] = { -1, -1 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 2) || + !require_size(array, size, 2)) SWIG_fail; + $1 = (DIM_TYPE) array_size(array,0); + $2 = (DIM_TYPE) array_size(array,1); + $3 = (DATA_TYPE*) array_data(array); +} +%typemap(freearg) + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[2] = { -1, -1 }; + array = obj_to_array_fortran_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 2) || + !require_size(array, size, 2) || !require_fortran(array)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = (DIM_TYPE) array_size(array,0); + $3 = (DIM_TYPE) array_size(array,1); +} +%typemap(freearg) + (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[2] = { -1, -1 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 2) || + !require_size(array, size, 2) || !require_fortran(array)) SWIG_fail; + $1 = (DIM_TYPE) array_size(array,0); + $2 = (DIM_TYPE) array_size(array,1); + $3 = (DATA_TYPE*) array_data(array); +} +%typemap(freearg) + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[3] = { $1_dim0, $1_dim1, $1_dim2 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 3) || + !require_size(array, size, 3)) SWIG_fail; + $1 = ($1_ltype) array_data(array); +} +%typemap(freearg) + (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, + * DIM_TYPE DIM3) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[3] = { -1, -1, -1 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 3) || + !require_size(array, size, 3)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = (DIM_TYPE) array_size(array,0); + $3 = (DIM_TYPE) array_size(array,1); + $4 = (DIM_TYPE) array_size(array,2); +} +%typemap(freearg) + (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, + * DATA_TYPE* IN_ARRAY3) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[3] = { -1, -1, -1 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 3) || + !require_size(array, size, 3)) SWIG_fail; + $1 = (DIM_TYPE) array_size(array,0); + $2 = (DIM_TYPE) array_size(array,1); + $3 = (DIM_TYPE) array_size(array,2); + $4 = (DATA_TYPE*) array_data(array); +} +%typemap(freearg) + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, + * DIM_TYPE DIM3) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[3] = { -1, -1, -1 }; + array = obj_to_array_fortran_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 3) || + !require_size(array, size, 3) | !require_fortran(array)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = (DIM_TYPE) array_size(array,0); + $3 = (DIM_TYPE) array_size(array,1); + $4 = (DIM_TYPE) array_size(array,2); +} +%typemap(freearg) + (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, + * DATA_TYPE* IN_FARRAY3) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) +{ + $1 = is_array($input) || PySequence_Check($input); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) + (PyArrayObject* array=NULL, int is_new_object=0) +{ + npy_intp size[3] = { -1, -1, -1 }; + array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, + &is_new_object); + if (!array || !require_dimensions(array, 3) || + !require_size(array, size, 3) || !require_fortran(array)) SWIG_fail; + $1 = (DIM_TYPE) array_size(array,0); + $2 = (DIM_TYPE) array_size(array,1); + $3 = (DIM_TYPE) array_size(array,2); + $4 = (DATA_TYPE*) array_data(array); +} +%typemap(freearg) + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) +{ + if (is_new_object$argnum && array$argnum) + { Py_DECREF(array$argnum); } +} + +/***************************/ +/* In-Place Array Typemaps */ +/***************************/ + +/* Typemap suite for (DATA_TYPE INPLACE_ARRAY1[ANY]) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE INPLACE_ARRAY1[ANY]) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE INPLACE_ARRAY1[ANY]) + (PyArrayObject* array=NULL) +{ + npy_intp size[1] = { $1_dim0 }; + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,1) || !require_size(array, size, 1) || + !require_contiguous(array) || !require_native(array)) SWIG_fail; + $1 = ($1_ltype) array_data(array); +} + +/* Typemap suite for (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) + (PyArrayObject* array=NULL, int i=1) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,1) || !require_contiguous(array) + || !require_native(array)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = 1; + for (i=0; i < array_numdims(array); ++i) $2 *= array_size(array,i); +} + +/* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) + (PyArrayObject* array=NULL, int i=0) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,1) || !require_contiguous(array) + || !require_native(array)) SWIG_fail; + $1 = 1; + for (i=0; i < array_numdims(array); ++i) $1 *= array_size(array,i); + $2 = (DATA_TYPE*) array_data(array); +} + +/* Typemap suite for (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) + (PyArrayObject* array=NULL) +{ + npy_intp size[2] = { $1_dim0, $1_dim1 }; + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,2) || !require_size(array, size, 2) || + !require_contiguous(array) || !require_native(array)) SWIG_fail; + $1 = ($1_ltype) array_data(array); +} + +/* Typemap suite for (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + (PyArrayObject* array=NULL) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,2) || !require_contiguous(array) + || !require_native(array)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = (DIM_TYPE) array_size(array,0); + $3 = (DIM_TYPE) array_size(array,1); +} + +/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) + (PyArrayObject* array=NULL) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,2) || !require_contiguous(array) || + !require_native(array)) SWIG_fail; + $1 = (DIM_TYPE) array_size(array,0); + $2 = (DIM_TYPE) array_size(array,1); + $3 = (DATA_TYPE*) array_data(array); +} + +/* Typemap suite for (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) + (PyArrayObject* array=NULL) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,2) || !require_contiguous(array) + || !require_native(array) || !require_fortran(array)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = (DIM_TYPE) array_size(array,0); + $3 = (DIM_TYPE) array_size(array,1); +} + +/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) + (PyArrayObject* array=NULL) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,2) || !require_contiguous(array) || + !require_native(array) || !require_fortran(array)) SWIG_fail; + $1 = (DIM_TYPE) array_size(array,0); + $2 = (DIM_TYPE) array_size(array,1); + $3 = (DATA_TYPE*) array_data(array); +} + +/* Typemap suite for (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) + (PyArrayObject* array=NULL) +{ + npy_intp size[3] = { $1_dim0, $1_dim1, $1_dim2 }; + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,3) || !require_size(array, size, 3) || + !require_contiguous(array) || !require_native(array)) SWIG_fail; + $1 = ($1_ltype) array_data(array); +} + +/* Typemap suite for (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, + * DIM_TYPE DIM3) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) + (PyArrayObject* array=NULL) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,3) || !require_contiguous(array) || + !require_native(array)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = (DIM_TYPE) array_size(array,0); + $3 = (DIM_TYPE) array_size(array,1); + $4 = (DIM_TYPE) array_size(array,2); +} + +/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, + * DATA_TYPE* INPLACE_ARRAY3) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) + (PyArrayObject* array=NULL) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,3) || !require_contiguous(array) + || !require_native(array)) SWIG_fail; + $1 = (DIM_TYPE) array_size(array,0); + $2 = (DIM_TYPE) array_size(array,1); + $3 = (DIM_TYPE) array_size(array,2); + $4 = (DATA_TYPE*) array_data(array); +} + +/* Typemap suite for (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, + * DIM_TYPE DIM3) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) + (PyArrayObject* array=NULL) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,3) || !require_contiguous(array) || + !require_native(array) || !require_fortran(array)) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); + $2 = (DIM_TYPE) array_size(array,0); + $3 = (DIM_TYPE) array_size(array,1); + $4 = (DIM_TYPE) array_size(array,2); +} + +/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, + * DATA_TYPE* INPLACE_FARRAY3) + */ +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, + fragment="NumPy_Macros") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) +{ + $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), + DATA_TYPECODE); +} +%typemap(in, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) + (PyArrayObject* array=NULL) +{ + array = obj_to_array_no_conversion($input, DATA_TYPECODE); + if (!array || !require_dimensions(array,3) || !require_contiguous(array) + || !require_native(array) || !require_fortran(array)) SWIG_fail; + $1 = (DIM_TYPE) array_size(array,0); + $2 = (DIM_TYPE) array_size(array,1); + $3 = (DIM_TYPE) array_size(array,2); + $4 = (DATA_TYPE*) array_data(array); +} + +/*************************/ +/* Argout Array Typemaps */ +/*************************/ + +/* Typemap suite for (DATA_TYPE ARGOUT_ARRAY1[ANY]) + */ +%typemap(in,numinputs=0, + fragment="NumPy_Backward_Compatibility,NumPy_Macros") + (DATA_TYPE ARGOUT_ARRAY1[ANY]) + (PyObject * array = NULL) +{ + npy_intp dims[1] = { $1_dim0 }; + array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); + if (!array) SWIG_fail; + $1 = ($1_ltype) array_data(array); +} +%typemap(argout) + (DATA_TYPE ARGOUT_ARRAY1[ANY]) +{ + $result = SWIG_Python_AppendOutput($result,array$argnum); +} + +/* Typemap suite for (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) + */ +%typemap(in,numinputs=1, + fragment="NumPy_Fragments") + (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) + (PyObject * array = NULL) +{ + npy_intp dims[1]; + if (!PyInt_Check($input)) + { + const char* typestring = pytype_string($input); + PyErr_Format(PyExc_TypeError, + "Int dimension expected. '%s' given.", + typestring); + SWIG_fail; + } + $2 = (DIM_TYPE) PyInt_AsLong($input); + dims[0] = (npy_intp) $2; + array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); + if (!array) SWIG_fail; + $1 = (DATA_TYPE*) array_data(array); +} +%typemap(argout) + (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) +{ + $result = SWIG_Python_AppendOutput($result,array$argnum); +} + +/* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) + */ +%typemap(in,numinputs=1, + fragment="NumPy_Fragments") + (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) + (PyObject * array = NULL) +{ + npy_intp dims[1]; + if (!PyInt_Check($input)) + { + const char* typestring = pytype_string($input); + PyErr_Format(PyExc_TypeError, + "Int dimension expected. '%s' given.", + typestring); + SWIG_fail; + } + $1 = (DIM_TYPE) PyInt_AsLong($input); + dims[0] = (npy_intp) $1; + array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); + if (!array) SWIG_fail; + $2 = (DATA_TYPE*) array_data(array); +} +%typemap(argout) + (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) +{ + $result = SWIG_Python_AppendOutput($result,array$argnum); +} + +/* Typemap suite for (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) + */ +%typemap(in,numinputs=0, + fragment="NumPy_Backward_Compatibility,NumPy_Macros") + (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) + (PyObject * array = NULL) +{ + npy_intp dims[2] = { $1_dim0, $1_dim1 }; + array = PyArray_SimpleNew(2, dims, DATA_TYPECODE); + if (!array) SWIG_fail; + $1 = ($1_ltype) array_data(array); +} +%typemap(argout) + (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) +{ + $result = SWIG_Python_AppendOutput($result,array$argnum); +} + +/* Typemap suite for (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) + */ +%typemap(in,numinputs=0, + fragment="NumPy_Backward_Compatibility,NumPy_Macros") + (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) + (PyObject * array = NULL) +{ + npy_intp dims[3] = { $1_dim0, $1_dim1, $1_dim2 }; + array = PyArray_SimpleNew(3, dims, DATA_TYPECODE); + if (!array) SWIG_fail; + $1 = ($1_ltype) array_data(array); +} +%typemap(argout) + (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) +{ + $result = SWIG_Python_AppendOutput($result,array$argnum); +} + +/*****************************/ +/* Argoutview Array Typemaps */ +/*****************************/ + +/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) + */ +%typemap(in,numinputs=0) + (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1 ) + (DATA_TYPE* data_temp , DIM_TYPE dim_temp) +{ + $1 = &data_temp; + $2 = &dim_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility") + (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) +{ + npy_intp dims[1] = { *$2 }; + PyObject * array = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$1)); + if (!array) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,array); +} + +/* Typemap suite for (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) + */ +%typemap(in,numinputs=0) + (DIM_TYPE* DIM1 , DATA_TYPE** ARGOUTVIEW_ARRAY1) + (DIM_TYPE dim_temp, DATA_TYPE* data_temp ) +{ + $1 = &dim_temp; + $2 = &data_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility") + (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) +{ + npy_intp dims[1] = { *$1 }; + PyObject * array = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$2)); + if (!array) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,array); +} + +/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) + */ +%typemap(in,numinputs=0) + (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) + (DATA_TYPE* data_temp , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) +{ + $1 = &data_temp; + $2 = &dim1_temp; + $3 = &dim2_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility") + (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) +{ + npy_intp dims[2] = { *$2, *$3 }; + PyObject * array = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); + if (!array) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,array); +} + +/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) + */ +%typemap(in,numinputs=0) + (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEW_ARRAY2) + (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp ) +{ + $1 = &dim1_temp; + $2 = &dim2_temp; + $3 = &data_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility") + (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) +{ + npy_intp dims[2] = { *$1, *$2 }; + PyObject * array = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); + if (!array) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,array); +} + +/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) + */ +%typemap(in,numinputs=0) + (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) + (DATA_TYPE* data_temp , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) +{ + $1 = &data_temp; + $2 = &dim1_temp; + $3 = &dim2_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") + (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) +{ + npy_intp dims[2] = { *$2, *$3 }; + PyObject * obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); + PyArrayObject * array = (PyArrayObject*) obj; + if (!array || !require_fortran(array)) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,obj); +} + +/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) + */ +%typemap(in,numinputs=0) + (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEW_FARRAY2) + (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp ) +{ + $1 = &dim1_temp; + $2 = &dim2_temp; + $3 = &data_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") + (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) +{ + npy_intp dims[2] = { *$1, *$2 }; + PyObject * obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); + PyArrayObject * array = (PyArrayObject*) obj; + if (!array || !require_fortran(array)) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,obj); +} + +/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, + DIM_TYPE* DIM3) + */ +%typemap(in,numinputs=0) + (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) + (DATA_TYPE* data_temp, DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) +{ + $1 = &data_temp; + $2 = &dim1_temp; + $3 = &dim2_temp; + $4 = &dim3_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility") + (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) +{ + npy_intp dims[3] = { *$2, *$3, *$4 }; + PyObject * array = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); + if (!array) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,array); +} + +/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, + DATA_TYPE** ARGOUTVIEW_ARRAY3) + */ +%typemap(in,numinputs=0) + (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) + (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp) +{ + $1 = &dim1_temp; + $2 = &dim2_temp; + $3 = &dim3_temp; + $4 = &data_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility") + (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) +{ + npy_intp dims[3] = { *$1, *$2, *$3 }; + PyObject * array = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$3)); + if (!array) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,array); +} + +/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, + DIM_TYPE* DIM3) + */ +%typemap(in,numinputs=0) + (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) + (DATA_TYPE* data_temp, DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) +{ + $1 = &data_temp; + $2 = &dim1_temp; + $3 = &dim2_temp; + $4 = &dim3_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") + (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) +{ + npy_intp dims[3] = { *$2, *$3, *$4 }; + PyObject * obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); + PyArrayObject * array = (PyArrayObject*) obj; + if (!array || require_fortran(array)) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,obj); +} + +/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, + DATA_TYPE** ARGOUTVIEW_FARRAY3) + */ +%typemap(in,numinputs=0) + (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) + (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp) +{ + $1 = &dim1_temp; + $2 = &dim2_temp; + $3 = &dim3_temp; + $4 = &data_temp; +} +%typemap(argout, + fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") + (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) +{ + npy_intp dims[3] = { *$1, *$2, *$3 }; + PyObject * obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$3)); + PyArrayObject * array = (PyArrayObject*) obj; + if (!array || require_fortran(array)) SWIG_fail; + $result = SWIG_Python_AppendOutput($result,obj); +} + +%enddef /* %numpy_typemaps() macro */ +/* *************************************************************** */ + +/* Concrete instances of the %numpy_typemaps() macro: Each invocation + * below applies all of the typemaps above to the specified data type. + */ +%numpy_typemaps(signed char , NPY_BYTE , int) +%numpy_typemaps(unsigned char , NPY_UBYTE , int) +%numpy_typemaps(short , NPY_SHORT , int) +%numpy_typemaps(unsigned short , NPY_USHORT , int) +%numpy_typemaps(int , NPY_INT , int) +%numpy_typemaps(unsigned int , NPY_UINT , int) +%numpy_typemaps(long , NPY_LONG , int) +%numpy_typemaps(unsigned long , NPY_ULONG , int) +%numpy_typemaps(long long , NPY_LONGLONG , int) +%numpy_typemaps(unsigned long long, NPY_ULONGLONG, int) +%numpy_typemaps(float , NPY_FLOAT , int) +%numpy_typemaps(double , NPY_DOUBLE , int) + +/* *************************************************************** + * The follow macro expansion does not work, because C++ bool is 4 + * bytes and NPY_BOOL is 1 byte + * + * %numpy_typemaps(bool, NPY_BOOL, int) + */ + +/* *************************************************************** + * On my Mac, I get the following warning for this macro expansion: + * 'swig/python detected a memory leak of type 'long double *', no destructor found.' + * + * %numpy_typemaps(long double, NPY_LONGDOUBLE, int) + */ + +/* *************************************************************** + * Swig complains about a syntax error for the following macro + * expansions: + * + * %numpy_typemaps(complex float, NPY_CFLOAT , int) + * + * %numpy_typemaps(complex double, NPY_CDOUBLE, int) + * + * %numpy_typemaps(complex long double, NPY_CLONGDOUBLE, int) + */ + +#endif /* SWIGPYTHON */ diff --git a/advanced/interfacing_with_c/swig_numpy/setup.py b/advanced/interfacing_with_c/swig_numpy/setup.py new file mode 100644 index 0000000..6fb02ca --- /dev/null +++ b/advanced/interfacing_with_c/swig_numpy/setup.py @@ -0,0 +1,6 @@ +from distutils.core import setup, Extension +import numpy + +setup(ext_modules=[Extension("_cos_doubles", + sources=["cos_doubles.c", "cos_doubles.i"], + include_dirs=[numpy.get_include()])]) diff --git a/advanced/interfacing_with_c/swig_numpy/test_cos_doubles.png b/advanced/interfacing_with_c/swig_numpy/test_cos_doubles.png new file mode 120000 index 0000000..bf98de6 --- /dev/null +++ b/advanced/interfacing_with_c/swig_numpy/test_cos_doubles.png @@ -0,0 +1 @@ +../numpy_shared/test_cos_doubles.png \ No newline at end of file diff --git a/advanced/interfacing_with_c/swig_numpy/test_cos_doubles.py b/advanced/interfacing_with_c/swig_numpy/test_cos_doubles.py new file mode 120000 index 0000000..1e10f46 --- /dev/null +++ b/advanced/interfacing_with_c/swig_numpy/test_cos_doubles.py @@ -0,0 +1 @@ +../numpy_shared/test_cos_doubles.py \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/compare_optimizers.py b/advanced/mathematical_optimization/auto_examples/compare_optimizers.py new file mode 100644 index 0000000..754b797 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/compare_optimizers.py @@ -0,0 +1,173 @@ +""" +Comparison of optimizers on various problems. +""" +import functools +import pickle + +import numpy as np +from scipy import optimize +from joblib import Memory + +from cost_functions import mk_quad, mk_gauss, rosenbrock,\ + rosenbrock_prime, rosenbrock_hessian, LoggingFunction, \ + CountingFunction + +def my_partial(function, **kwargs): + f = functools.partial(function, **kwargs) + functools.update_wrapper(f, function) + return f + +methods = { + 'Nelder-mead': my_partial(optimize.fmin, + ftol=1e-12, maxiter=5e3, + xtol=1e-7, maxfun=1e6), + 'Powell': my_partial(optimize.fmin_powell, + ftol=1e-9, maxiter=5e3, + maxfun=1e7), + 'BFGS': my_partial(optimize.fmin_bfgs, + gtol=1e-9, maxiter=5e3), + 'Newton': my_partial(optimize.fmin_ncg, + avextol=1e-7, maxiter=5e3), + 'Conjugate gradient': my_partial(optimize.fmin_cg, + gtol=1e-7, maxiter=5e3), + 'L-BFGS': my_partial(optimize.fmin_l_bfgs_b, + approx_grad=1, factr=10.0, + pgtol=1e-8, maxfun=1e7), + "L-BFGS w f'": my_partial(optimize.fmin_l_bfgs_b, + factr=10.0, + pgtol=1e-8, maxfun=1e7), +} + +############################################################################### + +def bencher(cost_name, ndim, method_name, x0): + cost_function = mk_costs(ndim)[0][cost_name][0] + method = methods[method_name] + f = LoggingFunction(cost_function) + method(f, x0) + this_costs = np.array(f.all_f_i) + return this_costs + + +# Bench with gradients +def bencher_gradient(cost_name, ndim, method_name, x0): + cost_function, cost_function_prime, hessian = mk_costs(ndim)[0][cost_name] + method = methods[method_name] + f_prime = CountingFunction(cost_function_prime) + f = LoggingFunction(cost_function, counter=f_prime.counter) + method(f, x0, f_prime) + this_costs = np.array(f.all_f_i) + return this_costs, np.array(f.counts) + + +# Bench with the hessian +def bencher_hessian(cost_name, ndim, method_name, x0): + cost_function, cost_function_prime, hessian = mk_costs(ndim)[0][cost_name] + method = methods[method_name] + f_prime = CountingFunction(cost_function_prime) + hessian = CountingFunction(hessian, counter=f_prime.counter) + f = LoggingFunction(cost_function, counter=f_prime.counter) + method(f, x0, f_prime, fhess=hessian) + this_costs = np.array(f.all_f_i) + return this_costs, np.array(f.counts) + + +def mk_costs(ndim=2): + costs = { + 'Well-conditioned quadratic': mk_quad(.7, ndim=ndim), + 'Ill-conditioned quadratic': mk_quad(.02, ndim=ndim), + 'Well-conditioned Gaussian': mk_gauss(.7, ndim=ndim), + 'Ill-conditioned Gaussian': mk_gauss(.02, ndim=ndim), + 'Rosenbrock ': (rosenbrock, rosenbrock_prime, rosenbrock_hessian), + } + + rng = np.random.RandomState(0) + starting_points = 4*rng.rand(20, ndim) - 2 + if ndim > 100: + starting_points = starting_points[:10] + return costs, starting_points + +############################################################################### +# Compare methods without gradient +mem = Memory('.', verbose=3) + +if 1: + gradient_less_benchs = dict() + + for ndim in (2, 8, 32, 128): + this_dim_benchs = dict() + costs, starting_points = mk_costs(ndim) + for cost_name, cost_function in costs.iteritems(): + # We don't need the derivative or the hessian + cost_function = cost_function[0] + function_bench = dict() + for x0 in starting_points: + all_bench = list() + # Bench gradient-less + for method_name, method in methods.iteritems(): + if method_name in ('Newton', "L-BFGS w f'"): + continue + this_bench = function_bench.get(method_name, list()) + this_costs = mem.cache(bencher)(cost_name, ndim, + method_name, x0) + if np.all(this_costs > .25*ndim**2*1e-9): + convergence = 2*len(this_costs) + else: + convergence = np.where( + np.diff(this_costs > .25*ndim**2*1e-9) + )[0].max() + 1 + this_bench.append(convergence) + all_bench.append(convergence) + function_bench[method_name] = this_bench + + # Bench with gradients + for method_name, method in methods.iteritems(): + if method_name in ('Newton', 'Powell', 'Nelder-mead', + "L-BFGS"): + continue + this_method_name = method_name + if method_name.endswith(" w f'"): + this_method_name = method_name[:-4] + this_method_name = this_method_name + "\nw f'" + this_bench = function_bench.get(this_method_name, list()) + this_costs, this_counts = mem.cache(bencher_gradient)( + cost_name, ndim, method_name, x0) + if np.all(this_costs > .25*ndim**2*1e-9): + convergence = 2*this_counts.max() + else: + convergence = np.where( + np.diff(this_costs > .25*ndim**2*1e-9) + )[0].max() + 1 + convergence = this_counts[convergence] + this_bench.append(convergence) + all_bench.append(convergence) + function_bench[this_method_name] = this_bench + + # Bench Newton with Hessian + method_name = 'Newton' + this_bench = function_bench.get(method_name, list()) + this_costs = mem.cache(bencher_hessian)(cost_name, ndim, + method_name, x0) + if np.all(this_costs > .25*ndim**2*1e-9): + convergence = 2*len(this_costs) + else: + convergence = np.where( + np.diff(this_costs > .25*ndim**2*1e-9) + )[0].max() + 1 + this_bench.append(convergence) + all_bench.append(convergence) + function_bench[method_name + '\nw Hessian '] = this_bench + + # Normalize across methods + x0_mean = np.mean(all_bench) + for method_name in function_bench: + function_bench[method_name][-1] /= x0_mean + this_dim_benchs[cost_name] = function_bench + gradient_less_benchs[ndim] = this_dim_benchs + print 80*'_' + print 'Done cost %s, ndim %s' % (cost_name, ndim) + print 80*'_' + + pickle.dump(gradient_less_benchs, file('compare_optimizers.pkl', 'w')) + + diff --git a/advanced/mathematical_optimization/auto_examples/compare_optimizers.rst b/advanced/mathematical_optimization/auto_examples/compare_optimizers.rst new file mode 100644 index 0000000..af69337 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/compare_optimizers.rst @@ -0,0 +1,13 @@ + + +.. _example_compare_optimizers.py: + + +Comparison of optimizers on various problems. + + +**Python source code:** :download:`compare_optimizers.py ` + +.. literalinclude:: compare_optimizers.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/cost_functions.py b/advanced/mathematical_optimization/auto_examples/cost_functions.py new file mode 100644 index 0000000..3381074 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/cost_functions.py @@ -0,0 +1,159 @@ +""" +Example cost functions or objective functions to optimize. +""" +import numpy as np + +############################################################################### +# Gaussian functions with varying conditionning + +def gaussian(x): + return np.exp(-np.sum(x**2)) + + +def gaussian_prime(x): + return -2*x*np.exp(-np.sum(x**2)) + + +def gaussian_prime_prime(x): + return -2*np.exp(-x**2) + 4*x**2*np.exp(-x**2) + + +def mk_gauss(epsilon, ndim=2): + def f(x): + x = np.asarray(x) + y = x.copy() + y *= np.power(epsilon, np.arange(ndim)) + return -gaussian(.5*y) + 1 + + def f_prime(x): + x = np.asarray(x) + y = x.copy() + scaling = np.power(epsilon, np.arange(ndim)) + y *= scaling + return -.5*scaling*gaussian_prime(.5*y) + + def hessian(x): + epsilon = .07 + x = np.asarray(x) + y = x.copy() + scaling = np.power(epsilon, np.arange(ndim)) + y *= .5*scaling + H = -.25*np.ones((ndim, ndim))*gaussian(y) + d = 4*y*y[:, np.newaxis] + d.flat[::ndim+1] += -2 + H *= d + return H + + return f, f_prime, hessian + +############################################################################### +# Quadratic functions with varying conditionning + +def mk_quad(epsilon, ndim=2): + def f(x): + x = np.asarray(x) + y = x.copy() + y *= np.power(epsilon, np.arange(ndim)) + return .33*np.sum(y**2) + + def f_prime(x): + x = np.asarray(x) + y = x.copy() + scaling = np.power(epsilon, np.arange(ndim)) + y *= scaling + return .33*2*scaling*y + + def hessian(x): + scaling = np.power(epsilon, np.arange(ndim)) + return .33*2*np.diag(scaling) + + return f, f_prime, hessian + + +############################################################################### +# Super ill-conditionned problem: the Rosenbrock function + +def rosenbrock(x): + y = 4*x + y[0] += 1 + y[1:] += 3 + return np.sum(.5*(1 - y[:-1])**2 + (y[1:] - y[:-1]**2)**2) + + +def rosenbrock_prime(x): + y = 4*x + y[0] += 1 + y[1:] += 3 + xm = y[1:-1] + xm_m1 = y[:-2] + xm_p1 = y[2:] + der = np.zeros_like(y) + der[1:-1] = 2*(xm - xm_m1**2) - 4*(xm_p1 - xm**2)*xm - .5*2*(1 - xm) + der[0] = -4*y[0]*(y[1] - y[0]**2) - .5*2*(1 - y[0]) + der[-1] = 2*(y[-1] - y[-2]**2) + return 4*der + + +def rosenbrock_hessian_(x): + x, y = x + x = 4*x + 1 + y = 4*y + 3 + return 4*4*np.array(( + (1 - 4*y + 12*x**2, -4*x), + ( -4*x, 2), + )) + + +def rosenbrock_hessian(x): + y = 4*x + y[0] += 1 + y[1:] += 3 + + H = np.diag(-4*y[:-1], 1) - np.diag(4*y[:-1], -1) + diagonal = np.zeros_like(y) + diagonal[0] = 12*y[0]**2 - 4*y[1] + 2*.5 + diagonal[-1] = 2 + diagonal[1:-1] = 3 + 12*y[1:-1]**2 - 4*y[2:]*.5 + H = H + np.diag(diagonal) + return 4*4*H + + +############################################################################### +# Helpers to wrap the functions + +class LoggingFunction(object): + + def __init__(self, function, counter=None): + self.function = function + if counter is None: + counter = list() + self.counter = counter + self.all_x_i = list() + self.all_y_i = list() + self.all_f_i = list() + self.counts = list() + + def __call__(self, x0): + x_i, y_i = x0[:2] + self.all_x_i.append(x_i) + self.all_y_i.append(y_i) + f_i = self.function(np.asarray(x0)) + self.all_f_i.append(f_i) + self.counter.append('f') + self.counts.append(len(self.counter)) + return f_i + +class CountingFunction(object): + + def __init__(self, function, counter=None): + self.function = function + if counter is None: + counter = list() + self.counter = counter + + def __call__(self, x0): + self.counter.append('f_prime') + return self.function(x0) + + + diff --git a/advanced/mathematical_optimization/auto_examples/cost_functions.rst b/advanced/mathematical_optimization/auto_examples/cost_functions.rst new file mode 100644 index 0000000..0f8837f --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/cost_functions.rst @@ -0,0 +1,13 @@ + + +.. _example_cost_functions.py: + + +Example cost functions or objective functions to optimize. + + +**Python source code:** :download:`cost_functions.py ` + +.. literalinclude:: cost_functions.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_1.png new file mode 100644 index 0000000..b48a0ab Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_2.png b/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_2.png new file mode 100644 index 0000000..0ac5b11 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_2.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_3.png b/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_3.png new file mode 100644 index 0000000..a36b95e Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_3.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_4.png b/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_4.png new file mode 100644 index 0000000..27db4f0 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_1d_optim_4.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_compare_optimizers_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_compare_optimizers_1.png new file mode 100644 index 0000000..7e6ed1c Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_compare_optimizers_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_constraints_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_constraints_1.png new file mode 100644 index 0000000..a29f40b Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_constraints_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_constraints_2.png b/advanced/mathematical_optimization/auto_examples/images/plot_constraints_2.png new file mode 100644 index 0000000..11905ed Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_constraints_2.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_convex_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_convex_1.png new file mode 100644 index 0000000..df7b753 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_convex_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_convex_2.png b/advanced/mathematical_optimization/auto_examples/images/plot_convex_2.png new file mode 100644 index 0000000..81e9775 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_convex_2.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_curve_fit_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_curve_fit_1.png new file mode 100644 index 0000000..dca22e3 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_curve_fit_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_exercise_flat_minimum_0.png b/advanced/mathematical_optimization/auto_examples/images/plot_exercise_flat_minimum_0.png new file mode 100644 index 0000000..3b1cdb3 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_exercise_flat_minimum_0.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_exercise_flat_minimum_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_exercise_flat_minimum_1.png new file mode 100644 index 0000000..94e3678 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_exercise_flat_minimum_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_exercise_ill_conditioned_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_exercise_ill_conditioned_1.png new file mode 100644 index 0000000..5440c12 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_exercise_ill_conditioned_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_0.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_0.png new file mode 100644 index 0000000..d372914 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_0.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_1.png new file mode 100644 index 0000000..521e860 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_10.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_10.png new file mode 100644 index 0000000..05365fe Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_10.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_100.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_100.png new file mode 100644 index 0000000..04953ae Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_100.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_101.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_101.png new file mode 100644 index 0000000..8833035 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_101.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_102.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_102.png new file mode 100644 index 0000000..9e8bb05 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_102.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_103.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_103.png new file mode 100644 index 0000000..1369ed8 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_103.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_104.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_104.png new file mode 100644 index 0000000..cfac3f3 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_104.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_105.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_105.png new file mode 100644 index 0000000..2c7ece9 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_105.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_106.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_106.png new file mode 100644 index 0000000..e4174d1 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_106.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_107.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_107.png new file mode 100644 index 0000000..4cc493c Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_107.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_108.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_108.png new file mode 100644 index 0000000..c346201 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_108.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_109.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_109.png new file mode 100644 index 0000000..4853840 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_109.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_11.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_11.png new file mode 100644 index 0000000..73f7b12 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_11.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_110.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_110.png new file mode 100644 index 0000000..d589fe6 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_110.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_111.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_111.png new file mode 100644 index 0000000..3d4aa6f Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_111.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_112.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_112.png new file mode 100644 index 0000000..ad8ec35 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_112.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_113.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_113.png new file mode 100644 index 0000000..134f225 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_113.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_114.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_114.png new file mode 100644 index 0000000..c04a9c1 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_114.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_115.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_115.png new file mode 100644 index 0000000..e7bad9f Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_115.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_116.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_116.png new file mode 100644 index 0000000..bcd6db1 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_116.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_117.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_117.png new file mode 100644 index 0000000..74dd0eb Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_117.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_118.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_118.png new file mode 100644 index 0000000..13bd4a7 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_118.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_12.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_12.png new file mode 100644 index 0000000..56454ef Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_12.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_13.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_13.png new file mode 100644 index 0000000..6726bb6 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_13.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_14.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_14.png new file mode 100644 index 0000000..135ea62 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_14.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_15.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_15.png new file mode 100644 index 0000000..c0d4f1c Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_15.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_16.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_16.png new file mode 100644 index 0000000..dfd5903 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_16.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_17.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_17.png new file mode 100644 index 0000000..105d28f Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_17.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_18.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_18.png new file mode 100644 index 0000000..7e85ed9 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_18.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_2.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_2.png new file mode 100644 index 0000000..a4554d2 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_2.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_3.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_3.png new file mode 100644 index 0000000..ad759ca Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_3.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_4.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_4.png new file mode 100644 index 0000000..c7ba668 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_4.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_5.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_5.png new file mode 100644 index 0000000..04895ce Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_5.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_6.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_6.png new file mode 100644 index 0000000..c81dc97 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_6.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_7.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_7.png new file mode 100644 index 0000000..58d9199 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_7.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_8.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_8.png new file mode 100644 index 0000000..6f0d739 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_8.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_9.png b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_9.png new file mode 100644 index 0000000..282fc7e Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_gradient_descent_9.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_noisy_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_noisy_1.png new file mode 100644 index 0000000..8ce7619 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_noisy_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_non_bounds_constraints_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_non_bounds_constraints_1.png new file mode 100644 index 0000000..2be4e65 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_non_bounds_constraints_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_smooth_1.png b/advanced/mathematical_optimization/auto_examples/images/plot_smooth_1.png new file mode 100644 index 0000000..5d46e5e Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_smooth_1.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/plot_smooth_2.png b/advanced/mathematical_optimization/auto_examples/images/plot_smooth_2.png new file mode 100644 index 0000000..b18086b Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/plot_smooth_2.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/compare_optimizers.png b/advanced/mathematical_optimization/auto_examples/images/thumb/compare_optimizers.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/compare_optimizers.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/cost_functions.png b/advanced/mathematical_optimization/auto_examples/images/thumb/cost_functions.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/cost_functions.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_1d_optim.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_1d_optim.png new file mode 100644 index 0000000..c139c5e Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_1d_optim.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_compare_optimizers.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_compare_optimizers.png new file mode 100644 index 0000000..9d54081 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_compare_optimizers.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_constraints.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_constraints.png new file mode 100644 index 0000000..ffe4c2c Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_constraints.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_convex.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_convex.png new file mode 100644 index 0000000..2e3f159 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_convex.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_curve_fit.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_curve_fit.png new file mode 100644 index 0000000..6b430f5 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_curve_fit.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_exercise_flat_minimum.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_exercise_flat_minimum.png new file mode 100644 index 0000000..321a7af Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_exercise_flat_minimum.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_exercise_ill_conditioned.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_exercise_ill_conditioned.png new file mode 100644 index 0000000..f8444e9 Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_exercise_ill_conditioned.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_gradient_descent.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_gradient_descent.png new file mode 100644 index 0000000..33744fd Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_gradient_descent.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_noisy.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_noisy.png new file mode 100644 index 0000000..4ac965d Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_noisy.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_non_bounds_constraints.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_non_bounds_constraints.png new file mode 100644 index 0000000..7ec4c8c Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_non_bounds_constraints.png differ diff --git a/advanced/mathematical_optimization/auto_examples/images/thumb/plot_smooth.png b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_smooth.png new file mode 100644 index 0000000..a8e9cde Binary files /dev/null and b/advanced/mathematical_optimization/auto_examples/images/thumb/plot_smooth.png differ diff --git a/advanced/mathematical_optimization/auto_examples/index.rst b/advanced/mathematical_optimization/auto_examples/index.rst new file mode 100644 index 0000000..9c3d1cb --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/index.rst @@ -0,0 +1,96 @@ + +.. raw:: html + + + +Examples +======== + +.. _examples-index: +.. figure:: ./images/thumb/compare_optimizers.png + :target: ./compare_optimizers.html + + :ref:`example_compare_optimizers.py` + +.. figure:: ./images/thumb/cost_functions.png + :target: ./cost_functions.html + + :ref:`example_cost_functions.py` + +.. figure:: ./images/thumb/plot_1d_optim.png + :target: ./plot_1d_optim.html + + :ref:`example_plot_1d_optim.py` + +.. figure:: ./images/thumb/plot_compare_optimizers.png + :target: ./plot_compare_optimizers.html + + :ref:`example_plot_compare_optimizers.py` + +.. figure:: ./images/thumb/plot_constraints.png + :target: ./plot_constraints.html + + :ref:`example_plot_constraints.py` + +.. figure:: ./images/thumb/plot_convex.png + :target: ./plot_convex.html + + :ref:`example_plot_convex.py` + +.. figure:: ./images/thumb/plot_curve_fit.png + :target: ./plot_curve_fit.html + + :ref:`example_plot_curve_fit.py` + +.. figure:: ./images/thumb/plot_exercise_flat_minimum.png + :target: ./plot_exercise_flat_minimum.html + + :ref:`example_plot_exercise_flat_minimum.py` + +.. figure:: ./images/thumb/plot_exercise_ill_conditioned.png + :target: ./plot_exercise_ill_conditioned.html + + :ref:`example_plot_exercise_ill_conditioned.py` + +.. figure:: ./images/thumb/plot_gradient_descent.png + :target: ./plot_gradient_descent.html + + :ref:`example_plot_gradient_descent.py` + +.. figure:: ./images/thumb/plot_noisy.png + :target: ./plot_noisy.html + + :ref:`example_plot_noisy.py` + +.. figure:: ./images/thumb/plot_non_bounds_constraints.png + :target: ./plot_non_bounds_constraints.html + + :ref:`example_plot_non_bounds_constraints.py` + +.. figure:: ./images/thumb/plot_smooth.png + :target: ./plot_smooth.html + + :ref:`example_plot_smooth.py` + + +.. raw:: html + +
    + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_1d_optim.py b/advanced/mathematical_optimization/auto_examples/plot_1d_optim.py new file mode 100644 index 0000000..9f5be5d --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_1d_optim.py @@ -0,0 +1,54 @@ +""" +Illustration of 1D optimization: Brent's method +""" + +import numpy as np +import pylab as pl +from scipy import optimize + +x = np.linspace(-1, 3, 100) +x_0 = np.exp(-1) + +def f(x): + return (x - x_0)**2 + epsilon*np.exp(-5*(x - .5 - x_0)**2) + +for epsilon in (0, 1): + pl.figure(figsize=(3, 2.5)) + pl.axes([0, 0, 1, 1]) + + # A convex function + pl.plot(x, f(x), linewidth=2) + + # Apply brent method. To have access to the iteration, do this in an + # artificial way: allow the algorithm to iter only once + all_x = list() + all_y = list() + for iter in range(30): + out = optimize.brent(f, brack=(-5, 2.9, 4.5), maxiter=iter, + full_output=True, + tol=np.finfo(1.).eps) + if iter != out[-2]: + print 'Converged at ', iter + break + this_x = out[0] + all_x.append(this_x) + all_y.append(f(this_x)) + if iter < 6: + pl.text(this_x - .05*np.sign(this_x) - .05, + f(this_x) + 1.2*(.3 - iter % 2), iter + 1, + size=12) + + pl.plot(all_x[:10], all_y[:10], 'k+', markersize=12, markeredgewidth=2) + + pl.plot(all_x[-1], all_y[-1], 'rx', markersize=12) + pl.axis('off') + pl.ylim(ymin=-1, ymax=8) + + pl.figure(figsize=(4, 3)) + pl.semilogy(np.abs(all_y - all_y[-1]), linewidth=2) + pl.ylabel('Error on f(x)') + pl.xlabel('Iteration') + pl.tight_layout() + +pl.show() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_1d_optim.rst b/advanced/mathematical_optimization/auto_examples/plot_1d_optim.rst new file mode 100644 index 0000000..edd01f3 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_1d_optim.rst @@ -0,0 +1,38 @@ + + +.. _example_plot_1d_optim.py: + + +Illustration of 1D optimization: Brent's method + + + +.. rst-class:: horizontal + + + * + + .. image:: images/plot_1d_optim_2.png + :scale: 50 + + * + + .. image:: images/plot_1d_optim_1.png + :scale: 50 + + * + + .. image:: images/plot_1d_optim_4.png + :scale: 50 + + * + + .. image:: images/plot_1d_optim_3.png + :scale: 50 + + +**Python source code:** :download:`plot_1d_optim.py ` + +.. literalinclude:: plot_1d_optim.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.py b/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.py new file mode 100644 index 0000000..275c981 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.py @@ -0,0 +1,59 @@ +import pickle + +import numpy as np +import pylab as pl + +results = pickle.load(file('compare_optimizers.pkl')) +#results = pickle.load(file('compare_optimizers_gradients.pkl')) +n_methods = len(results.values()[0]['Rosenbrock ']) +n_dims = len(results) + +symbols = 'o>*Ds' + +pl.figure(1, figsize=(10, 4)) +pl.clf() + +colors = pl.cm.Spectral(np.linspace(0, 1, n_dims))[:, :3] + +method_names = results.values()[0]['Rosenbrock '].keys() +method_names.sort(key=lambda x: x[::-1], reverse=True) + +for n_dim_index, ((n_dim, n_dim_bench), color) in enumerate( + zip(sorted(results.items()), colors)): + for (cost_name, cost_bench), symbol in zip(sorted(n_dim_bench.items()), + symbols): + for method_index, method_name, in enumerate(method_names): + this_bench = cost_bench[method_name] + bench = np.mean(this_bench) + pl.semilogy([method_index + .1*n_dim_index, ], [bench, ], + marker=symbol, color=color) + +# Create a legend for the problem type +for cost_name, symbol in zip(sorted(n_dim_bench.keys()), + symbols): + pl.semilogy([-10, ], [0, ], symbol, color='.5', + label=cost_name) + +pl.xticks(np.arange(n_methods), method_names, size=11) +pl.xlim(-.2, n_methods - .5) +pl.legend(loc='best', numpoints=1, handletextpad=0, prop=dict(size=12), + frameon=False) +pl.ylabel('# function calls (a.u.)') + +# Create a second legend for the problem dimensionality +pl.twinx() + +for n_dim, color in zip(sorted(results.keys()), colors): + pl.plot([-10, ], [0, ], 'o', color=color, + label='# dim: %i' % n_dim) +pl.legend(loc=(.47, .07), numpoints=1, handletextpad=0, prop=dict(size=12), + frameon=False, ncol=2) +pl.xlim(-.2, n_methods - .5) + +pl.xticks(np.arange(n_methods), method_names) +pl.yticks(()) + +pl.tight_layout() +pl.show() + + diff --git a/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.rst b/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.rst new file mode 100644 index 0000000..f45d9cf --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_compare_optimizers.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_compare_optimizers.py: + + + + +.. image:: images/plot_compare_optimizers_1.png + :align: center + + +**Python source code:** :download:`plot_compare_optimizers.py ` + +.. literalinclude:: plot_compare_optimizers.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_constraints.py b/advanced/mathematical_optimization/auto_examples/plot_constraints.py new file mode 100644 index 0000000..b785819 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_constraints.py @@ -0,0 +1,62 @@ +""" +Optimization with constraints +""" +import numpy as np +import pylab as pl +from scipy import optimize + +x, y = np.mgrid[-2.9:5.8:.05, -2.5:5:.05] +x = x.T +y = y.T + +for i in (1, 2): + # Create 2 figure: only the second one will have the optimization + # path + pl.figure(i, figsize=(3, 2.5)) + pl.clf() + pl.axes([0, 0, 1, 1]) + + contours = pl.contour(np.sqrt((x - 3)**2 + (y - 2)**2), + extent=[-3, 6, -2.5, 5], + cmap=pl.cm.gnuplot) + pl.clabel(contours, + inline=1, + fmt='%1.1f', + fontsize=14) + pl.plot([-1.5, -1.5, 1.5, 1.5, -1.5], + [-1.5, 1.5, 1.5, -1.5, -1.5], 'k', linewidth=2) + pl.fill_between([ -1.5, 1.5], + [ -1.5, -1.5], + [ 1.5, 1.5], + color='.8') + pl.axvline(0, color='k') + pl.axhline(0, color='k') + + pl.text(-.9, 4.4, '$x_2$', size=20) + pl.text(5.6, -.6, '$x_1$', size=20) + pl.axis('equal') + pl.axis('off') + +# And now plot the optimization path +accumulator = list() + +def f(x): + # Store the list of function calls + accumulator.append(x) + return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2) + + +# We don't use the gradient, as with the gradient, L-BFGS is too fast, +# and finds the optimum without showing us a pretty path +def f_prime(x): + r = np.sqrt((x[0] - 3)**2 + (x[0] - 2)**2) + return np.array(((x[0] - 3)/r, (x[0] - 2)/r)) + +optimize.fmin_l_bfgs_b(f, np.array([0, 0]), approx_grad=1, + bounds=((-1.5, 1.5), (-1.5, 1.5))) + +accumulated = np.array(accumulator) +pl.plot(accumulated[:, 0], accumulated[:, 1]) + +pl.show() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_constraints.rst b/advanced/mathematical_optimization/auto_examples/plot_constraints.rst new file mode 100644 index 0000000..43974a0 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_constraints.rst @@ -0,0 +1,28 @@ + + +.. _example_plot_constraints.py: + + +Optimization with constraints + + + +.. rst-class:: horizontal + + + * + + .. image:: images/plot_constraints_1.png + :scale: 50 + + * + + .. image:: images/plot_constraints_2.png + :scale: 50 + + +**Python source code:** :download:`plot_constraints.py ` + +.. literalinclude:: plot_constraints.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_convex.py b/advanced/mathematical_optimization/auto_examples/plot_convex.py new file mode 100644 index 0000000..6fcd969 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_convex.py @@ -0,0 +1,43 @@ +""" +Definition of a convex function +""" + +import numpy as np +import pylab as pl + +x = np.linspace(-1, 2) + +pl.figure(1, figsize=(3, 2.5)) +pl.clf() + +# A convex function +pl.plot(x, x**2, linewidth=2) +pl.text(-.7, -.6**2, '$f$', size=20) + +# The tangent in one point +pl.plot(x, 2*x - 1) +pl.plot(1, 1, 'k+') +pl.text(.3, -.75, "Tangent to $f$", size=15) +pl.text(1, 1 - .5, 'C', size=15) + +# Convexity as barycenter +pl.plot([.35, 1.85], [.35**2, 1.85**2]) +pl.plot([.35, 1.85], [.35**2, 1.85**2], 'k+') +pl.text(.35 - .2, .35**2 + .1, 'A', size=15) +pl.text(1.85 - .2, 1.85**2, 'B', size=15) + +pl.ylim(ymin=-1) +pl.axis('off') +pl.tight_layout() + +# Convexity as barycenter +pl.figure(2, figsize=(3, 2.5)) +pl.clf() +pl.plot(x, x**2 + np.exp(-5*(x - .5)**2), linewidth=2) +pl.text(-.7, -.6**2, '$f$', size=20) + +pl.ylim(ymin=-1) +pl.axis('off') +pl.tight_layout() +pl.show() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_convex.rst b/advanced/mathematical_optimization/auto_examples/plot_convex.rst new file mode 100644 index 0000000..8445f92 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_convex.rst @@ -0,0 +1,28 @@ + + +.. _example_plot_convex.py: + + +Definition of a convex function + + + +.. rst-class:: horizontal + + + * + + .. image:: images/plot_convex_2.png + :scale: 50 + + * + + .. image:: images/plot_convex_1.png + :scale: 50 + + +**Python source code:** :download:`plot_convex.py ` + +.. literalinclude:: plot_convex.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_curve_fit.py b/advanced/mathematical_optimization/auto_examples/plot_curve_fit.py new file mode 100644 index 0000000..1f03bc1 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_curve_fit.py @@ -0,0 +1,31 @@ +""" +A curve fitting example +""" + +import numpy as np +from scipy import optimize +import pylab as pl + +np.random.seed(0) + +# Our test function +def f(t, omega, phi): + return np.cos(omega * t + phi) + +# Our x and y data +x = np.linspace(0, 3, 50) +y = f(x, 1.5, 1) + .1*np.random.normal(size=50) + +# Fit the model: the parameters omega and phi can be found in the +# `params` vector +params, params_cov = optimize.curve_fit(f, x, y) + +# plot the data and the fitted curve +t = np.linspace(0, 3, 1000) + +pl.figure(1) +pl.clf() +pl.plot(x, y, 'bx') +pl.plot(t, f(t, *params), 'r-') +pl.show() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_curve_fit.rst b/advanced/mathematical_optimization/auto_examples/plot_curve_fit.rst new file mode 100644 index 0000000..0c16d03 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_curve_fit.rst @@ -0,0 +1,18 @@ + + +.. _example_plot_curve_fit.py: + + +A curve fitting example + + + +.. image:: images/plot_curve_fit_1.png + :align: center + + +**Python source code:** :download:`plot_curve_fit.py ` + +.. literalinclude:: plot_curve_fit.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.py b/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.py new file mode 100644 index 0000000..14daab6 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.py @@ -0,0 +1,61 @@ +""" +Finding a minimum in a flat neighborhood +========================================= + +An excercise of finding minimum. This excercise is hard because the +function is very flat around the minimum (all its derivatives are zero). +Thus gradient information is unreliable. + +The function admits a minimum in [0, 0]. The challenge is to get within +1e-7 of this minimum, starting at x0 = [1, 1]. + +The solution that we adopt here is to give up on using gradient or +information based on local differences, and to rely on the Powell +algorithm. With 162 function evaluations, we get to 1e-8 of the +solution. +""" + +import numpy as np +from scipy import optimize +import pylab as pl + +def f(x): + return np.exp(-1/(.01*x[0]**2 + x[1]**2)) + +# A well-conditionned version of f: +def g(x): + return f([10*x[0], x[1]]) + +# The gradient of g. We won't use it here for the optimization. +def g_prime(x): + r = np.sqrt(x[0]**2 + x[1]**2) + return 2/r**3*g(x)*x/r + +x_min = optimize.fmin_powell(g, [1, 1], xtol=1e-10) + +############################################################################### +# Some pretty plotting + +pl.figure(0) +pl.clf() +t = np.linspace(-1.1, 1.1, 100) +pl.plot(t, f([0, t])) + +pl.figure(1) +pl.clf() +X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] +pl.imshow(f([X, Y]).T, cmap=pl.cm.gray_r, extent=[-1.5, 1.5, -1.1, 1.1], + origin='lower') +pl.contour(X, Y, f([X, Y]), cmap=pl.cm.gnuplot) + +# Plot the gradient +dX, dY = g_prime([.1*X[::5, ::5], Y[::5, ::5]]) +# Adjust for our preconditioning +dX *= .1 +pl.quiver(X[::5, ::5], Y[::5, ::5], dX, dY, color='.5') + +# Plot our solution +pl.plot(x_min[0], x_min[1], 'r+', markersize=15) + +pl.show() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.rst b/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.rst new file mode 100644 index 0000000..6780c86 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_exercise_flat_minimum.rst @@ -0,0 +1,31 @@ + + +.. _example_plot_exercise_flat_minimum.py: + + +Finding a minimum in a flat neighborhood +========================================= + +An excercise of finding minimum. This excercise is hard because the +function is very flat around the minimum (all its derivatives are zero). +Thus gradient information is unreliable. + +The function admits a minimum in [0, 0]. The challenge is to get within +1e-7 of this minimum, starting at x0 = [1, 1]. + +The solution that we adopt here is to give up on using gradient or +information based on local differences, and to rely on the Powell +algorithm. With 162 function evaluations, we get to 1e-8 of the +solution. + + + +.. image:: images/plot_exercise_flat_minimum_1.png + :align: center + + +**Python source code:** :download:`plot_exercise_flat_minimum.py ` + +.. literalinclude:: plot_exercise_flat_minimum.py + :lines: 17- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.py b/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.py new file mode 100644 index 0000000..6d0398a --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.py @@ -0,0 +1,85 @@ +""" +Alternating optimization +========================= + +The challenge here is that Hessian of the problem is a very +ill-conditioned matrix. This can easily be seen, as the Hessian of the +first term in simply 2*np.dot(K.T, K). Thus the conditioning of the +problem can be judged from looking at the conditioning of K. +""" +import time + +import numpy as np +from scipy import optimize +import pylab as pl + +np.random.seed(0) + +K = np.random.normal(size=(100, 100)) + +def f(x): + return np.sum((np.dot(K, x - 1))**2) + np.sum(x**2)**2 + + +def f_prime(x): + return 2*np.dot(np.dot(K.T, K), x - 1) + 4*np.sum(x**2)*x + + +def hessian(x): + H = 2*np.dot(K.T, K) + 4*2*x*x[:, np.newaxis] + return H + 4*np.eye(H.shape[0])*np.sum(x**2) + + +############################################################################### +# Some pretty plotting + +pl.figure(1) +pl.clf() +Z = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] +# Complete in the additional dimensions with zeros +Z = np.reshape(Z, (2, -1)).copy() +Z.resize((100, Z.shape[-1])) +Z = np.apply_along_axis(f, 0, Z) +Z = np.reshape(Z, X.shape) +pl.imshow(Z.T, cmap=pl.cm.gray_r, extent=[-1.5, 1.5, -1.1, 1.1], + origin='lower') +pl.contour(X, Y, Z, cmap=pl.cm.gnuplot) + +# A reference but slow solution: +t0 = time.time() +x_ref = optimize.fmin_powell(f, K[0], xtol=1e-10, ftol=1e-6, disp=0) +print ' Powell: time %.2fs' % (time.time() - t0) +f_ref = f(x_ref) + +# Compare different approaches +t0 = time.time() +x_bfgs = optimize.fmin_bfgs(f, K[0], disp=0)[0] +print ' BFGS: time %.2fs, x error %.2f, f error %.2f' % (time.time() - t0, + np.sqrt(np.sum((x_bfgs - x_ref)**2)), f(x_bfgs) - f_ref) + +t0 = time.time() +x_l_bfgs = optimize.fmin_l_bfgs_b(f, K[0], approx_grad=1, disp=0)[0] +print ' L-BFGS: time %.2fs, x error %.2f, f error %.2f' % (time.time() - t0, + np.sqrt(np.sum((x_l_bfgs - x_ref)**2)), f(x_l_bfgs) - f_ref) + + +t0 = time.time() +x_bfgs = optimize.fmin_bfgs(f, K[0], f_prime, disp=0)[0] +print " BFGS w f': time %.2fs, x error %.2f, f error %.2f" % ( + time.time() - t0, np.sqrt(np.sum((x_bfgs - x_ref)**2)), + f(x_bfgs) - f_ref) + +t0 = time.time() +x_l_bfgs = optimize.fmin_l_bfgs_b(f, K[0], f_prime, disp=0)[0] +print "L-BFGS w f': time %.2fs, x error %.2f, f error %.2f" % ( + time.time() - t0, np.sqrt(np.sum((x_l_bfgs - x_ref)**2)), + f(x_l_bfgs) - f_ref) + +t0 = time.time() +x_newton = optimize.fmin_ncg(f, K[0], f_prime, fhess=hessian, disp=0)[0] +print " Newton: time %.2fs, x error %.2f, f error %.2f" % ( + time.time() - t0, np.sqrt(np.sum((x_newton - x_ref)**2)), + f(x_newton) - f_ref) + +pl.show() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.rst b/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.rst new file mode 100644 index 0000000..0db4bce --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_exercise_ill_conditioned.rst @@ -0,0 +1,24 @@ + + +.. _example_plot_exercise_ill_conditioned.py: + + +Alternating optimization +========================= + +The challenge here is that Hessian of the problem is a very +ill-conditioned matrix. This can easily be seen, as the Hessian of the +first term in simply 2*np.dot(K.T, K). Thus the conditioning of the +problem can be judged from looking at the conditioning of K. + + + +.. image:: images/plot_exercise_ill_conditioned_1.png + :align: center + + +**Python source code:** :download:`plot_exercise_ill_conditioned.py ` + +.. literalinclude:: plot_exercise_ill_conditioned.py + :lines: 10- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.py b/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.py new file mode 100644 index 0000000..fed7fe1 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.py @@ -0,0 +1,232 @@ +""" +Demo gradient descent +""" +import numpy as np +import pylab as pl +from scipy import optimize + +from cost_functions import mk_quad, mk_gauss, rosenbrock,\ + rosenbrock_prime, rosenbrock_hessian, LoggingFunction,\ + CountingFunction + +x_min, x_max = -1, 2 +y_min, y_max = 2.25/3*x_min - .2, 2.25/3*x_max - .2 + +############################################################################### +# A formatter to print values on contours +def super_fmt(value): + if value > 1: + if np.abs(int(value) - value) < .1: + out = '$10^{%.1i}$' % value + else: + out = '$10^{%.1f}$' % value + else: + value = np.exp(value - .01) + if value > .1: + out = '%1.1f' % value + elif value > .01: + out = '%.2f' % value + else: + out = '%.2e' % value + return out + +############################################################################### +# A gradient descent algorithm +# do not use: its a toy, use scipy's optimize.fmin_cg + +def gradient_descent(x0, f, f_prime, hessian=None, adaptative=False): + x_i, y_i = x0 + all_x_i = list() + all_y_i = list() + all_f_i = list() + + for i in range(1, 100): + all_x_i.append(x_i) + all_y_i.append(y_i) + all_f_i.append(f([x_i, y_i])) + dx_i, dy_i = f_prime(np.asarray([x_i, y_i])) + if adaptative: + # Compute a step size using a line_search to satisfy the Wolf + # conditions + step = optimize.line_search(f, f_prime, + np.r_[x_i, y_i], -np.r_[dx_i, dy_i], + np.r_[dx_i, dy_i], c2=.05) + step = step[0] + else: + step = 1 + x_i += - step*dx_i + y_i += - step*dy_i + if np.abs(all_f_i[-1]) < 1e-16: + break + return all_x_i, all_y_i, all_f_i + + +def gradient_descent_adaptative(x0, f, f_prime, hessian=None): + return gradient_descent(x0, f, f_prime, adaptative=True) + + +def conjugate_gradient(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + optimize.fmin_cg(f, x0, f_prime, callback=store, gtol=1e-12) + return all_x_i, all_y_i, all_f_i + + +def newton_cg(x0, f, f_prime, hessian): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + optimize.fmin_ncg(f, x0, f_prime, fhess=hessian, callback=store, + avextol=1e-12) + return all_x_i, all_y_i, all_f_i + + +def bfgs(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + optimize.fmin_bfgs(f, x0, f_prime, callback=store, gtol=1e-12) + return all_x_i, all_y_i, all_f_i + + +def powell(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + optimize.fmin_powell(f, x0, callback=store, ftol=1e-12) + return all_x_i, all_y_i, all_f_i + + +def nelder_mead(x0, f, f_prime, hessian=None): + all_x_i = [x0[0]] + all_y_i = [x0[1]] + all_f_i = [f(x0)] + def store(X): + x, y = X + all_x_i.append(x) + all_y_i.append(y) + all_f_i.append(f(X)) + optimize.fmin(f, x0, callback=store, ftol=1e-12) + return all_x_i, all_y_i, all_f_i + + + + +############################################################################### +# Run different optimizers on these problems +levels = dict() + +for index, ((f, f_prime, hessian), optimizer) in enumerate(( + (mk_quad(.7), gradient_descent), + (mk_quad(.7), gradient_descent_adaptative), + (mk_quad(.02), gradient_descent), + (mk_quad(.02), gradient_descent_adaptative), + (mk_gauss(.02), gradient_descent_adaptative), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), + gradient_descent_adaptative), + (mk_gauss(.02), conjugate_gradient), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), + conjugate_gradient), + (mk_quad(.02), newton_cg), + (mk_gauss(.02), newton_cg), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), + newton_cg), + (mk_quad(.02), bfgs), + (mk_gauss(.02), bfgs), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), + bfgs), + (mk_quad(.02), powell), + (mk_gauss(.02), powell), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), + powell), + (mk_gauss(.02), nelder_mead), + ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), + nelder_mead), + )): + + # Compute a gradient-descent + x_i, y_i = 1.6, 1.1 + counting_f_prime = CountingFunction(f_prime) + counting_hessian = CountingFunction(hessian) + logging_f = LoggingFunction(f, counter=counting_f_prime.counter) + all_x_i, all_y_i, all_f_i = optimizer(np.array([x_i, y_i]), + logging_f, counting_f_prime, + hessian=counting_hessian) + + # Plot the contour plot + if not max(all_y_i) < y_max: + x_min *= 1.2 + x_max *= 1.2 + y_min *= 1.2 + y_max *= 1.2 + x, y = np.mgrid[x_min:x_max:100j, y_min:y_max:100j] + x = x.T + y = y.T + + pl.figure(index, figsize=(3, 2.5)) + pl.clf() + pl.axes([0, 0, 1, 1]) + + X = np.concatenate((x[np.newaxis, ...], y[np.newaxis, ...]), axis=0) + z = np.apply_along_axis(f, 0, X) + log_z = np.log(z + .01) + pl.imshow(log_z, + extent=[x_min, x_max, y_min, y_max], + cmap=pl.cm.gray_r, origin='lower', + vmax=log_z.min() + 1.5*log_z.ptp()) + contours = pl.contour(log_z, + levels=levels.get(f, None), + extent=[x_min, x_max, y_min, y_max], + cmap=pl.cm.gnuplot, origin='lower') + levels[f] = contours.levels + pl.clabel(contours, inline=1, + fmt=super_fmt, fontsize=14) + + pl.plot(all_x_i, all_y_i, 'b-', linewidth=2) + pl.plot(all_x_i, all_y_i, 'k+') + + pl.plot(logging_f.all_x_i, logging_f.all_y_i, 'k.', markersize=2) + + pl.plot([0], [0], 'rx', markersize=12) + + + pl.xticks(()) + pl.yticks(()) + pl.xlim(x_min, x_max) + pl.ylim(y_min, y_max) + pl.draw() + + pl.figure(index + 100, figsize=(4, 3)) + pl.clf() + pl.semilogy(np.maximum(np.abs(all_f_i), 1e-30), linewidth=2, + label='# iterations') + pl.ylabel('Error on f(x)') + pl.semilogy(logging_f.counts, + np.maximum(np.abs(logging_f.all_f_i), 1e-30), + linewidth=2, color='g', label='# function calls') + pl.legend(loc='upper right', frameon=True, prop=dict(size=11), + borderaxespad=0, handlelength=1.5, handletextpad=.5) + pl.tight_layout() + pl.draw() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.rst b/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.rst new file mode 100644 index 0000000..19bfc8b --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_gradient_descent.rst @@ -0,0 +1,63 @@ + + +.. _example_plot_gradient_descent.py: + + +Demo gradient descent + + + +.. rst-class:: horizontal + + + * + + .. image:: images/plot_gradient_descent_2.png + :scale: 50 + + * + + .. image:: images/plot_gradient_descent_3.png + :scale: 50 + + * + + .. image:: images/plot_gradient_descent_8.png + :scale: 50 + + * + + .. image:: images/plot_gradient_descent_5.png + :scale: 50 + + * + + .. image:: images/plot_gradient_descent_9.png + :scale: 50 + + * + + .. image:: images/plot_gradient_descent_6.png + :scale: 50 + + * + + .. image:: images/plot_gradient_descent_7.png + :scale: 50 + + * + + .. image:: images/plot_gradient_descent_1.png + :scale: 50 + + * + + .. image:: images/plot_gradient_descent_4.png + :scale: 50 + + +**Python source code:** :download:`plot_gradient_descent.py ` + +.. literalinclude:: plot_gradient_descent.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_noisy.py b/advanced/mathematical_optimization/auto_examples/plot_noisy.py new file mode 100644 index 0000000..7091775 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_noisy.py @@ -0,0 +1,26 @@ +""" +Noisy vs non-noisy +""" +import numpy as np +import pylab as pl + +np.random.seed(0) + +x = np.linspace(-5, 5, 101) +x_ = np.linspace(-5, 5, 31) + +def f(x): + return -np.exp(-x**2) + +# A smooth function +pl.figure(1, figsize=(3, 2.5)) +pl.clf() + +pl.plot(x_, f(x_) + .2*np.random.normal(size=31), linewidth=2) +pl.plot(x, f(x), linewidth=2) + +pl.ylim(ymin=-1.3) +pl.axis('off') +pl.tight_layout() +pl.show() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_noisy.rst b/advanced/mathematical_optimization/auto_examples/plot_noisy.rst new file mode 100644 index 0000000..1d54100 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_noisy.rst @@ -0,0 +1,18 @@ + + +.. _example_plot_noisy.py: + + +Noisy vs non-noisy + + + +.. image:: images/plot_noisy_1.png + :align: center + + +**Python source code:** :download:`plot_noisy.py ` + +.. literalinclude:: plot_noisy.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.py b/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.py new file mode 100644 index 0000000..41ee252 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.py @@ -0,0 +1,56 @@ +""" +Optimization with general constraints using SLSQP and cobyla +""" +import numpy as np +import pylab as pl +from scipy import optimize + +x, y = np.mgrid[-2.03:4.2:.04, -1.6:3.2:.04] +x = x.T +y = y.T + +pl.figure(1, figsize=(3, 2.5)) +pl.clf() +pl.axes([0, 0, 1, 1]) + +contours = pl.contour(np.sqrt((x - 3)**2 + (y - 2)**2), + extent=[-2.03, 4.2, -1.6, 3.2], + cmap=pl.cm.gnuplot) +pl.clabel(contours, + inline=1, + fmt='%1.1f', + fontsize=14) +pl.plot([-1.5, 0, 1.5, 0, -1.5], + [ 0, 1.5, 0, -1.5, 0], 'k', linewidth=2) +pl.fill_between([ -1.5, 0, 1.5], + [ 0, -1.5, 0], + [ 0, 1.5, 0], + color='.8') +pl.axvline(0, color='k') +pl.axhline(0, color='k') + +pl.text(-.9, 2.8, '$x_2$', size=20) +pl.text(3.6, -.6, '$x_1$', size=20) +pl.axis('tight') +pl.axis('off') + +# And now plot the optimization path +accumulator = list() + +def f(x): + # Store the list of function calls + accumulator.append(x) + return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2) + + +def constraint(x): + return np.atleast_1d(1.5 - np.sum(np.abs(x))) + +optimize.fmin_slsqp(f, np.array([0, 0]), + ieqcons=[constraint, ]) + +accumulated = np.array(accumulator) +pl.plot(accumulated[:, 0], accumulated[:, 1]) + +pl.show() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.rst b/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.rst new file mode 100644 index 0000000..3ec4d23 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_non_bounds_constraints.rst @@ -0,0 +1,18 @@ + + +.. _example_plot_non_bounds_constraints.py: + + +Optimization with general constraints using SLSQP and cobyla + + + +.. image:: images/plot_non_bounds_constraints_1.png + :align: center + + +**Python source code:** :download:`plot_non_bounds_constraints.py ` + +.. literalinclude:: plot_non_bounds_constraints.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/mathematical_optimization/auto_examples/plot_smooth.py b/advanced/mathematical_optimization/auto_examples/plot_smooth.py new file mode 100644 index 0000000..0ae3591 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_smooth.py @@ -0,0 +1,30 @@ +""" +Smooth vs non-smooth +""" +import numpy as np +import pylab as pl + +x = np.linspace(-1.5, 1.5, 101) + +# A smooth function +pl.figure(1, figsize=(3, 2.5)) +pl.clf() + +pl.plot(x, np.sqrt(.2 + x**2), linewidth=2) +pl.text(-1, 0, '$f$', size=20) + +pl.ylim(ymin=-.2) +pl.axis('off') +pl.tight_layout() + +# A non-smooth function +pl.figure(2, figsize=(3, 2.5)) +pl.clf() +pl.plot(x, np.abs(x), linewidth=2) +pl.text(-1, 0, '$f$', size=20) + +pl.ylim(ymin=-.2) +pl.axis('off') +pl.tight_layout() +pl.show() + diff --git a/advanced/mathematical_optimization/auto_examples/plot_smooth.rst b/advanced/mathematical_optimization/auto_examples/plot_smooth.rst new file mode 100644 index 0000000..794b387 --- /dev/null +++ b/advanced/mathematical_optimization/auto_examples/plot_smooth.rst @@ -0,0 +1,28 @@ + + +.. _example_plot_smooth.py: + + +Smooth vs non-smooth + + + +.. rst-class:: horizontal + + + * + + .. image:: images/plot_smooth_2.png + :scale: 50 + + * + + .. image:: images/plot_smooth_1.png + :scale: 50 + + +**Python source code:** :download:`plot_smooth.py ` + +.. literalinclude:: plot_smooth.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/optimizing/demo-prof.png b/advanced/optimizing/demo-prof.png new file mode 100644 index 0000000..01ca382 Binary files /dev/null and b/advanced/optimizing/demo-prof.png differ diff --git a/advanced/optimizing/demo.py b/advanced/optimizing/demo.py index 9ac8adb..fa9a910 100644 --- a/advanced/optimizing/demo.py +++ b/advanced/optimizing/demo.py @@ -9,7 +9,8 @@ def test(): data = np.random.random((5000, 100)) u, s, v = linalg.svd(data) - pca = np.dot(u[:10, :], data) + pca = np.dot(u[:, :10].T, data) results = fastica(pca.T, whiten=False) -test() +if __name__ == '__main__': + test() diff --git a/advanced/optimizing/demo_opt.py b/advanced/optimizing/demo_opt.py new file mode 100644 index 0000000..cdef6ca --- /dev/null +++ b/advanced/optimizing/demo_opt.py @@ -0,0 +1,16 @@ +# For this example to run, you also need the 'ica.py' file + +import numpy as np +from scipy import linalg + +from ica import fastica + + +def test(): + data = np.random.random((5000, 100)) + u, s, v = linalg.svd(data, full_matrices=False) + pca = np.dot(u[:, :10].T, data) + results = fastica(pca.T, whiten=False) + +if __name__ == '__main__': + test() diff --git a/advanced/optimizing/ica.py b/advanced/optimizing/ica.py old mode 100755 new mode 100644 diff --git a/advanced/optimizing/index.rst b/advanced/optimizing/index.rst index c3c6a3d..0a12001 100644 --- a/advanced/optimizing/index.rst +++ b/advanced/optimizing/index.rst @@ -2,7 +2,7 @@ Optimizing code ================= -.. sidebar:: Donald Knuth +.. sidebar:: Donald Knuth *“Premature optimization is the root of all evil”* @@ -12,7 +12,9 @@ This chapter deals with strategies to make Python code go faster. .. topic:: Prerequisites - * line_profiler (http://packages.python.org/line_profiler/) + * `line_profiler `_ + * `gprof2dot `_ + * `dot utility from Graphviz `_ .. contents:: Chapters contents :local: @@ -37,7 +39,7 @@ Optimization workflow Profiling Python code -========================================== +===================== .. topic:: **No optimization without measuring!** @@ -53,7 +55,7 @@ Timeit In IPython, use ``timeit`` (http://docs.python.org/library/timeit.html) to time elementary operations: .. sourcecode:: ipython - + In [1]: import numpy as np In [2]: a = np.arange(1000) @@ -69,7 +71,7 @@ In IPython, use ``timeit`` (http://docs.python.org/library/timeit.html) to time Use this to guide your choice between strategies. -.. note:: +.. note:: For long running calls, using ``%time`` instead of ``%timeit``; it is less precise but faster @@ -82,6 +84,20 @@ Useful when you have a large program to profile, for example the .. literalinclude:: demo.py + +.. note:: + This is a combination of two unsupervised learning techniques, principal + component analysis (`PCA + `_) and + independent component analysis + (`ICA`_). PCA + is a technique for dimensionality reduction, i.e. an algorithm to explain + the observed variance in your data using less dimensions. ICA is a source + seperation technique, for example to unmix multiple signals that have been + recorded through multiple sensors. Doing a PCA first and then an ICA can be + useful if you have more sensors than signals. For more information see: + `the FastICA example from scikits-learn `_. + To run it, you also need to download the :download:`ica module `. In IPython we can time the script: @@ -140,23 +156,26 @@ Line-profiler The profiler is great: it tells us which function takes most of the time, but not where it is called. -For this, we use the +For this, we use the `line_profiler `_: in the source file, we decorate a few functions that we want to inspect with -``@profile`` (no need to import it):: +``@profile`` (no need to import it) + +.. sourcecode:: python @profile def test(): - data = np.random.random((5000, 100)) - u, s, v = linalg.svd(data) - pca = np.dot(u[:10, :], data) - results = fastica(pca.T, whiten=False) + data = np.random.random((5000, 100)) + u, s, v = linalg.svd(data) + pca = np.dot(u[: , :10], data) + results = fastica(pca.T, whiten=False) Then we run the script using the `kernprof.py -`_ program, with switches `-l` -and `-v`:: +`_ program, with switches ``-l, --line-by-line`` and ``-v, --view`` to use the line-by-line profiler and view the results in addition to saving them: + +.. sourcecode:: console - ~ $ kernprof.py -l -v demo.py + $ kernprof.py -l -v demo.py Wrote profile results to demo.py.lprof Timer unit: 1e-06 s @@ -167,16 +186,46 @@ and `-v`:: Line # Hits Time Per Hit % Time Line Contents ============================================================== - 5 @profile - 6 def test(): - 7 1 19015 19015.0 0.1 data = np.random.random((5000, 100)) - 8 1 14242163 14242163.0 99.7 u, s, v = linalg.svd(data) - 9 1 10282 10282.0 0.1 pca = np.dot(u[:10, :], data) + 5 @profile + 6 def test(): + 7 1 19015 19015.0 0.1 data = np.random.random((5000, 100)) + 8 1 14242163 14242163.0 99.7 u, s, v = linalg.svd(data) + 9 1 10282 10282.0 0.1 pca = np.dot(u[:10, :], data) 10 1 7799 7799.0 0.1 results = fastica(pca.T, whiten=False) - **The SVD is taking all the time.** We need to optimise this line. +Running ``cProfile`` +-------------------- + +In the IPython example above, IPython simply calls the built-in `Python +profilers `_ ``cProfile`` and +``profile``. This can be useful if you wish to process the profiler output with a +visualization tool. + +.. sourcecode:: console + + $ python -m cProfile -o demo.prof demo.py + +Using the ``-o`` switch will output the profiler results to the file +``demo.prof``. + +Using ``gprof2dot`` +------------------- + +In case you want a more visual representation of the profiler output, you can +use the `gprof2dot `_ tool: + +.. sourcecode:: console + + $ gprof2dot -f pstats demo.prof | dot -Tpng -o demo-prof.png + +Which will produce the following picture: + +.. image:: demo-prof.png + +Which again paints a similar picture as the previous approaches. + Making code go faster ====================== @@ -197,10 +246,10 @@ loop**, that bring in big gains. Example of the SVD ................... -In both examples above, the SVD - -`Singular Value Decomposition `_ +In both examples above, the SVD - +`Singular Value Decomposition `_ - is what -takes most of the time. Indeed, the computational cost of this algorithm is +takes most of the time. Indeed, the computational cost of this algorithm is roughly :math:`n^3` in the size of the input matrix. However, in both of these example, we are not using all the output of @@ -225,6 +274,30 @@ scipy are richer then those in numpy and should be preferred. In [7]: %timeit np.linalg.svd(data, full_matrices=False) 1 loops, best of 3: 293 ms per loop +We can then use this insight to :download:`optimize the previous code `: + +.. literalinclude:: demo_opt.py + :start-line: 9 + :end-line: 13 + +.. sourcecode:: ipython + + In [1]: import demo + + In [2]: %timeit demo. + demo.fastica demo.np demo.prof.pdf demo.py demo.pyc + demo.linalg demo.prof demo.prof.png demo.py.lprof demo.test + + In [2]: %timeit demo.test() + ica.py:65: RuntimeWarning: invalid value encountered in sqrt + W = (u * np.diag(1.0/np.sqrt(s)) * u.T) * W # W = (W * W.T) ^{-1/2} * W + 1 loops, best of 3: 17.5 s per loop + + In [3]: import demo_opt + + In [4]: %timeit demo_opt.test() + 1 loops, best of 3: 208 ms per loop + Real incomplete SVDs, e.g. computing only the first 10 eigenvectors, can be computed with arpack, available in ``scipy.sparse.linalg.eigsh``. @@ -315,7 +388,7 @@ discuss only some commonly encountered tricks to make code faster. This is the reason why Fortran ordering or C ordering may make a big difference on operations: - + .. sourcecode:: ipython In [5]: a = np.random.rand(20, 2**18) @@ -329,7 +402,7 @@ discuss only some commonly encountered tricks to make code faster. In [9]: %timeit np.dot(b, c) 10 loops, best of 3: 84.2 ms per loop - + Note that copying the data to work around this effect may not be worth it: .. sourcecode:: ipython @@ -345,9 +418,9 @@ discuss only some commonly encountered tricks to make code faster. The last resort, once you are sure that all the high-level optimizations have been explored, is to transfer the hot spots, i.e. the few lines or functions in which most of the time is spent, to - compiled code. For compiled code, the preferred option is to use + compiled code. For compiled code, the preferred option is to use `Cython `_: it is easy to transform exiting - Python code in compiled code, and with a good use of the + Python code in compiled code, and with a good use of the `numpy support `_ yields efficient code on numpy arrays, for instance by unrolling loops. @@ -355,3 +428,20 @@ discuss only some commonly encountered tricks to make code faster. For all the above: profile and time your choices. Don't base your optimization on theoretical considerations. + +Additional Links +---------------- + +* If you need to profile memory usage, you could try the `memory_profiler + `_ + +* If you need to profile down into C extensions, you could try using + `gperftools `_ from Python with + `yep `_. + +* If you would like to track performace of your code across time, i.e. as you + make new commits to your repository, you could try: + `vbench `_ + +* If you need some interactive visualization why not try `RunSnakeRun + `_ diff --git a/advanced/scipy_sparse/auto_examples/direct_solve.py b/advanced/scipy_sparse/auto_examples/direct_solve.py new file mode 100644 index 0000000..dbbf17d --- /dev/null +++ b/advanced/scipy_sparse/auto_examples/direct_solve.py @@ -0,0 +1,27 @@ +""" +Construct a 1000x1000 lil_matrix and add some values to it, convert it +to CSR format and solve A x = b for x:and solve a linear system with a +direct solver. +""" +import numpy as np +import scipy.sparse as sps +from matplotlib import pyplot as plt +from scipy.sparse.linalg.dsolve import linsolve + +rand = np.random.rand + +mtx = sps.lil_matrix((1000, 1000), dtype=np.float64) +mtx[0, :100] = rand(100) +mtx[1, 100:200] = mtx[0, :100] +mtx.setdiag(rand(1000)) + +plt.clf() +plt.spy(mtx, marker='.', markersize=2) +plt.show() + +mtx = mtx.tocsr() +rhs = rand(1000) + +x = linsolve.spsolve(mtx, rhs) + +print 'rezidual:', np.linalg.norm(mtx * x - rhs) diff --git a/advanced/scipy_sparse/auto_examples/direct_solve.rst b/advanced/scipy_sparse/auto_examples/direct_solve.rst new file mode 100644 index 0000000..9e3a3af --- /dev/null +++ b/advanced/scipy_sparse/auto_examples/direct_solve.rst @@ -0,0 +1,15 @@ + + +.. _example_direct_solve.py: + + +Construct a 1000x1000 lil_matrix and add some values to it, convert it +to CSR format and solve A x = b for x:and solve a linear system with a +direct solver. + + +**Python source code:** :download:`direct_solve.py ` + +.. literalinclude:: direct_solve.py + :lines: 6- + \ No newline at end of file diff --git a/advanced/scipy_sparse/auto_examples/images/thumb/direct_solve.png b/advanced/scipy_sparse/auto_examples/images/thumb/direct_solve.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/scipy_sparse/auto_examples/images/thumb/direct_solve.png differ diff --git a/advanced/scipy_sparse/auto_examples/images/thumb/lobpcg_sakurai.png b/advanced/scipy_sparse/auto_examples/images/thumb/lobpcg_sakurai.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/scipy_sparse/auto_examples/images/thumb/lobpcg_sakurai.png differ diff --git a/advanced/scipy_sparse/auto_examples/images/thumb/pyamg_with_lobpcg.png b/advanced/scipy_sparse/auto_examples/images/thumb/pyamg_with_lobpcg.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/advanced/scipy_sparse/auto_examples/images/thumb/pyamg_with_lobpcg.png differ diff --git a/advanced/scipy_sparse/auto_examples/index.rst b/advanced/scipy_sparse/auto_examples/index.rst new file mode 100644 index 0000000..6610072 --- /dev/null +++ b/advanced/scipy_sparse/auto_examples/index.rst @@ -0,0 +1,46 @@ + +.. raw:: html + + + +Examples +======== + +.. _examples-index: +.. figure:: ./images/thumb/direct_solve.png + :target: ./direct_solve.html + + :ref:`example_direct_solve.py` + +.. figure:: ./images/thumb/lobpcg_sakurai.png + :target: ./lobpcg_sakurai.html + + :ref:`example_lobpcg_sakurai.py` + +.. figure:: ./images/thumb/pyamg_with_lobpcg.png + :target: ./pyamg_with_lobpcg.html + + :ref:`example_pyamg_with_lobpcg.py` + + +.. raw:: html + +
    + \ No newline at end of file diff --git a/advanced/scipy_sparse/auto_examples/lobpcg_sakurai.py b/advanced/scipy_sparse/auto_examples/lobpcg_sakurai.py new file mode 100644 index 0000000..bfc8fe1 --- /dev/null +++ b/advanced/scipy_sparse/auto_examples/lobpcg_sakurai.py @@ -0,0 +1,51 @@ +from scipy import array, arange, ones, sort, cos, pi, rand, \ + set_printoptions, r_ +from scipy.sparse.linalg import lobpcg +from scipy import sparse +from pylab import loglog, show, xlabel, ylabel, title +set_printoptions(precision=8,linewidth=90) +import time + +def sakurai(n): + """ Example taken from + T. Sakurai, H. Tadano, Y. Inadomi and U. Nagashima + A moment-based method for large-scale generalized eigenvalue problems + Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004) """ + + A = sparse.eye( n, n ) + d0 = array(r_[5,6*ones(n-2),5]) + d1 = -4*ones(n) + d2 = ones(n) + B = sparse.spdiags([d2,d1,d0,d1,d2],[-2,-1,0,1,2],n,n) + + k = arange(1,n+1) + w_ex = sort(1./(16.*pow(cos(0.5*k*pi/(n+1)),4))) # exact eigenvalues + + return A,B, w_ex + +m = 3 # Blocksize + +# +# Large scale +# +n = 2500 +A,B, w_ex = sakurai(n) # Mikota pair +X = rand(n,m) +data=[] +tt = time.clock() +eigs,vecs, resnh = lobpcg(A,X,B, tol=1e-6, maxiter=500, retResidualNormsHistory=1) +data.append(time.clock()-tt) +print 'Results by LOBPCG for n='+str(n) +print +print eigs +print +print 'Exact eigenvalues' +print +print w_ex[:m] +print +print 'Elapsed time',data[0] +loglog(arange(1,n+1),w_ex,'b.') +xlabel(r'Number $i$') +ylabel(r'$\lambda_i$') +title('Eigenvalue distribution') +show() diff --git a/advanced/scipy_sparse/auto_examples/lobpcg_sakurai.rst b/advanced/scipy_sparse/auto_examples/lobpcg_sakurai.rst new file mode 100644 index 0000000..3454f40 --- /dev/null +++ b/advanced/scipy_sparse/auto_examples/lobpcg_sakurai.rst @@ -0,0 +1,11 @@ + + +.. _example_lobpcg_sakurai.py: + + + +**Python source code:** :download:`lobpcg_sakurai.py ` + +.. literalinclude:: lobpcg_sakurai.py + :lines: 2- + \ No newline at end of file diff --git a/advanced/scipy_sparse/auto_examples/pyamg_with_lobpcg.py b/advanced/scipy_sparse/auto_examples/pyamg_with_lobpcg.py new file mode 100644 index 0000000..b8f1ac6 --- /dev/null +++ b/advanced/scipy_sparse/auto_examples/pyamg_with_lobpcg.py @@ -0,0 +1,43 @@ +""" +Compute eigenvectors and eigenvalues using a preconditioned eigensolver + +In this example Smoothed Aggregation (SA) is used to precondition +the LOBPCG eigensolver on a two-dimensional Poisson problem with +Dirichlet boundary conditions. +""" + +import scipy +from scipy.sparse.linalg import lobpcg + +from pyamg import smoothed_aggregation_solver +from pyamg.gallery import poisson + +N = 100 +K = 9 +A = poisson((N,N), format='csr') + +# create the AMG hierarchy +ml = smoothed_aggregation_solver(A) + +# initial approximation to the K eigenvectors +X = scipy.rand(A.shape[0], K) + +# preconditioner based on ml +M = ml.aspreconditioner() + +# compute eigenvalues and eigenvectors with LOBPCG +W,V = lobpcg(A, X, M=M, tol=1e-8, largest=False) + + +#plot the eigenvectors +import pylab + +pylab.figure(figsize=(9,9)) + +for i in range(K): + pylab.subplot(3, 3, i+1) + pylab.title('Eigenvector %d' % i) + pylab.pcolor(V[:,i].reshape(N,N)) + pylab.axis('equal') + pylab.axis('off') +pylab.show() diff --git a/advanced/scipy_sparse/auto_examples/pyamg_with_lobpcg.rst b/advanced/scipy_sparse/auto_examples/pyamg_with_lobpcg.rst new file mode 100644 index 0000000..d7cfebc --- /dev/null +++ b/advanced/scipy_sparse/auto_examples/pyamg_with_lobpcg.rst @@ -0,0 +1,17 @@ + + +.. _example_pyamg_with_lobpcg.py: + + +Compute eigenvectors and eigenvalues using a preconditioned eigensolver + +In this example Smoothed Aggregation (SA) is used to precondition +the LOBPCG eigensolver on a two-dimensional Poisson problem with +Dirichlet boundary conditions. + + +**Python source code:** :download:`pyamg_with_lobpcg.py ` + +.. literalinclude:: pyamg_with_lobpcg.py + :lines: 8- + \ No newline at end of file diff --git a/conf.py b/conf.py index 034b2bc..3a8ce83 100644 --- a/conf.py +++ b/conf.py @@ -49,7 +49,7 @@ doctest_test_doctest_blocks = 'true' # Add any paths that contain templates here, relative to this directory. -templates_path = ['.templates'] +templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' @@ -62,7 +62,7 @@ # General information about the project. project = u"Scipy lecture notes" -copyright = u'2012' +copyright = u'2012,2013' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -78,11 +78,11 @@ version = p.stdout.read().strip() # The full version, including alpha/beta/rc tags. -release = '2012.3 (EuroScipy 2012)' +release = '2013.2 beta (euroscipy 2013)' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -language = 'en' +language = 'es' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: @@ -188,7 +188,7 @@ def __init__(self, **options): # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -# html_static_path = ['themes/scikit-learn/static'] +html_static_path = ['themes/scipy_lectures/static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. @@ -291,7 +291,10 @@ def __init__(self, **options): _python_doc_base: None, 'http://docs.scipy.org/doc/numpy': None, 'http://docs.scipy.org/doc/scipy/reference': None, - 'http://scikit-learn.org/stable': None + 'http://matplotlib.org/': None, + 'http://scikit-learn.org/stable': None, + 'http://scikit-image.org/docs/0.8.0/': None, + 'http://docs.enthought.com/mayavi/mayavi/': None, } extlinks = { @@ -303,3 +306,9 @@ def __init__(self, **options): pngmath_dvipng_args = ['-gamma 1.5', '-D 180', '-bg', 'Transparent'] pngmath_use_preview = True + + +# Add the 'copybutton' javascript, to hide/show the prompt in code +# examples +def setup(app): + app.add_javascript('copybutton.js') diff --git a/data/MV_HFV_012.jpg b/data/MV_HFV_012.jpg old mode 100755 new mode 100644 diff --git a/data/populations.txt b/data/populations.txt index ec43c8f..6de710c 100644 --- a/data/populations.txt +++ b/data/populations.txt @@ -1,4 +1,4 @@ -# year hare lynx carrot +# year hare lynx carrot 1900 30e3 4e3 48300 1901 47.2e3 6.1e3 48200 1902 70.2e3 9.8e3 41500 diff --git a/guide/index.rst b/guide/index.rst index 678e923..9ce1647 100644 --- a/guide/index.rst +++ b/guide/index.rst @@ -1,88 +1,107 @@ .. _guide -================= -How to contribute -================= +=============== +Cómo contribuir +=============== -:authors: Nicolas Rougier +:Autores: Nicolas Rougier -.. topic:: Foreword +.. topic:: Prólogo - Use the ``topic`` keyword for any forewords + Utilice la palabra clave ``topic`` para cualquier prólogo - -.. contents:: Chapters contents +.. contents:: Contenido :local: :depth: 1 +Asegúrese de leer `Documentation style guide`_, `tips, tricks`_ y convenciones sobre el contenido de la documentación y flujo de trabajo. -Make sure to read this `Documentation style guide`_ as well as these -`tips, tricks`_ and conventions about documentation content and workflows. +Cómo colaborar? +=============== +Elija un tema que todavía no está cubierto y escriba así! -How to contribute ? -=================== +Crear un nuevo directorio en ``intro`` o ``advanced``, crear un archivo ``index.rst`` y comenzar a escribir. No se olvide de actualizar el archivo ``scipy-lecture-notes/index.rst`` de tal manera que su nuevo tutorial aparezca en la tabla de contenidos. -Choose a topic that is not yet covered and write it up ! +También hay que tener en cuenta que estos tutoriales pueden ser usados para la enseñanza y las diferentes partes se pueden combinar para formar un curso de Python para computación científica. Queremos que sean muy interactivos y razonablemente cortos (de una a dos horas) o su público podría dormirse mucho antes de que haya terminado de hablar ... -Create a new directory in either the ``intro`` or ``advanded`` part and start -writing into ``index.rst``. Don't forget to also update the ``index.rst`` in -the corresponding part such that your new tutorial appear in the table of -contents. +Por último, pero no menos importante, el objetivo de este material es proporcionar un texto conciso para el aprendizaje de las principales características del ecosistema scipy. Si usted desea contribuir al material de referencia, le sugerimos contribuir a la documentación de los paquetes específicos en los que está interesado. -Also keep in mind that these tutorials are to being taught at different places -and you want them to be quite interactive or your audience might just fall -asleep long before you've finished talking... +Mantengalo conciso: párrafos colapsados +======================================= +La versión HTML se utiliza para mostrarlo en pantalla mientras se enseña. El objetivo es tener el mismo material como en las notas de muestra. Por tanto es necesario mostrarlo de una concisa, con párrafos y oraciones cortas. Sin embargo, a largo plazo, es útil tener párrafos más elaborados que la gente pueda leer y consultar. Para esto, la directiva sphinx ``tip``creará párrafos plegables, que se pueden ocultar durante una presentación oral +.. code-block:: rst -Figures and code examples -========================== + .. tip:: A continuación inserte una discusión en toda regla, que será plegable en la versión HTML. + + Puede extenderse sobre varios párrafos -**We do not check figures in the repository**. -Any figure must be generated from a python script that needs to be named -``plot_xxx.py`` (xxx can be anything of course) and put into the ``examples`` -directory. The generated image will be named from the script name. +Esto hace de la siguiente manera: -.. image:: auto_examples/images/plot_simple.png - :target: auto_examples/plot_simple.html +.. tip:: A continuación inserte una discusión en toda regla, que será plegable en la versión HTML. + + Puede extenderse sobre varios párrafos +Figuras y ejemplos de código +============================ -This is the way to include your image and link it to the code: +**Nosotros no revisamos las figuras en el repositorio.** Cualquier figura generada a partir de un script Python debe ser nombrado como ``plot_xxx.py`` (xxx puede ser cualquier cosa, por supuesto) y debe estar en el directorio ``examples``. La imagen generada se llamará usando el nombre del script. + +.. image:: auto_examples/images/plot_simple_1.png + :target: auto_examples/plot_simple.html + +Esta es la forma de incluir una imagen y vincularla con el código: .. code-block:: rst - .. image:: auto_examples/images/plot_simple.png + .. image:: auto_examples/images/plot_simple_1.png :target: auto_examples/plot_simple.html -You can display the corresponding code using the ``literal-include`` -directive. +Se puede visualizar el código correspondiente utilizando la directiva ``literalinclude``. -.. literal-include:: examples/plot_simple.py +.. literalinclude:: examples/plot_simple.py +.. note:: El código para proporcionar este tipo de inclusión fue adoptado del proyecto scikits.learn y se puede encontrar en ``sphinxext/gen_rst.py``. -Linking to package documentations -================================== +Usando un lenguaje de marcado +============================= -The goal of the scipy lecture notes is not to duplicate or replace the -documentation of the various packages. You should link as much as -possible to the original documentation. For this purpose, you can use the -`:ref:section` sphinx directive, as well as `:func:function_name`, e.g. -:func:`numpy.var`. Sphinx will find the links on the web for you. +Hay tres tipos principales de marcado que se debe utilizar: *cursiva*, **negrita** +y ``fuente fija``. *Cursiva* debe ser utilizado en la introducción a una nueva técnica, **negrita** debe ser utilizado para dar énfasis y ``fuente fija`` para el código fuente. -Chapter, section, subsection, paragraph -======================================= +.. topic:: Ejemplo: + + Cuando se utiliza la *programación orientada a objetos* en Python que se debe *utilizar* la palabra clave ``class`` para definir *clases*. + +El texto anterior en reStructuredText es: -Try to avoid to go below paragraph granularity or your document might become -difficult to read: +.. code-block:: rst + + Cuando se utiliza la *programación orientada a objetos* en Python que se debe *utilizar* la palabra clave ``class`` para definir *clases*. + +Enlaces a documentación del paquete +=================================== + +El objetivo de los apuntes de clase scipy no es duplicar o sustituir la documentación de los diferentes paquetes. Se recomienda crear enlaces a la documentación original. + +Para obtener referencias cruzadas a la documentación API es preferible usar `intersphinx +extension `_. Esto proporciona +las directivas `:mod:`, `:class:` y `:func:` para enlazar los módulos, clases y funciones respectivamente. Por ejemplo, ``:func:`numpy.var``` crea un enlace a :func:`numpy.var`. + +Capítulo, artículo, inciso, párrafo +=================================== + +Trate de evitar párrafos sin estrutuctura o el documento podría llegar a ser difícil de leer: .. code-block:: rst - ============= - Chapter title - ============= + =================== + Título del capítulo + =================== - Sample content. + Contenido de la muestra. Section ======= @@ -93,30 +112,34 @@ difficult to read: Paragraph ......... - And some text. + Y un poco de texto. + + +Usando Github +============= +La forma más fácil de hacer su propia versión de este material didáctico es Github, utilizando el sistema de control de versiones git para mantener su propia versión. Para ello, lo único que tienes que hacer es crear una cuenta en github (este sitio) y hacer clic en el botón *fork*, en la parte superior derecha de esta página. Puede usar ``git pull`` para actualizar tu *fork*. Si quiere contribuir a la versión original, sólo tiene que hacer un *pull request*, utilizando el botón en la parte superior de la página de su fork. +Por favor, abstengase de modificar el Makefile a menos que sea absolutamente necesario. -Admonitions +Advertencias ============ -.. note:: - - This is a note +.. note:: Esta es una nota -.. warning:: +.. warning:: Esta es una advertencia - This is a warning +Limpieza de objetos flotantes +============================= -Clearing floats -================ +Figuras posicionadas con `:align: right` son flotantes. Para limpiar, use -Figures positionned with `:align: right` are float. To flush them, use:: +.. code-block:: rst - |clear-floats| + |clear-floats| -References -========== +Referencias +=========== .. target-notes:: diff --git a/index.rst b/index.rst index f557dd5..72b3b10 100644 --- a/index.rst +++ b/index.rst @@ -16,160 +16,23 @@ Python Scientific Lecture Notes (Spanish translation) .. nice layout in the toc -.. raw:: html - - - - +.. include:: tune_toc.rst .. only:: html - .. sidebar:: Download + .. sidebar:: Descarga - * `PDF, 2 pages per side <./_downloads/PythonScientific.pdf>`_ + * `PDF, 2 páginas por lado <./_downloads/PythonScientific.pdf>`_ - * `PDF, 1 page per side <./_downloads/PythonScientific-simple.pdf>`_ + * `PDF, 1 página por lado <./_downloads/PythonScientific-simple.pdf>`_ - * `HTML and example files `_ + * `HTML y archivos ejemplo `_ - * `Source code (github) `_ + * `Código fuente (github) `_ - .. topic:: This document + .. topic:: Este documento - Teaching material on the scientific Python ecosystem, a quick - introduction to central tools and techniques. The different chapters - each correspond to a 1 to 2 hours course with increasing level of - expertise, from beginner to expert. + Material didáctico para el ecosistema científico Python, una rápida introducción a las herramientas y técnicas centrales. Cada uno de los diferentes capítulos corresponden a un curso de 1 a 2 horas con el aumento de nivel de experiencia, desde principiantes hasta expertos. .. toctree:: :maxdepth: 1 @@ -186,7 +49,7 @@ _____ intro/index.rst advanced/index.rst - + packages/index.rst ____ diff --git a/intro/help/help.rst b/intro/help/help.rst index 7e53e13..894d5ca 100644 --- a/intro/help/help.rst +++ b/intro/help/help.rst @@ -36,7 +36,6 @@ para mostrar únicamente la ayuda y `docstrings`... Tutoriales sobre varios temas además de la API completa con todos los `docstrings` se puede encontrar en el siguiente sitio web. - .. image:: scipy_doc.png :align: center :scale: 80 @@ -57,13 +56,11 @@ para mostrar únicamente la ayuda y `docstrings`... para muchos de los problemas que nos encontramos a menudo, como el ajuste de datos, resolver ecuaciones diferenciales ordinarias, etc. - * La web de Matplotlib http://matplotlib.sourceforge.net/ dispone de una **galeria* con un gran número de gráficos y ejemplos con el código fuente y el gráfico resultante. Esto es muy útil aprender mediante ejemplos. También se encuentra disponible la documentación estándar. - .. image:: matplotlib.png :align: center :scale: 80 @@ -84,7 +81,6 @@ Finalmente, también serían útiles dos posibilidades más "técnicas": con los patrones de búsqueda. Esto es útil, por ejemplo, cuando desconocemos el nombre exacto de una función. - .. sourcecode:: ipython In [3]: import numpy as np @@ -121,21 +117,15 @@ Finalmente, también serían útiles dos posibilidades más "técnicas": os.walk Directory tree generator. - - * Si todo lo anterior falla (y Google no tiene la respuesta)... ¡no hay que desesperarse! Escribe a la lista de correo que se ajuste a tu problema: obtendrás una rápida respuesta si defines correctamente tu problema. A menudo, expertos en `python científico` ofrecen explicaciones muy clarificadoras en las listas de correo. - * **Numpy discussion** (numpy-discussion@scipy.org): todo acerca de arrays - numpy, como manipularlos, preguntas sobre indexación, etc. - + * **Numpy discussion** (numpy-discussion@scipy.org): todo acerca de arrays numpy, como manipularlos, preguntas sobre indexación, etc. - * **SciPy Users List** (scipy-user@scipy.org): cálculos científicos con Python, - procesamiento de datos de alto nivel, en particular con el paquete scipy. + * **SciPy Users List** (scipy-user@scipy.org): cálculos científicos con Python, procesamiento de datos de alto nivel, en particular con el paquete scipy. - * matplotlib-users@lists.sourceforge.net para hacer gráficas con - matplotlib. + * matplotlib-users@lists.sourceforge.net para hacer gráficas con matplotlib. diff --git a/intro/image_processing/MV_HFV_012.jpg b/intro/image_processing/MV_HFV_012.jpg old mode 100755 new mode 100644 diff --git a/intro/image_processing/image_processing.rst b/intro/image_processing/image_processing.rst index 3d3246f..c86ed81 100644 --- a/intro/image_processing/image_processing.rst +++ b/intro/image_processing/image_processing.rst @@ -1,257 +1,259 @@ -The submodule dedicated to image processing in scipy is `scipy.ndimage`. :: +El submódulo dedicada al procesamiento de imágenes en scipy es :mod:`scipy.ndimage`. - >>> from scipy import ndimage +.. code-block:: python -Image processing routines may be sorted according to the category of -processing they perform. + >>> from scipy import ndimage +Rutinas de procesamiento de imágenes pueden ser clasificadas de acuerdo a la categoría de procesamiento que realizan. -Geometrical transformations on images -....................................... +Transformaciones geométricas en imágenes +........................................ -Changing orientation, resolution, .. :: +Cambio de orientación, resolución, .. - >>> from scipy import misc - >>> lena = misc.lena() - >>> shifted_lena = ndimage.shift(lena, (50, 50)) - >>> shifted_lena2 = ndimage.shift(lena, (50, 50), mode='nearest') - >>> rotated_lena = ndimage.rotate(lena, 30) - >>> cropped_lena = lena[50:-50, 50:-50] - >>> zoomed_lena = ndimage.zoom(lena, 2) - >>> zoomed_lena.shape - (1024, 1024) +.. code-block:: python -.. image:: image_processing/lena_transforms.png - :align: center + >>> from scipy import misc + >>> lena = misc.lena() + >>> shifted_lena = ndimage.shift(lena, (50, 50)) + >>> shifted_lena2 = ndimage.shift(lena, (50, 50), mode='nearest') + >>> rotated_lena = ndimage.rotate(lena, 30) + >>> cropped_lena = lena[50:-50, 50:-50] + >>> zoomed_lena = ndimage.zoom(lena, 2) + >>> zoomed_lena.shape + (1024, 1024) +.. figure:: image_processing/lena_transforms.png + :align: center + :scale: 70 .. sourcecode:: ipython - In [35]: subplot(151) - Out[35]: + In [35]: subplot(151) + Out[35]: - In [36]: pl.imshow(shifted_lena, cmap=cm.gray) - Out[36]: + In [36]: pl.imshow(shifted_lena, cmap=cm.gray) + Out[36]: - In [37]: axis('off') - Out[37]: (-0.5, 511.5, 511.5, -0.5) + In [37]: axis('off') + Out[37]: (-0.5, 511.5, 511.5, -0.5) - In [39]: # etc. + In [39]: # etc. +Filtrado de imágenes +.................... -Image filtering -................... +.. code-block:: python -:: + >>> from scipy import misc + >>> lena = misc.lena() + >>> import numpy as np + >>> noisy_lena = np.copy(lena).astype(np.float) + >>> noisy_lena += lena.std()*0.5*np.random.standard_normal(lena.shape) + >>> blurred_lena = ndimage.gaussian_filter(noisy_lena, sigma=3) + >>> median_lena = ndimage.median_filter(blurred_lena, size=5) + >>> from scipy import signal + >>> wiener_lena = signal.wiener(blurred_lena, (5,5)) - >>> from scipy import misc - >>> lena = misc.lena() - >>> import numpy as np - >>> noisy_lena = np.copy(lena).astype(np.float) - >>> noisy_lena += lena.std()*0.5*np.random.standard_normal(lena.shape) - >>> blurred_lena = ndimage.gaussian_filter(noisy_lena, sigma=3) - >>> median_lena = ndimage.median_filter(blurred_lena, size=5) - >>> from scipy import signal - >>> wiener_lena = signal.wiener(blurred_lena, (5,5)) - -.. image:: image_processing/filtered_lena.png +.. figure:: image_processing/filtered_lena.png :align: center + :scale: 80 +Muchos otros filtros en :mod:`scipy.ndimage.filters` y :mod:`scipy.signal` se puede aplicar a las imágenes. -Many other filters in ``scipy.ndimage.filters`` and ``scipy.signal`` -can be applied to images. - -.. topic:: Exercise +.. topic:: Ejercicio :class: green - Compare histograms for the different filtered images. + Comparar histogramas para las diferentes imágenes filtradas. -Mathematical morphology -........................ +Morfología matemática +..................... -Mathematical morphology is a mathematical theory that stems from set -theory. It characterizes and transforms geometrical structures. Binary -(black and white) images, in particular, can be transformed using this -theory: the sets to be transformed are the sets of neighboring -non-zero-valued pixels. The theory was also extended to gray-valued images. +Morfología matemática es una teoría derivada de teória de conjuntos. Se caracterizan y transforman las estructuras geométricas. En particular las imágenes binarias (blanco y negro), se pueden transformar mediante esta teoría: los conjuntos para ser transformados son los grupos de píxeles vecinos de valor no cero. La teoría también se extendió a las imágenes en escala de grises. .. image:: image_processing/morpho_mat.png :align: center -Elementary mathematical-morphology operations use a *structuring element* -in order to modify other geometrical structures. - -Let us first generate a structuring element :: - - >>> el = ndimage.generate_binary_structure(2, 1) - >>> el - array([[False, True, False], - [ True, True, True], - [False, True, False]], dtype=bool) - >>> el.astype(np.int) - array([[0, 1, 0], - [1, 1, 1], - [0, 1, 0]]) - -* **Erosion** :: - - >>> a = np.zeros((7,7), dtype=np.int) - >>> a[1:6, 2:5] = 1 - >>> a - array([[0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 0, 0, 0, 0, 0]]) - >>> ndimage.binary_erosion(a).astype(a.dtype) - array([[0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 1, 0, 0, 0], - [0, 0, 0, 1, 0, 0, 0], - [0, 0, 0, 1, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0]]) - >>> #Erosion removes objects smaller than the structure - >>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) - array([[0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0]]) - -* **Dilation** :: - - >>> a = np.zeros((5, 5)) - >>> a[2, 2] = 1 - >>> a - array([[ 0., 0., 0., 0., 0.], - [ 0., 0., 0., 0., 0.], - [ 0., 0., 1., 0., 0.], - [ 0., 0., 0., 0., 0.], - [ 0., 0., 0., 0., 0.]]) - >>> ndimage.binary_dilation(a).astype(a.dtype) - array([[ 0., 0., 0., 0., 0.], - [ 0., 0., 1., 0., 0.], - [ 0., 1., 1., 1., 0.], - [ 0., 0., 1., 0., 0.], - [ 0., 0., 0., 0., 0.]]) - -* **Opening** :: - - >>> a = np.zeros((5,5), dtype=np.int) - >>> a[1:4, 1:4] = 1; a[4, 4] = 1 - >>> a - array([[0, 0, 0, 0, 0], - [0, 1, 1, 1, 0], - [0, 1, 1, 1, 0], - [0, 1, 1, 1, 0], - [0, 0, 0, 0, 1]]) - >>> # Opening removes small objects - >>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(np.int) - array([[0, 0, 0, 0, 0], - [0, 1, 1, 1, 0], - [0, 1, 1, 1, 0], - [0, 1, 1, 1, 0], - [0, 0, 0, 0, 0]]) - >>> # Opening can also smooth corners - >>> ndimage.binary_opening(a).astype(np.int) - array([[0, 0, 0, 0, 0], - [0, 0, 1, 0, 0], - [0, 1, 1, 1, 0], - [0, 0, 1, 0, 0], - [0, 0, 0, 0, 0]]) - -* **Closing:** ``ndimage.binary_closing`` - -.. topic:: Exercise +Operaciones elementales matemático-morfologícas usan un *elemento estructurante* +con el fin de modificar otras estructuras geométricas. + +Primero vamos a generar un elemento estructurante + +.. code-block:: python + + >>> el = ndimage.generate_binary_structure(2, 1) + >>> el + array([[False, True, False], + [True, True, True], + [False, True, False]], dtype=bool) + >>> el.astype(np.int) + array([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]]) + +* **Erosion** + + .. code-block:: python + + >>> a = np.zeros((7,7), dtype=np.int) + >>> a[1:6, 2:5] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.binary_erosion(a).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> #Erosión elimina los objetos más pequeños que la estructura + >>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + +* **Dilatación** + + .. code-block:: python + + >>> a = np.zeros((5, 5)) + >>> a[2, 2] = 1 + >>> a + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> ndimage.binary_dilation(a).astype(a.dtype) + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 1., 1., 1., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + +* **Apertura** + + .. code-block:: python + + >>> a = np.zeros((5,5), dtype=np.int) + >>> a[1:4, 1:4] = 1; a[4, 4] = 1 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 1]]) + >>> #Apertura elimina objetos pequeños + >>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(np.int) + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0]]) + >>> # Opening can also smooth corners + >>> ndimage.binary_opening(a).astype(np.int) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]) + +* **Cierre:** ``ndimage.binary_closing`` + +.. topic:: Ejercicio :class: green - Check that opening amounts to eroding, then dilating. + Compruebe que las cantidades iniciales a erosionar, se dilataran. -An opening operation removes small structures, while a closing operation -fills small holes. Such operations can therefore be used to "clean" an -image. :: +Una operación de apertura elimina estructuras pequeñas, mientras que una operación de cierre rellena pequeños agujeros. Por tanto, estas operaciones pueden ser utilizados para "limpiar" una imagen. - >>> a = np.zeros((50, 50)) - >>> a[10:-10, 10:-10] = 1 - >>> a += 0.25*np.random.standard_normal(a.shape) - >>> mask = a>=0.5 - >>> opened_mask = ndimage.binary_opening(mask) - >>> closed_mask = ndimage.binary_closing(opened_mask) +.. code-block:: python -.. image:: image_processing/morpho.png + >>> a = np.zeros((50, 50)) + >>> a[10:-10, 10:-10] = 1 + >>> a += 0.25*np.random.standard_normal(a.shape) + >>> mask = a>=0.5 + >>> opened_mask = ndimage.binary_opening(mask) + >>> closed_mask = ndimage.binary_closing(opened_mask) + +.. figure:: image_processing/morpho.png :align: center + :scale: 75 -.. topic:: Exercise +.. topic:: Ejercicio :class: green - Check that the area of the reconstructed square is smaller - than the area of the initial square. (The opposite would occur if the - closing step was performed *before* the opening). - -For **gray-valued** images, eroding (resp. dilating) amounts to replacing -a pixel by the minimal (resp. maximal) value among pixels covered by the -structuring element centered on the pixel of interest. :: - - >>> a = np.zeros((7,7), dtype=np.int) - >>> a[1:6, 1:6] = 3 - >>> a[4,4] = 2; a[2,3] = 1 - >>> a - array([[0, 0, 0, 0, 0, 0, 0], - [0, 3, 3, 3, 3, 3, 0], - [0, 3, 3, 1, 3, 3, 0], - [0, 3, 3, 3, 3, 3, 0], - [0, 3, 3, 3, 2, 3, 0], - [0, 3, 3, 3, 3, 3, 0], - [0, 0, 0, 0, 0, 0, 0]]) - >>> ndimage.grey_erosion(a, size=(3,3)) - array([[0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 1, 0, 0], - [0, 0, 3, 2, 2, 0, 0], - [0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0]]) - - -Measurements on images -........................ - -Let us first generate a nice synthetic binary image. :: - - >>> x, y = np.indices((100, 100)) - >>> sig = np.sin(2*np.pi*x/50.)*np.sin(2*np.pi*y/50.)*(1+x*y/50.**2)**2 - >>> mask = sig > 1 - -Now we look for various information about the objects in the image:: - - >>> labels, nb = ndimage.label(mask) - >>> nb - 8 - >>> areas = ndimage.sum(mask, labels, xrange(1, labels.max()+1)) - >>> areas - array([ 190., 45., 424., 278., 459., 190., 549., 424.]) - >>> maxima = ndimage.maximum(sig, labels, xrange(1, labels.max()+1)) - >>> maxima - array([ 1.80238238, 1.13527605, 5.51954079, 2.49611818, - 6.71673619, 1.80238238, 16.76547217, 5.51954079]) - >>> ndimage.find_objects(labels==4) - [(slice(30L, 48L, None), slice(30L, 48L, None))] - >>> sl = ndimage.find_objects(labels==4) - >>> import pylab as pl - >>> pl.imshow(sig[sl[0]]) # doctest: +ELLIPSIS - - - -.. image:: image_processing/measures.png + Compruebe que el área del cuadrado reconstruido es menor que el área del cuadrado inicial. (Lo contrario ocurriría si la etapa de cierre se realiza *antes* que la apertura). + +Para imágenes *en escala de grises*, erosionar (respuesta a dilatar) equivale a la sustitución de un píxel por el valor mínimo (respuesta maximal) entre los píxeles incluidos en el elemento estructurante centrado en el píxel de interés. + +.. code-block:: python + + >>> a = np.zeros((7,7), dtype=np.int) + >>> a[1:6, 1:6] = 3 + >>> a[4,4] = 2; a[2,3] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 3, 3, 1, 3, 3, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 3, 3, 3, 2, 3, 0], + [0, 3, 3, 3, 3, 3, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> ndimage.grey_erosion(a, size=(3,3)) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 3, 2, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + +Mediciones en imágenes +...................... + +Primero vamos a generar una imagen binaria sintética agradable. + +.. code-block:: python + + >>> x, y = np.indices((100, 100)) + >>> sig = np.sin(2*np.pi*x/50.)*np.sin(2*np.pi*y/50.)*(1+x*y/50.**2)**2 + >>> mask = sig > 1 + +Ahora veremos variada información acerca de los objetos en la imagen + +.. code-block:: python + + >>> labels, nb = ndimage.label(mask) + >>> nb + 8 + >>> areas = ndimage.sum(mask, labels, xrange(1, labels.max()+1)) + >>> areas + array([ 190., 45., 424., 278., 459., 190., 549., 424.]) + >>> maxima = ndimage.maximum(sig, labels, xrange(1, labels.max()+1)) + >>> maxima + array([ 1.80238238, 1.13527605, 5.51954079, 2.49611818, + 6.71673619, 1.80238238, 16.76547217, 5.51954079]) + >>> ndimage.find_objects(labels==4) + [(slice(30L, 48L, None), slice(30L, 48L, None))] + >>> sl = ndimage.find_objects(labels==4) + >>> import pylab as pl + >>> pl.imshow(sig[sl[0]]) # doctest: +ELLIPSIS + + +.. figure:: image_processing/measures.png :align: center + :scale: 80 - -See the summary exercise on :ref:`summary_exercise_image_processing` for a more -advanced example. - - +Ver el sumario de ejercicios en :ref:`summary_exercise_image_processing` para una ejemplo más avanzado. diff --git a/intro/index.rst b/intro/index.rst index 554cc5a..8049fbe 100644 --- a/intro/index.rst +++ b/intro/index.rst @@ -1,16 +1,26 @@ -Para empezar con Python para fines científicos -============================================== +Iniciandose en computación científica con Python +================================================ + +Esta parte de *Scipy lecture notes* es una introducción que todo lo que necesita para usar Python en computación científica; como ser sintaxis del lenguaje, cálculo numérico o gráficas. + +|clear-floats| + +_____ + +|clear-floats| + .. include:: ../includes/big_toc_css.rst +.. include:: ../tune_toc.rst + .. toctree:: - :maxdepth: 3 intro.rst language/python_language.rst numpy/index.rst - help/help.rst matplotlib/matplotlib.rst scipy.rst + help/help.rst diff --git a/intro/intro.rst b/intro/intro.rst index 5bdfc14..af932b7 100644 --- a/intro/intro.rst +++ b/intro/intro.rst @@ -1,17 +1,17 @@ -Computación científica con herramientas y flujos de trabajo +Herramientas y flujo de trabajo para computación científica =========================================================== -:autores: Fernando Pérez, Emmanuelle Gouillart, Gaël Varoquaux, Valentin Haenel +:Autores: Fernando Pérez, Emmanuelle Gouillart, Gaël Varoquaux, Valentin Haenel .. .. image:: phd053104s.png :align: center -¿Por qué Python? ----------------- +Por qué Python? +--------------- -¡Cuáles son las necesidades de los científicos? -............................................... +Cuáles son las necesidades de los científicos? +.............................................. * Obtener datos (simulación, experimentos) @@ -46,12 +46,12 @@ Especificaciones de ejecución. * La idea es evitar tener que aprender un nuevo software para cada problema nuevo. - Un ambiente/lenguaje para todo, siempreque sea posible. + Un ambiente/lenguaje para todo, siempre que sea posible. Soluciones existentes ..................... -¿Qué soluciones usan los científicos para trabajar? +Qué soluciones usan los científicos para trabajar? **Lenguajes compilados: C, C++, Fortran, etc.** @@ -107,7 +107,7 @@ Soluciones existentes xmgrace para graficar curvas. Estos programas son muy poderosos, pero están restringidos a un solo tipo de uso, como por ejemplo para hacer gráficos. -**¿Qué hay de Python?** +**Qué hay de Python?** * Ventajas: @@ -117,7 +117,7 @@ Soluciones existentes * Lenguaje bien pensado, lo que permite escribir código muy legible y bien estructurado: "escribimos el código que pensamos". - * Existen muchas bibliotecas para otras tareas, además de para cálculo científico + * Existen muchas bibliotecas para otras tareas, además de cálculo científico (administración de servidores web, acceso al puerto serie, etc.). * Software libre y de acceso abierto, ampliamente difundido con una @@ -141,39 +141,35 @@ completo ambiente de desarrollo para cálculo científico: * **Python**, un lenguaje computacional genérico y moderno - * Lenguaje Python: tipos de datos (``string``, ``int``), control de flujo, - estructuras de datos (listas, diccionarios), patrones, etc. + * Lenguaje Python: tipos de datos (``string``, ``int``), control de flujo, estructuras de datos (listas, diccionarios), patrones, etc. - * Módulos de la biblioteca estándar. + * Módulos de la biblioteca estándar. - * Un gran número de módulos especializados o aplicaciones escritas en - Python: protocolos web, framework para aplicaciones web, etc. ... y - cálculo científico. + * Un gran número de módulos especializados o aplicaciones escritas en Python: protocolos web, framework para aplicaciones web, etc. ... y cálculo científico. - * Herramientas de desarrollo (pruebas automáticas, generación de - documentación) + * Herramientas de desarrollo (pruebas automáticas, generación de documentación) .. image:: snapshot_ipython.png :align: right :scale: 40 -* **IPython**, una **consola de Python** avanzada http://ipython.org/ +* **IPython**, una **consola avanzada de Python** http://ipython.org/ -* **Numpy** : proporciona poderosos objetos de **arrays numéricos** y rutinas +* **Numpy**: proporciona poderosos objetos llamados **arreglos numéricos** y rutinas para manipularlos. http://www.numpy.org/ .. >>> import numpy as np >>> np.random.seed(4) -* **Scipy** : rutinas de alto nivel para procesamiento de datos. +* **Scipy**: rutinas de alto nivel para procesamiento de datos. Optimización, regresión, interpolación, etc. http://www.scipy.org/ .. image:: random_c.jpg :scale: 40 :align: right -* **Matplotlib** : visualización bidimensional, gráficos "listos para publicar" +* **Matplotlib**: visualización bidimensional, gráficos "listos para publicar" http://matplotlib.sourceforge.net/ |clear-floats| @@ -182,14 +178,13 @@ completo ambiente de desarrollo para cálculo científico: :scale: 60 :align: right -* **Mayavi** : visualización tridimensional +* **Mayavi**: visualización tridimensional http://code.enthought.com/projects/mayavi/ |clear-floats| - -El flujo de trabajo interactivo: IPython y un editor de textos --------------------------------------------------------------- +Flujo de trabajo interactivo: IPython y un editor de textos +----------------------------------------------------------- **Trabajo interactivo para probar y entender algoritmos**: En esta sección, describiremos un flujo de trabajo interactivo con @@ -199,15 +194,15 @@ entender algoritmos. Python es un lenguaje multipropósito. Como tal, no existe un ambiente bendito para trabajar ni hay una sola manera de usarlo. Aunque esto hace que sea más difícil para principiantes encontrar su propio camino, esto hace -posible que Python sea usado para escribir programas, en servidores web o +posible que Python sea usado para escribir programas en servidores web o dispositivos embebidos. .. note:: Documento de referencia para esta sección: **IPython user manual:** http://ipython.org/ipython-doc/dev/index.html -Interacción en la línea de comandos -................................... +Interacción con la línea de comandos +.................................... Iniciar `ipython`: @@ -235,12 +230,12 @@ Obteniendo ayuda usando el operador **?** después de un objeto: end: string appended after the last value, default a newline. -Elaboración del algoritmo en un editor de textos +Elaboración de algoritmos en un editor de textos ................................................ Creamos un archivo `mi_fichero.py` en un editor de texto. En EPD (Enthought Python Distribution), puedes usar `Scite`, disponible en el menú de inicio. En -Python(x,y) puedes usar Spyder. En Ubuntu, si todavía no tienes tu editor +Python(x,y) puedes usar Spyder. En Ubuntu, si todavía no tienes un editor favorito, te aconsejamos instalar `Stani's Python editor`. En el archivo, agrega las siguientes líneas:: @@ -271,7 +266,7 @@ Ahora, puedes ejecutarlo en IPython y explorar las variables resultantes: * Un script no es reutilizable, las funciones sí. - * Pensar en términos de funcionas ayuda a dividir el problema en + * Pensar en términos de funciones ayuda a dividir el problema en pequeños bloques. @@ -283,8 +278,7 @@ IPython, pero para que puedas iniciarte queremos darte una breve introducción a características útiles: *historial*, *funciones mágicas* y *autocompletado con tabulador*. -Como una consola UNIX, IPython soporta comandos de historial. Teclea *arriba* -y *abajo* para reutilizar los comandos anteriormente ejecutados: +Al igual que una consola UNIX, IPython cuenta con un historial de comandos. Teclea *arriba* y *abajo* para reutilizar los comandos anteriormente ejecutados: .. sourcecode:: ipython @@ -296,8 +290,8 @@ y *abajo* para reutilizar los comandos anteriormente ejecutados: IPython soporta las llamadas funciones *mágicas* anteponiendo a un comando el caracter ``%``. Por ejemplo, las funciones ``run`` y ``whos`` de la -sección anterior son funciones mágicas. Tened en cuenta que, el ajuste -``automagic``, que está activado por defecto, te permite omitir el signo ``%`` +sección anterior son funciones mágicas. Tenga en cuenta que, el ajuste +``automagic`` está activado por defecto, te permite omitir el signo ``%`` predecesor al comando. De esta forma, puedes solo escribir la función mágica y funcionará. @@ -319,8 +313,8 @@ Otras funciones mágicas útiles son: 10000000 loops, best of 3: 39 ns per loop * ``%cpaste`` te permite pegar código, especialmente aquel que venga de un - sitio web que ha sido precedido por el prompt estándar de Python (o sea - ``>>>``) o con un prompt de IPython (por ejemplo: ``In [3]:``): + sitio web que proceda de la consola estándar de Python (o sea + ``>>>``) o de la consola IPython (por ejemplo: ``In [3]:``): .. sourcecode:: ipython diff --git a/intro/language/assignment.rst b/intro/language/assignment.rst deleted file mode 100644 index b0edf56..0000000 --- a/intro/language/assignment.rst +++ /dev/null @@ -1,61 +0,0 @@ -Assignment operator -=================== - -`Python library reference -`_ -says: - - Assignment statements are used to (re)bind names to values and to - modify attributes or items of mutable objects. - -In short, it works as follows (simple assignment): - -#. an expression on the right hand side is evaluated, the corresponding - object is created/obtained -#. a **name** on the left hand side is assigned, or bound, to the - r.h.s. object - -Things to note: - -* a single object can have several names bound to it: - - .. sourcecode:: ipython - - In [1]: a = [1, 2, 3] - In [2]: b = a - In [3]: a - Out[3]: [1, 2, 3] - In [4]: b - Out[4]: [1, 2, 3] - In [5]: a is b - Out[5]: True - In [6]: b[1] = 'hi!' - In [7]: a - Out[7]: [1, 'hi!', 3] - -* to change a list *in place*, use indexing/slices: - - .. sourcecode:: ipython - - In [1]: a = [1, 2, 3] - In [3]: a - Out[3]: [1, 2, 3] - In [4]: a = ['a', 'b', 'c'] # Creates another object. - In [5]: a - Out[5]: ['a', 'b', 'c'] - In [6]: id(a) - Out[6]: 138641676 - In [7]: a[:] = [1, 2, 3] # Modifies object in place. - In [8]: a - Out[8]: [1, 2, 3] - In [9]: id(a) - Out[9]: 138641676 # Same as in Out[6], yours will differ... - -* the key concept here is **mutable vs. immutable** - - * mutable objects can be changed in place - * immutable objects cannot be modified once created - -A very good and detailed explanation of the above issues can be found -in David M. Beazley's article `Types and Objects in Python -`_. diff --git a/intro/language/basic_types.rst b/intro/language/basic_types.rst index 0b848ac..f475c2b 100644 --- a/intro/language/basic_types.rst +++ b/intro/language/basic_types.rst @@ -1,13 +1,15 @@ -Basic types -============ +Tipos básicos +============= -Numerical types ----------------- +Tipos numéricos +--------------- -Python supports the following numerical, scalar types: +.. tip:: Python soporta los siguientes tipos escalares: :Integer: + .. code-block:: python + >>> 1 + 1 2 >>> a = 4 @@ -16,12 +18,16 @@ Python supports the following numerical, scalar types: :Floats: + .. code-block:: python + >>> c = 2.1 >>> type(c) :Complex: + .. code-block:: python + >>> a = 1.5 + 0.5j >>> a.real 1.5 @@ -32,6 +38,8 @@ Python supports the following numerical, scalar types: :Booleans: + .. code-block:: python + >>> 3 > 4 False >>> test = (3 > 4) @@ -40,284 +48,279 @@ Python supports the following numerical, scalar types: >>> type(test) -A Python shell can therefore replace your pocket calculator, with the -basic arithmetic operations ``+``, ``-``, ``*``, ``/``, ``%`` (modulo) -natively implemented:: +.. tip:: La consola Python puede reemplazar a una calculadora, las operaciones arítmeticas básicas ``+``, ``-``, ``*``, ``/``, ``%`` (módulo) estan implementadas nativamente. - >>> 7 * 3. - 21.0 - >>> 2**10 - 1024 - >>> 8 % 3 - 2 +.. code-block:: python -Type conversion (casting):: + >>> 7 * 3. + 21.0 + >>> 2**10 + 1024 + >>> 8 % 3 + 2 - >>> float(1) - 1.0 +Conversión de tipos (casting) -.. warning:: Integer division +.. code-block:: python - :: + >>> float(1) + 1.0 - >>> 3 / 2 - 1 +.. warning:: División de enteros - **Trick**: use floats:: + .. code-block:: python - >>> 3 / 2. - 1.5 + >>> 3 / 2 + 1 - >>> a = 3 - >>> b = 2 - >>> a / b - 1 - >>> a / float(b) - 1.5 + **Truco**: Use floats + + .. code-block:: python - If you explicitly want integer division use ``//`` + >>> 3 / 2. + 1.5 + >>> a = 3 + >>> b = 2 + >>> a / b + 1 + >>> a / float(b) + 1.5 - >>> 3.0//2 - 1.0 + .. tip:: Si requiere la parte entera de una division use ``//`` + + .. code-block:: python - .. note:: + >>> 3.0 // 2 + 1.0 - The behaviour of the division operator has changed in Python 3. Please - look at the `python3porting - `_ - website for details. + .. note:: El comportamiento del operador división fue cambiado en Python 3. Por favor visite `python3porting `_ para más detalles. -Containers +Contenedores ------------ -Python provides many efficient types of containers, in which collections of -objects can be stored. +.. tip:: Python proporciona muchos tipos eficazes de contenedores, en la que colecciones de objetos pueden ser almacenados. -Lists -~~~~~ +Listas +~~~~~~ -A list is an ordered collection of objects, that may have different -types. For example :: +.. tip:: Una lista es una colección ordenada de objetos, que puede contener diferentes tipos. Por ejemplo: - >>> l = ['red', 'blue', 'green', 'black', 'white'] - >>> type(l) - +.. code-block:: python -Indexing: accessing individual objects contained in the list:: + >>> L = ['rojo', 'azul', 'verde', 'negro', 'blanco'] + >>> type(L) + - >>> l[2] - 'green' +Indexado: acceso individual a objetos contenidos en la lista -Counting from the end with negative indices:: +.. code-block:: python + + >>> L[2] + 'verde' - >>> l[-1] - 'white' - >>> l[-2] - 'black' +Conteo de elementos desde el final con indices negativos -.. warning:: +.. code-block:: python - **Indexing starts at 0** (as in C), not at 1 (as in Fortran or Matlab)! + >>> L[-1] + 'blanco' + >>> L[-2] + 'negro' -Slicing: obtaining sublists of regularly-spaced elements:: +.. warning:: **El indexado empieza en 0** (como en C), no en 1 (como en Fortran o Matlab)! - >>> l - ['red', 'blue', 'green', 'black', 'white'] - >>> l[2:4] - ['green', 'black'] +Segmentación(slicing): Obtener sublistas con elementos regularmente espaciados -.. Warning:: +.. code-block:: python - Note that ``l[start:stop]`` contains the elements with indices ``i`` - such as ``start<= i < stop`` (``i`` ranging from ``start`` to - ``stop-1``). Therefore, ``l[start:stop]`` has ``(stop-start)`` elements. + >>> L + ['rojo', 'azul', 'verde', 'negro', 'blanco'] + >>> L[2:4] + ['verde', 'negro'] -**Slicing syntax**: ``l[start:stop:stride]`` +.. warning:: Note que ``L[inicio:final]`` contiene los elementos con indices ``i`` que pertenecen al intervalo ``inicio<= i < final`` (``i`` es el rango de valores enteros desde ``inicio`` a ``final-1``). Por tanto, ``L[inicio:final]`` tiene elementos ``(final-inicio)``. -All slicing parameters are optional:: +**Sintaxis de segmentación**: ``L[inicio:final:paso]`` - >>> l - ['red', 'blue', 'green', 'black', 'white'] - >>> l[3:] - ['black', 'white'] - >>> l[:3] - ['red', 'blue', 'green'] - >>> l[::2] - ['red', 'green', 'white'] +.. tip:: Los parámetros de segmentación son opcionales -Lists are *mutable* objects and can be modified:: +.. code-block:: python - >>> l[0] = 'yellow' - >>> l - ['yellow', 'blue', 'green', 'black', 'white'] - >>> l[2:4] = ['gray', 'purple'] - >>> l - ['yellow', 'blue', 'gray', 'purple', 'white'] - -.. Note:: + >>> L + ['rojo', 'azul', 'verde', 'negro', 'blanco'] + >>> L[3:] + ['negro', 'blanco'] + >>> L[:3] + ['rojo', 'azul', 'verde'] + >>> L[::2] + ['rojo', 'verde', 'blanco'] - The elements of a list may have different types:: +Las listas son objectos *mutables* y pueden modificarse - >>> l = [3, -200, 'hello'] - >>> l - [3, -200, 'hello'] - >>> l[1], l[2] - (-200, 'hello') +.. code-block:: python - For collections of numerical data that all have the same type, it - is often **more efficient** to use the ``array`` type provided by - the ``numpy`` module. A NumPy array is a chunk of memory - containing fixed-sized items. With NumPy arrays, operations on - elements can be faster because elements are regularly spaced in - memory and more operations are performed through specialized C - functions instead of Python loops. + >>> L[0] = 'amarillo' + >>> L + ['amarillo', 'azul', 'verde', 'negro', 'blanco'] + >>> L[2:4] = ['gris', 'púrpura'] + >>> L + ['amarillo', 'azul', 'gris', 'púrpura', 'blanco'] +.. note:: Los elementos de una lista pueden ser de tipos diferentes -Python offers a large panel of functions to modify lists, -or query them. Here are a few examples; for more details, see -http://docs.python.org/tutorial/datastructures.html#more-on-lists + .. code-block:: python -Add and remove elements:: + >>> L = [3, -200, 'hola'] + >>> L + [3, -200, 'hola'] + >>> L[1], L[2] + (-200, 'hola') - >>> l = ['red', 'blue', 'green', 'black', 'white'] - >>> l.append('pink') - >>> l - ['red', 'blue', 'green', 'black', 'white', 'pink'] - >>> l.pop() # removes and returns the last item - 'pink' - >>> l - ['red', 'blue', 'green', 'black', 'white'] - >>> l.extend(['pink', 'purple']) # extend l, in-place - >>> l - ['red', 'blue', 'green', 'black', 'white', 'pink', 'purple'] - >>> l = l[:-2] - >>> l - ['red', 'blue', 'green', 'black', 'white'] - -Reverse:: - - >>> r = l[::-1] - >>> r - ['white', 'black', 'green', 'blue', 'red'] - >>> r2 = list(l) - >>> r2 - ['red', 'blue', 'green', 'black', 'white'] - >>> r2.reverse() # in-place - >>> r2 - ['white', 'black', 'green', 'blue', 'red'] - -Concatenate and repeat lists:: - - >>> r + l - ['white', 'black', 'green', 'blue', 'red', 'red', 'blue', 'green', 'black', 'white'] - >>> r * 2 - ['white', 'black', 'green', 'blue', 'red', 'white', 'black', 'green', 'blue', 'red'] - -Sort:: - - >>> sorted(r) # new object - ['black', 'blue', 'green', 'red', 'white'] - >>> r - ['white', 'black', 'green', 'blue', 'red'] - >>> r.sort() # in-place - >>> r - ['black', 'blue', 'green', 'red', 'white'] - -.. Note:: **Methods and Object-Oriented Programming** - - The notation ``r.method()`` (``r.sort(), r.append(3), l.pop()``) is our - first example of object-oriented programming (OOP). Being a ``list``, the - object `r` owns the *method* `function` that is called using the notation - **.**. No further knowledge of OOP than understanding the notation **.** is - necessary for going through this tutorial. - - -.. note:: **Discovering methods:** - - Reminder: in Ipython: tab-completion (press tab) - - .. sourcecode:: ipython - - In [28]: r. - r.__add__ r.__iadd__ r.__setattr__ - r.__class__ r.__imul__ r.__setitem__ - r.__contains__ r.__init__ r.__setslice__ - r.__delattr__ r.__iter__ r.__sizeof__ - r.__delitem__ r.__le__ r.__str__ - r.__delslice__ r.__len__ r.__subclasshook__ - r.__doc__ r.__lt__ r.append - r.__eq__ r.__mul__ r.count - r.__format__ r.__ne__ r.extend - r.__ge__ r.__new__ r.index - r.__getattribute__ r.__reduce__ r.insert - r.__getitem__ r.__reduce_ex__ r.pop - r.__getslice__ r.__repr__ r.remove - r.__gt__ r.__reversed__ r.reverse - r.__hash__ r.__rmul__ r.sort - -Strings -~~~~~~~ + .. tip:: Para las colecciones de datos numéricos que tienen el mismo tipo, a menudo es **más eficiente** utilizar el tipo ``arreglo (array)`` proporcionado por el módulo ``numpy``. Un arreglo NumPy es un trozo de memoria que contiene elementos de tamaño fijo. Con arreglos NumPy, las operaciones con elementos son más rápidos porque los elementos están espaciados regularmente en memoria y otras operaciones se realizan a través funciones C especializadas en lugar de bucles Python. -Different string syntaxes (simple, double or triple quotes):: +.. tip:: Python ofrece un gran panel de funciones para modificar las listas, o la consulta a ellos. Éstos son algunos ejemplos; para obtener más detalles, consulte http://docs.python.org/tutorial/datastructures.html#more-on-lists - s = 'Hello, how are you?' - s = "Hi, what's up" - s = '''Hello, # tripling the quotes allows the - how are you''' # the string to span more than one line - s = """Hi, - what's up?""" +Agregar y remover elementos -.. sourcecode:: ipython +.. code-block:: python - In [1]: 'Hi, what's up?' - ------------------------------------------------------------ - File "", line 1 - 'Hi, what's up?' - ^ - SyntaxError: invalid syntax + >>> L = ['rojo', 'azul', 'verde', 'negro', 'blanco'] + >>> L.append('rosado') + >>> L + ['rojo', 'azul', 'verde', 'negro', 'blanco', 'rosado'] + >>> L.pop() # remover y devolver el último item + 'rosado' + >>> L + ['rojo', 'azul', 'verde', 'negro', 'blanco'] + >>> L.extend(['rosado', 'violeta']) # extender L, sobre la marcha + >>> L + ['rojo', 'azul', 'verde', 'negro', 'blanco', 'rosado', 'violeta'] + >>> L = L[:-2] + >>> L + ['rojo', 'azul', 'verde', 'negro', 'blanco'] +Invertir el orden de los elementos (reverse) -The newline character is ``\n``, and the tab character is -``\t``. +.. code-block:: python -Strings are collections like lists. Hence they can be indexed and sliced, -using the same syntax and rules. + >>> r = L[::-1] + >>> r + ['blanco', 'negro', 'verde', 'azul', 'rojo'] + >>> r2 = list(L) + >>> r2 + ['rojo', 'azul', 'verde', 'negro', 'blanco'] + >>> r2.reverse() # reasignando valores + >>> r2 + ['blanco', 'negro', 'verde', 'azul', 'rojo'] -Indexing:: +Concatenar y repetir listas - >>> a = "hello" - >>> a[0] - 'h' - >>> a[1] - 'e' - >>> a[-1] - 'o' +.. code-block:: python + >>> r + L + ['blanco', 'negro', 'verde', 'azul', 'rojo', 'rojo', 'azul', 'verde', 'negro', 'blanco'] + >>> r * 2 + ['blanco', 'negro', 'verde', 'azul', 'rojo', 'blanco', 'negro', 'verde', 'azul', 'rojo'] -(Remember that negative indices correspond to counting from the right -end.) +.. tip:: Ordenar en forma ascendente -Slicing:: +.. code-block:: python + >>> sorted(r) # nuevo objecto + ['azul', 'blanco', 'negro', 'rojo', 'verde'] + >>> r + ['blanco', 'negro', 'verde', 'azul', 'rojo'] + >>> r.sort() # reasignando elementos + >>> r + ['azul', 'blanco', 'negro', 'rojo', 'verde'] - >>> a = "hello, world!" - >>> a[3:6] # 3rd to 6th (excluded) elements: elements 3, 4, 5 - 'lo,' - >>> a[2:10:2] # Syntax: a[start:stop:step] - 'lo o' - >>> a[::3] # every three characters, from beginning to end - 'hl r!' +.. note:: **Métodos y Programación Orientada a Objectos** -Accents and special characters can also be handled in Unicode strings (see -http://docs.python.org/tutorial/introduction.html#unicode-strings). + La notación ``r.method()`` (``r.append(3)``, ``L.pop()``) es el primer ejemplo de Programación Orientada a Objectos (POO). Para una ``lista``, el objecto es `r` posee el *método* `función` que es llamado usando la notación **.**. Sin profundizar en el conocimiento de la Programación Orientada a Objetos la comprensión de la notación **.** es necesaria para recorrer este tutorial. +.. note:: **Descubriendo métodos:** -A string is an **immutable object** and it is not possible to modify its -contents. One may however create new strings from the original one. + Recuerde: en IPython: autocompletado con tabular (presione tab) + + .. sourcecode:: ipython + + In [28]: r. + r.__add__ r.__iadd__ r.__setattr__ + r.__class__ r.__imul__ r.__setitem__ + r.__contains__ r.__init__ r.__setslice__ + r.__delattr__ r.__iter__ r.__sizeof__ + r.__delitem__ r.__le__ r.__str__ + r.__delslice__ r.__len__ r.__subclasshook__ + r.__doc__ r.__lt__ r.append + r.__eq__ r.__mul__ r.count + r.__format__ r.__ne__ r.extend + r.__ge__ r.__new__ r.index + r.__getattribute__ r.__reduce__ r.insert + r.__getitem__ r.__reduce_ex__ r.pop + r.__getslice__ r.__repr__ r.remove + r.__gt__ r.__reversed__ r.reverse + r.__hash__ r.__rmul__ r.sort + +Cadenas +~~~~~~~ + +Diferentes sintaxis de cadena (simple, double o comilla triple) + +.. code-block:: python + + s = 'Hola, cómo estás' + s = "Hola, qué tal" + s = '''Hola, # triplicando las comillas permite a + cómo estás''' # la cadena ocupar más de una línea + s = """Hola, + qué tal""" .. sourcecode:: ipython - In [53]: a = "hello, world!" + In [1]: 'Hola, qué tal' + ------------------------------------------------------------ + File "", line 1 + 'Hola, qué tal' + ^ + SyntaxError: invalid syntax + +El carácter nueva línea es ``\n``, y el carácter tabulación es ``\t``. + +.. tip:: Las cadenas son colecciones como las listas. Por lo tanto pueden ser indexados y segmentados, utilizando la mismas reglas de sintaxis. + +Indexado + +.. code-block:: python + + >>> a = "hola" + >>> a[0] + 'h' + >>> a[1] + 'o' + >>> a[-1] + 'a' + +.. tip:: (Recuerde que los valores negativos corresponden a un conteo desde la derecha.) + +Segmentación (slicing) + +.. code-block:: python + + >>> a = "hola, mundo!" + >>> a[2:5] # elementos 2do al 5to (excluido): elementos 2, 3, 4 + 'la,' + >>> a[2:11:2] # sintaxis: a[inicio:final:paso] + 'l,mno' + >>> a[::3] # cada tres caracteres, del inicio al final + 'hamd' + +.. tip:: Acentos y caracteres especiales también pueden ser manejados en cadenas Unicode (véase http://docs.python.org/tutorial/introduction.html#unicode-strings). + +Una cadena es un **objeto inmutable** y no es posible modificar su contenido. Sin embargo, se puede crear nuevas cadenas a partir del original. + +.. sourcecode:: ipython + + In [53]: a = "hola, mundo!" In [54]: a[2] = 'z' --------------------------------------------------------------------------- Traceback (most recent call last): @@ -325,143 +328,136 @@ contents. One may however create new strings from the original one. TypeError: 'str' object does not support item assignment In [55]: a.replace('l', 'z', 1) - Out[55]: 'hezlo, world!' + Out[55]: 'hoza, mundo!' In [56]: a.replace('l', 'z') - Out[56]: 'hezzo, worzd!' + Out[56]: 'hzla, mundz!' + +.. tip:: Las cadenas tienen muchos métodos útiles, como ``a.replace`` como se vio anteriormente. Recuerde la notación orientada a objetos ``a.`` y el autocompletado con tabulador o ``help(str)`` para buscar nuevos métodos. + +.. seealso:: Python ofrece posibilidades avanzadas para la manipulación de cadenas, busqueda por patrones o formateado. El lector interesado puede consultar http://docs.python.org/library/stdtypes.html#string-methods y http://docs.python.org/library/string.html#new-string-formatting. + +Sustitución de cadenas + +.. code-block:: python + + >>> 'Un integer: %i; un float: %f; otra cadena: %s' % (1, 0.1, 'cadena') + 'Un integer: 1; un float: 0.100000; otra cadena: cadena' + >>> i = 102 + >>> nombre_archivo = 'procesamiento_de_conjunto_de_datos_%d.txt' % i + >>> nombre_archivo + 'procesamiento_de_conjunto_de_datos_102.txt' + +Diccionarios +~~~~~~~~~~~~ + +.. tip:: Un diccionario es básicamente una tabla eficiente que **mapea claves a valores**. Es un contenedor **sin orden** + +.. code-block:: python + + >>> tel = {'emmanuelle': 5752, 'sebastian': 5578} + >>> tel['francis'] = 5915 + >>> tel + {'sebastian': 5578, 'francis': 5915, 'emmanuelle': 5752} + >>> tel['sebastian'] + 5578 + >>> tel.keys() + ['sebastian', 'francis', 'emmanuelle'] + >>> tel.values() + [5578, 5915, 5752] + >>> 'francis' in tel + True -Strings have many useful methods, such as ``a.replace`` as seen above. -Remember the ``a.`` object-oriented notation and use tab completion or -``help(str)`` to search for new methods. +.. tip:: Se puede utilizar para almacenar y recuperar valores convenientemente asociados a un nombre (una cadena de una fecha, un nombre, etc.) ver http://docs.python.org/tutorial/datastructures.html#dictionaries para más información. +Un diccionario puede tener claves (respuesta valores) con diferentes tipos. -.. Note:: +.. code-block:: python - Python offers advanced possibilities for manipulating strings, - looking for patterns or formatting. The interested reader is referred to - http://docs.python.org/library/stdtypes.html#string-methods and - http://docs.python.org/library/string.html#new-string-formatting + >>> d = {'a':1, 'b':2, 3:'hola'} + >>> d + {'a': 1, 3: 'hola', 'b': 2} -String substitution:: +Más contenedores de tipos +~~~~~~~~~~~~~~~~~~~~~~~~~ - >>> 'An integer: %i; a float: %f; another string: %s' % (1, 0.1, 'string') - 'An integer: 1; a float: 0.100000; another string: string' +**Tuplas** - >>> i = 102 - >>> filename = 'processing_of_dataset_%d.txt' % i - >>> filename - 'processing_of_dataset_102.txt' +Las tuplas son basicamente listas immutables. Los elementos de una tupla se escriben entre paréntesis y separados por comas, o solamente separados por comas. -Dictionaries -~~~~~~~~~~~~~ - -A dictionary is basically an efficient table that **maps keys to -values**. It is an **unordered** container:: +.. code-block:: python + >>> t = 12345, 54321, 'hola!' + >>> t[0] + 12345 + >>> t + (12345, 54321, 'hola!') + >>> u = (0, 2) + >>> u + (0, 2) - >>> tel = {'emmanuelle': 5752, 'sebastian': 5578} - >>> tel['francis'] = 5915 - >>> tel - {'sebastian': 5578, 'francis': 5915, 'emmanuelle': 5752} - >>> tel['sebastian'] - 5578 - >>> tel.keys() - ['sebastian', 'francis', 'emmanuelle'] - >>> tel.values() - [5578, 5915, 5752] - >>> 'francis' in tel - True +**Conjuntos:** sin orden, items únicos. -It can be used to conveniently store and retrieve values -associated with a name (a string for a date, a name, etc.). See -http://docs.python.org/tutorial/datastructures.html#dictionaries -for more information. +.. code-block:: python -A dictionary can have keys (resp. values) with different types:: + >>> s = set(('a', 'b', 'c', 'a')) + >>> s + set(['a', 'c', 'b']) + >>> s.difference(('a', 'b')) + set(['c']) - >>> d = {'a':1, 'b':2, 3:'hello'} - >>> d - {'a': 1, 3: 'hello', 'b': 2} +Operador de asignación +---------------------- -More container types -~~~~~~~~~~~~~~~~~~~~ +.. tip:: La `referencia de bibliotecas Python `_ dice: -**Tuples** +.. -Tuples are basically immutable lists. The elements of a tuple are written -between parentheses, or just separated by commas:: + Las sentencias de asignación se utilizan para (re)vincular nombres a valores y modificar los atributos o elementos de los objetos mutables. - >>> t = 12345, 54321, 'hello!' - >>> t[0] - 12345 - >>> t - (12345, 54321, 'hello!') - >>> u = (0, 2) +En pocas palabras, funciona de la siguiente manera (asignación simple): -**Sets:** unordered, unique items:: +#. una expresión en el lado derecho es evaluada, el correspondiente objeto se crea/obtiene - >>> s = set(('a', 'b', 'c', 'a')) - >>> s - set(['a', 'c', 'b']) - >>> s.difference(('a', 'b')) - set(['c']) +#. un **nombre** en el lado izquierdo es asignado, o vinculado al objeto r.h.s. -Assignment operator -------------------- +Cosas a tener en cuenta: -`Python library reference -`_ -says: +* un objeto puede estar vinculado a varios nombres: - Assignment statements are used to (re)bind names to values and to - modify attributes or items of mutable objects. + .. sourcecode:: ipython -In short, it works as follows (simple assignment): + In [1]: a = [1, 2, 3] + In [2]: b = a + In [3]: a + Out[3]: [1, 2, 3] + In [4]: b + Out[4]: [1, 2, 3] + In [5]: a is b + Out[5]: True + In [6]: b[1] = 'hi!' + In [7]: a + Out[7]: [1, 'hi!', 3] -#. an expression on the right hand side is evaluated, the corresponding - object is created/obtained -#. a **name** on the left hand side is assigned, or bound, to the - r.h.s. object +* para cambiar una lista *sin crear una copia*, use indexado/segmentado: -Things to note: + .. sourcecode:: ipython -* a single object can have several names bound to it: + In [1]: a = [1, 2, 3] + In [3]: a + Out[3]: [1, 2, 3] + In [4]: a = ['a', 'b', 'c'] # Creando otro objeto. + In [5]: a + Out[5]: ['a', 'b', 'c'] + In [6]: id(a) + Out[6]: 138641676 + In [7]: a[:] = [1, 2, 3] # Modificando objetos sobre la marcha. + In [8]: a + Out[8]: [1, 2, 3] + In [9]: id(a) + Out[9]: 138641676 # Lo mismo esta en Out[6], el tuyo puede ser diferente... - .. sourcecode:: ipython +* el concepto clave aqui es **mutable vs. immutable** - In [1]: a = [1, 2, 3] - In [2]: b = a - In [3]: a - Out[3]: [1, 2, 3] - In [4]: b - Out[4]: [1, 2, 3] - In [5]: a is b - Out[5]: True - In [6]: b[1] = 'hi!' - In [7]: a - Out[7]: [1, 'hi!', 3] + * mutable, objecto que puede cambiar sobre sobre la marcha + * immutable, objecto que no puede modificarse despues de su creación -* to change a list *in place*, use indexing/slices: - - .. sourcecode:: ipython - - In [1]: a = [1, 2, 3] - In [3]: a - Out[3]: [1, 2, 3] - In [4]: a = ['a', 'b', 'c'] # Creates another object. - In [5]: a - Out[5]: ['a', 'b', 'c'] - In [6]: id(a) - Out[6]: 138641676 - In [7]: a[:] = [1, 2, 3] # Modifies object in place. - In [8]: a - Out[8]: [1, 2, 3] - In [9]: id(a) - Out[9]: 138641676 # Same as in Out[6], yours will differ... - -* the key concept here is **mutable vs. immutable** - - * mutable objects can be changed in place - * immutable objects cannot be modified once created - -A very good and detailed explanation of the above issues can be found -in David M. Beazley's article `Types and Objects in Python -`_. +.. seealso:: Una explicación muy buena y detallada de los aspectos mencionados anteriormente se encuentra en el artículo `Types and Objects in Python `_ de David M. Beazley's. diff --git a/intro/language/control_flow.rst b/intro/language/control_flow.rst index bbe80b1..7a4bc39 100644 --- a/intro/language/control_flow.rst +++ b/intro/language/control_flow.rst @@ -1,128 +1,139 @@ -Control Flow -============ +Control de flujo +================ -Controls the order in which the code is executed. +Controla el orden en el que se ejecuta el código. if/elif/else ------------ -.. sourcecode:: ipython +.. code-block:: python + + >>> if 2**2 == 4: + ... print 'Obvio!' + ... + Obvio! - >>> if 2**2 == 4: - ... print 'Obvious!' - ... - Obvious! +.. code-block:: python + >>> a = -1 + >>> if a > 0: + ... print 'Número positivo' + ... else: + ... print 'Número negativo' + ... + Número negativo -**Blocks are delimited by indentation** +**Los bloques de código son delimitados por indentación** -Type the following lines in your Python interpreter, and be careful to -**respect the indentation depth**. The Ipython shell automatically -increases the indentation depth after a column ``:`` sign; to -decrease the indentation depth, go four spaces to the left with the -Backspace key. Press the Enter key twice to leave the logical block. +.. tip:: Escriba las siguientes líneas en el intérprete de Python, y tenga cuidado **respecto a la profundidad de indentación**. La consola IPython aumenta automáticamente la profundidad de indentado una columna después del signo ``:``, para disminuir la profundidad de indentado, presione la tecla de retroceso o la flecha izquierda. Pulse la tecla Intro dos veces para salir del bloque lógico. .. sourcecode:: ipython - In [1]: a = 10 + In [1]: a = 10 - In [2]: if a == 1: - ...: print(1) - ...: elif a == 2: - ...: print(2) - ...: else: - ...: print('A lot') - ...: - A lot + In [2]: if a == 1: + ...: print 1 + ...: elif a == 2: + ...: print 2 + ...: else: + ...: print('Diferente de 1 y 2') + ...: + Diferente de 1 y 2 -Indentation is compulsory in scripts as well. As an exercise, re-type the -previous lines with the same indentation in a script ``condition.py``, and -execute the script with ``run condition.py`` in Ipython. +La indentación es obligatoria en scripts. Como ejercicio, reescriba la líneas anteriores en el script ``indentado.py`` y ejecutelo en IPython usando ``run``. for/range ---------- -Iterating with an index:: +Iterando con indices + +.. code-block:: python - >>> for i in range(4): - ... print(i) - 0 - 1 - 2 - 3 + >>> for i in range(4): + ... print(i) + 0 + 1 + 2 + 3 -But most often, it is more readable to iterate over values:: +A menudo, el código es más legible si se itera sobre valores: - >>> for word in ('cool', 'powerful', 'readable'): - ... print('Python is %s' % word) - Python is cool - Python is powerful - Python is readable +.. code-block:: python + >>> for palabra in ('interesante', 'poderoso', 'legible'): + ... print('Python es %s' % palabra) + Python es interesante + Python es poderoso + Python es legible while/break/continue --------------------- -Typical C-style while loop (Mandelbrot problem):: +Bucle while al estilo C (problema de Mandelbrot) - >>> z = 1 + 1j - >>> while abs(z) < 100: - ... z = z**2 + 1 - >>> z - (-134+352j) +.. code-block:: python -**More advanced features** + >>> z = 1 + 1j + >>> while abs(z) < 100: + ... z = z**2 + 1 + >>> z + (-134+352j) -``break`` out of enclosing for/while loop:: +**Características más avanzadas** - >>> z = 1 + 1j +``break`` sale del bucle encerrado por for/while - >>> while abs(z) < 100: - ... if z.imag == 0: - ... break - ... z = z**2 + 1 +.. code-block:: python + >>> z = 1 + 1j + >>> while abs(z) < 100: + ... if z.imag == 0: + ... break + ... z = z**2 + 1 -``continue`` the next iteration of a loop.:: +``continue`` la siguiente iteración de un bucle. - >>> a = [1, 0, 2, 4] - >>> for element in a: - ... if element == 0: - ... continue - ... print 1. / element - 1.0 - 0.5 - 0.25 +.. code-block:: python + >>> a = [1, 0, 2, 4] + >>> for element in a: + ... if element == 0: + ... continue + ... print 1. / element + 1.0 + 0.5 + 0.25 - -Conditional Expressions ------------------------ +Expresiones condicionales +------------------------- :``if ``: - Evaluates to False: - * any number equal to zero (0, 0.0, 0+0j) - * an empty container (list, tuple, set, dictionary, ...) - * ``False``, ``None`` + Se evalúa como False: + * Cualquier número igual a cero (0, 0.0, 0+0j) + * Un contenedor vacío (lista, tupla, conjunto, diccionario, ...) + * ``False``, ``None`` - Evaluates to True: - * everything else + Se evalúa como True: + * Todo lo demás :``a == b``: - Tests equality, with logics:: + Prueba de igualdad, con operadores lógicos + + .. code-block:: python >>> 1 == 1. True :``a is b``: - Tests identity: both sides are the same object:: + Prueba de identidad: ambos lados son el mismo objeto + + .. code-block:: python >>> 1 is 1. False - >>> a = 1 >>> b = 1 >>> a is b @@ -130,7 +141,9 @@ Conditional Expressions :``a in b``: - For any collection ``b``: ``b`` contains ``a`` :: + Para todas las colecciones ``b``: ``b`` contiene ``a`` + + .. code-block:: python >>> b = [1, 2, 3] >>> 2 in b @@ -138,101 +151,97 @@ Conditional Expressions >>> 5 in b False + Si ``b`` es un diccionario, se prueba si ``a`` es un clave en ``b``. - If ``b`` is a dictionary, this tests that ``a`` is a key of ``b``. - -Advanced iteration -------------------------- - -Iterate over any *sequence* -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Iteración avanzada +------------------ -You can iterate over any sequence (string, list, keys in a dictionary, lines in -a file, ...):: +Iterando sobre una *secuencia* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - >>> vowels = 'aeiouy' +Se puede iterar sobre una secuencia (cadenas, listas, claves en un diccionario, lineas en un archivo, ...) - >>> for i in 'powerful': - ... if i in vowels: - ... print(i), - o e u +.. code-block:: python -:: + >>> vocales = 'aeiou' + >>> for i in 'poderoso': + ... if i in vocales: + ... print i, + o e o o - >>> message = "Hello how are you?" - >>> message.split() # returns a list - ['Hello', 'how', 'are', 'you?'] - >>> for word in message.split(): - ... print word - ... - Hello - how - are - you? +.. code-block:: python -Few languages (in particular, languages for scientific computing) allow to -loop over anything but integers/indices. With Python it is possible to -loop exactly over the objects of interest without bothering with indices -you often don't care about. + >>> mensaje = "Hola como estas?" + >>> mensaje.split() # devuelve una lista + ['Hola', 'como', 'estas?'] + >>> for palabra in mensaje.split(): + ... print palabra + ... + Hola + como + estas? +.. tip:: Pocos lenguajes (en particular, los lenguajes de computación científica) permiten bucles sobre cualquier cosa menos sobre enteros/índices. Con Python es posible hacer un bucle sobre los objetos de interés sin preocuparse por los índices que a menudo no importan. Esta característica hace al código más legible. -.. warning:: Not safe to modify the sequence you are iterating over. +.. warning:: No es seguro modificar la secuencia que se está iterando. -Keeping track of enumeration number -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Seguimiento de una enumeración +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Common task is to iterate over a sequence while keeping track of the -item number. +Una tarea común es iterar sobre una secuencia mientras se enumera los elementos. -* Could use while loop with a counter as above. Or a for loop:: +* Puede utilizarse un bucle while con un contador como el ejemplo anterior. O un bucle for - >>> words = ('cool', 'powerful', 'readable') - >>> for i in range(0, len(words)): - ... print i, words[i] - 0 cool - 1 powerful - 2 readable +.. code-block:: python -* But, Python provides ``enumerate`` keyword for this:: + >>> palabras = ('interesante', 'poderoso', 'legible') + >>> for indice in range(0, len(palabras)): + ... print indice, palabras[indice] + 0 interesante + 1 poderoso + 2 legible - >>> for index, item in enumerate(words): - ... print index, item - 0 cool - 1 powerful - 2 readable +* Pero, Python provee la palabra clave ``enumerate`` +.. code-block:: python + >>> for indice, elemento in enumerate(palabras): + ... print indice, elemento + 0 estupendo + 1 poderoso + 2 legible -Looping over a dictionary +Bucle sobre un diccionario ~~~~~~~~~~~~~~~~~~~~~~~~~~ -Use **iteritems**:: +Use **iteritems** - >>> d = {'a': 1, 'b':1.2, 'c':1j} +.. code-block:: python - >>> for key, val in d.iteritems(): - ... print('Key: %s has value: %s' % (key, val)) - Key: a has value: 1 - Key: c has value: 1j - Key: b has value: 1.2 + >>> d = {'a': 1, 'b':1.2, 'c':1j} + >>> for clave, valor in d.iteritems(): + ... print('Clave: %s con valor: %s' % (clave, valor)) + Clave: a con valor: 1 + Clave: c con valor: 1j + Clave: b con valor: 1.2 -List Comprehensions -------------------- +Listas por comprensión +---------------------- -:: +.. code-block:: python - >>> [i**2 for i in range(4)] - [0, 1, 4, 9] + >>> [elemento**2 for elemento in range(4)] + [0, 1, 4, 9] _____ -.. topic:: Exercise - :class: green +.. topic:: Ejercicio + :class: green - Compute the decimals of Pi using the Wallis formula: + Calcular los decimales de Pi usando la formula de Wallis: - .. math:: - \pi = 2 \prod_{i=1}^{\infty} \frac{4i^2}{4i^2 - 1} + .. math:: + \pi = 2 \prod_{i=1}^{\infty} \frac{4i^2}{4i^2 - 1} .. :ref:`pi_wallis` diff --git a/intro/language/exceptions.rst b/intro/language/exceptions.rst index 3c65c4f..9af2e52 100644 --- a/intro/language/exceptions.rst +++ b/intro/language/exceptions.rst @@ -1,168 +1,153 @@ -Exception handling in Python -============================ +Manejo de excepciones en Python +=============================== -It is highly unlikely that you haven't yet raised Exceptions if you have -typed all the previous commands of the tutorial. For example, you may -have raised an exception if you entered a command with a typo. +Es muy poco probable que se hayan producido excepciones si tiene escrito todos los comandos anteriores del tutorial. Por ejemplo, es posible que se haya producido una excepción si introdujo un comando con un error tipográfico. -Exceptions are raised by different kinds of errors arising when executing -Python code. In your own code, you may also catch errors, or define custom -error types. You may want to look at the descriptions of the `the built-in -Exceptions `_ when looking -for the right exception type. +Las excepciones se producen por diferentes tipos de errores que surgen al ejecutar código Python. En su propio código, también puede detectar errores o definir tipos personalizados de errores. Es posible que desee ver las descripciones en `the built-in Exceptions `_. -Exceptions +Excepciones ----------- -Exceptions are raised by errors in Python: +Excepciones producidas por errores en Python: .. sourcecode:: ipython - In [1]: 1/0 - --------------------------------------------------------------------------- - ZeroDivisionError: integer division or modulo by zero + In [1]: 1/0 + --------------------------------------------------------------------------- + ZeroDivisionError: integer division or modulo by zero - In [2]: 1 + 'e' - --------------------------------------------------------------------------- - TypeError: unsupported operand type(s) for +: 'int' and 'str' + In [2]: 1 + 'e' + --------------------------------------------------------------------------- + TypeError: unsupported operand type(s) for +: 'int' and 'str' - In [3]: d = {1:1, 2:2} + In [3]: d = {1:1, 2:2} - In [4]: d[3] - --------------------------------------------------------------------------- - KeyError: 3 + In [4]: d[3] + --------------------------------------------------------------------------- + KeyError: 3 - In [5]: l = [1, 2, 3] + In [5]: l = [1, 2, 3] - In [6]: l[4] - --------------------------------------------------------------------------- - IndexError: list index out of range + In [6]: l[4] + --------------------------------------------------------------------------- + IndexError: list index out of range - In [7]: l.foobar - --------------------------------------------------------------------------- - AttributeError: 'list' object has no attribute 'foobar' + In [7]: l.foobar + --------------------------------------------------------------------------- + AttributeError: 'list' object has no attribute 'foobar' -As you can see, there are **different types** of exceptions for different errors. +Como puede ver, hay **diferentes tipos** de excepciones para diferentes errores. -Catching exceptions --------------------- +Atrapando excepciones +--------------------- try/except ~~~~~~~~~~~ .. sourcecode:: ipython - In [8]: while True: - ....: try: - ....: x = int(raw_input('Please enter a number: ')) - ....: break - ....: except ValueError: - ....: print('That was no valid number. Try again...') - ....: - ....: - Please enter a number: a - That was no valid number. Try again... - Please enter a number: 1 - - In [9]: x - Out[9]: 1 + In [8]: while True: + ...: try: + ...: x = int(raw_input('Digite un numero: ')) + ...: break + ...: except ValueError: + ...: print('No es un numero valido. Pruebe de nuevo...') + ...: + Digite un numero: a + No es un numero valido. Pruebe de nuevo... + Digite un numero: 1 + + In [9]: x + Out[9]: 1 try/finally ~~~~~~~~~~~~ .. sourcecode:: ipython - In [10]: try: - ....: x = int(raw_input('Please enter a number: ')) - ....: finally: - ....: print('Thank you for your input') - ....: - ....: - Please enter a number: a - Thank you for your input - --------------------------------------------------------------------------- - ValueError: invalid literal for int() with base 10: 'a' + In [10]: try: + ....: x = int(raw_input('Digite un numero: ')) + ....: finally: + ....: print('Gracias') + ....: + Digite un numero: a + Gracias -Important for resource management (e.g. closing a file) + --------------------------------------------------------------------------- + ValueError: invalid literal for int() with base 10: 'a' -Easier to ask for forgiveness than for permission -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Importante para gestión de recursos (por ejemplo, cerrar un archivo) +Es más fácil pedir perdón que permiso +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. sourcecode:: ipython - In [11]: def print_sorted(collection): - ....: try: - ....: collection.sort() - ....: except AttributeError: - ....: pass - ....: print(collection) - ....: - ....: - - In [12]: print_sorted([1, 3, 2]) - [1, 2, 3] + In [11]: def imprime_ordenado(coleccion): + ....: try: + ....: coleccion.sort() + ....: except AttributeError: + ....: pass + ....: print coleccion + ....: - In [13]: print_sorted(set((1, 3, 2))) - set([1, 2, 3]) + In [12]: imprime_ordenado([1, 3, 2]) + [1, 2, 3] - In [14]: print_sorted('132') - 132 + In [13]: imprime_ordenado(set((1, 3, 2))) + set([1, 2, 3]) + In [14]: imprime_ordenado('132') + 132 -Raising exceptions ------------------- +Agregando excepciones +--------------------- -* Capturing and reraising an exception: +* Capturando y agregando una excepción: .. sourcecode:: ipython - In [15]: def filter_name(name): - ....: try: - ....: name = name.encode('ascii') - ....: except UnicodeError, e: - ....: if name == 'Gaël': - ....: print('OK, Gaël') - ....: else: - ....: raise e - ....: return name - ....: - - In [16]: filter_name('Gaël') - OK, Gaël - Out[16]: 'Ga\xc3\xabl' + In [15]: def filtro_nombre(nombre): + ....: try: + ....: nombre = nombre.encode('ascii') + ....: except UnicodeError, e: + ....: if nombre == 'Gaël': + ....: print('OK, Gaël') + ....: else: + ....: raise e + ....: return nombre + ....: - In [17]: filter_name('Stéfan') - --------------------------------------------------------------------------- - UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128) + In [16]: filtro_nombre('Gaël') + OK, Gaël + Out[16]: 'Ga\xc3\xabl' + In [17]: filtro_nombre('Stéfan') + --------------------------------------------------------------------------- + UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128) -* Exceptions to pass messages between parts of the code: +* Excepciones para pasar mensajes entre las partes del código: .. sourcecode:: ipython - In [17]: def achilles_arrow(x): - ....: if abs(x - 1) < 1e-3: - ....: raise StopIteration - ....: x = 1 - (1-x)/2. - ....: return x - ....: - - In [18]: x = 0 - - In [19]: while True: - ....: try: - ....: x = achilles_arrow(x) - ....: except StopIteration: - ....: break - ....: - ....: - - In [20]: x - Out[20]: 0.9990234375 + In [18]: def tendon_de_aquiles(x): + ....: if abs(x - 1) < 1e-3: + ....: raise StopIteration + ....: x = 1 - (1 - x)/2.0 + ....: return x + ....: + In [19]: x = 0 -Use exceptions to notify certain conditions are met (e.g. -StopIteration) or not (e.g. custom error raising) + In [20]: while True: + ....: try: + ....: x = tendon_de_aquiles(x) + ....: except StopIteration: + ....: break + ....: + ....: + In [21]: x + Out[21]: 0.9990234375 +Utilice excepciones para notificar determinadas condiciones que se cumplen (por ejemplo, StopIteration) o no se cumplen (por ejemplo, agregar errores personalizado) diff --git a/intro/language/first_steps.rst b/intro/language/first_steps.rst index 278d218..4b59b1a 100644 --- a/intro/language/first_steps.rst +++ b/intro/language/first_steps.rst @@ -1,31 +1,28 @@ -First steps -------------- +Primeros pasos +-------------- +Inicie la consola **IPython** (consola mejorada interactiva Python): -Start the **Ipython** shell (an enhanced interactive Python shell): - -* by typing "ipython" from a Linux/Mac terminal, or from the Windows cmd shell, -* **or** by starting the program from a menu, e.g. in the `Python(x,y)`_ or - `EPD`_ menu if you have installed one of these scientific-Python suites. +* Escriba "ipython" en una terminal Linux/Mac, o desde la consola cmd de Windows. +* O iniciando el programa desde un menú, por ejemplo, en `Python(x,y)`_ o `EPD`_ si ha instalado una distribución científica Python. .. _`Python(x,y)`: http://www.pythonxy.com/ .. _`EPD`: http://www.enthought.com/products/epd.php -If you don't have Ipython installed on your computer, other Python shells -are available, such as the plain Python shell started by typing "python" -in a terminal, or the Idle interpreter. However, we advise to use the -Ipython shell because of its enhanced features, especially for -interactive scientific computing. +.. tip:: + +Si usted no tiene IPython instalado en su equipo, otras consolas Python están disponibles, como la consola estandar python que se inicia escribiendo "python" en una terminal, o el intérprete Idle. Sin embargo, nos recomiendan usar la consola IPython debido a sus características mejoradas, especialmente para computación científica interactiva. -Once you have started the interpreter, type :: +Después de iniciar el interprete, teclee:: - >>> print "Hello, world!" - Hello, world! + >>> print "Hola, mundo!" + Hola, mundo! -The message "Hello, world!" is then displayed. You just executed your -first Python instruction, congratulations! +.. tip:: -To get yourself started, type the following stack of instructions :: +Si el mensaje "Hola, mundo!" fue mostrado. Usted acaba de ejecutar su primera instrucción Python, felicitaciones! + +Para empezar, escriba las siguientes instrucciones:: >>> a = 3 >>> b = 2*a @@ -35,27 +32,20 @@ To get yourself started, type the following stack of instructions :: 6 >>> a*b 18 - >>> b = 'hello' + >>> b = 'hola' >>> type(b) >>> b + b - 'hellohello' + 'holahola' >>> 2*b - 'hellohello' + 'holahola' + +.. tip:: -Two variables ``a`` and ``b`` have been defined above. Note that one does -not declare the type of an variable before assigning its value. In C, -conversely, one should write: +Tenga en cuenta que las variables ``a`` y ``b`` no se declararon su tipo antes de asignarles un valor. Por el contrario en C, se debe escribir: -.. sourcecode:: c + .. sourcecode:: c - int a = 3; + int a = 3; -In addition, the type of a variable may change, in the sense that at -one point in time it can be equal to a value of a certain type, and a -second point in time, it can be equal to a value of a different -type. `b` was first equal to an integer, but it became equal to a -string when it was assigned the value `'hello'`. Operations on -integers (``b=2*a``) are coded natively in Python, and so are some -operations on strings such as additions and multiplications, which -amount respectively to concatenation and repetition. +Además, el tipo de una variable puede cambiar, en el sentido de que por un periodo de tiempo puede ser igual a un valor de un cierto tipo, y en otro periodo tiempo puede ser igual a otro valor de tipo diferente. Primero `b` fue igual a un número entero, pero se convirtio en cadena cuando se le asignó el valor ``hola``. Las operaciones con enteros (``b = 2*a``) están codificados de forma nativa en Python, y también lo son algunas operaciones sobre cadenas, tales como adiciones y multiplicaciones, que son respectivamente, concatenación y repetición. diff --git a/intro/language/functions.rst b/intro/language/functions.rst index 94a5c1e..5d5343c 100644 --- a/intro/language/functions.rst +++ b/intro/language/functions.rst @@ -1,362 +1,329 @@ -Defining functions -===================== +Definiendo funciones +==================== -Function definition -------------------- +Definiendo una función +---------------------- .. sourcecode:: ipython - In [56]: def test(): - ....: print('in test function') - ....: - ....: + In [56]: def test(): + ....: print('funcion de prueba') + ....: + ....: - In [57]: test() - in test function + In [57]: test() + funcion de prueba -.. Warning:: +.. warning:: Después de definir una función deben indentarse los bloques que la componen. - Function blocks must be indented as other control-flow blocks. - -Return statement +Sentencia return ---------------- -Functions can *optionally* return values. +Las funciones pueden *opcionalmente* devolver valores. .. sourcecode:: ipython - In [6]: def disk_area(radius): - ...: return 3.14 * radius * radius - ...: - - In [8]: disk_area(1.5) - Out[8]: 7.0649999999999995 + In [6]: def area_circulo(radio): + ...: return 3.14 * radio * radio + ...: -.. Note:: By default, functions return ``None``. + In [8]: area_circulo(1.5) + Out[8]: 7.0649999999999995 -.. Note:: Note the syntax to define a function: +.. note:: Por defecto, las funciones devuelven ``None``. - * the ``def`` keyword; +.. note:: Tenga en cuenta la sintaxis para definir una función: - * is followed by the function's **name**, then + * la palabra clave ``def``; - * the arguments of the function are given between parentheses followed - by a colon. + * seguido por el **nombre** la función, a continuación - * the function body; + * los argumentos de la función van entre paréntesis seguido por dos puntos. - * and ``return object`` for optionally returning values. + * el cuerpo de la función; + * y ``return object`` si la función devuelve valores. -Parameters +Parámetros ---------- -Mandatory parameters (positional arguments) +Parámetros obligatorios (argumentos con posición) .. sourcecode:: ipython - In [81]: def double_it(x): - ....: return x * 2 - ....: + In [81]: def por_dos(x): + ....: return x * 2 + ....: - In [82]: double_it(3) - Out[82]: 6 + In [82]: por_dos(3) + Out[82]: 6 - In [83]: double_it() - --------------------------------------------------------------------------- - Traceback (most recent call last): - File "", line 1, in - TypeError: double_it() takes exactly 1 argument (0 given) + In [83]: por_dos() + --------------------------------------------------------------------------- + Traceback (most recent call last): + File "", line 1, in + TypeError: double_it() takes exactly 1 argument (0 given) -Optional parameters (keyword or named arguments) +Parámetros opcionales (argumentos con nombre o palabra clave) .. sourcecode:: ipython - In [84]: def double_it(x=2): - ....: return x * 2 - ....: + In [84]: def por_dos(x=2): + ....: return x * 2 + ....: - In [85]: double_it() - Out[85]: 4 + In [85]: por_dos() + Out[85]: 4 - In [86]: double_it(3) - Out[86]: 6 + In [86]: por_dos(3) + Out[86]: 6 -Keyword arguments allow you to specify *default values*. +Los argumentos con nombre le permiten especificar los *valores por defecto*. -.. warning:: - - Default values are evaluated when the function is defined, not when - it is called. This can be problematic when using mutable types (e.g. - dictionary or list) and modifying them in the function body, since the - modifications will be persistent across invocations of the function. +.. warning:: Los valores por defecto se evalúan cuando se define la función, no cuando se le llama. Esto puede ser problemático cuando se utiliza tipos mutables (por ejemplo, un diccionario o una lista) y su modificación en el cuerpo de la función, ya que el modificaciones no persisten al invocar una función. .. sourcecode:: ipython - In [124]: bigx = 10 + In [124]: gran_x = 10 + + In [125]: def por_dos(x=gran_x): + .....: return x * 2 + .....: - In [125]: def double_it(x=bigx): - .....: return x * 2 - .....: + In [126]: por_dos() + Out[126]: 20 - In [126]: bigx = 1e9 # Now really big + In [127]: gran_x = 1e9 # Ahora si es grande - In [128]: double_it() - Out[128]: 20 + In [128]: por_dos() + Out[128]: 20 -More involved example implementing python's slicing: +.. tip:: Un ejemplo que se parece a la segmentación de Python: .. sourcecode:: ipython - In [98]: def slicer(seq, start=None, stop=None, step=None): - ....: """Implement basic python slicing.""" - ....: return seq[start:stop:step] - ....: + In [98]: def segmento(secuencia, inicio=None, final=None, paso=None): + ....: """Implementacion basica de segmentacion python.""" + ....: return secuencia[inicio:final:paso] + ....: - In [101]: rhyme = 'one fish, two fish, red fish, blue fish'.split() + In [101]: rima = 'pez uno, pez dos, pez rojo, pez azul'.split() - In [102]: rhyme - Out[102]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish'] + In [102]: rima + Out[102]: ['pez', 'uno,', 'pez', 'dos,', 'pez', 'rojo,', 'pez', 'azul'] - In [103]: slicer(rhyme) - Out[103]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish'] + In [103]: segmento(rima) + Out[103]: ['pez', 'uno,', 'pez', 'dos,', 'pez', 'rojo,', 'pez', 'azul'] - In [104]: slicer(rhyme, step=2) - Out[104]: ['one', 'two', 'red', 'blue'] + In [104]: segmento(rima, paso=2) + Out[104]: ['pez', 'pez', 'pez', 'pez'] - In [105]: slicer(rhyme, 1, step=2) - Out[105]: ['fish,', 'fish,', 'fish,', 'fish'] + In [105]: segmento(rima, 1, paso=2) + Out[105]: ['uno,', 'dos,', 'rojo,', 'azul'] - In [106]: slicer(rhyme, start=1, stop=4, step=2) - Out[106]: ['fish,', 'fish,'] + In [106]: segmento(rima, inicio=1, final=4, paso=2) + Out[106]: ['uno,', 'dos,'] -The order of the keyword arguments does not matter: +El orden de los argumentos con nombre no importa: .. sourcecode:: ipython - In [107]: slicer(rhyme, step=2, start=1, stop=4) - Out[107]: ['fish,', 'fish,'] + In [107]: segmento(rima, paso=2, inicio=1, final=4) + Out[107]: ['uno,', 'dos,'] -but it is good practice to use the same ordering as the function's -definition. +pero es una buena práctica usar el mismo orden que en la definición. -*Keyword arguments* are a very convenient feature for defining functions -with a variable number of arguments, especially when default values are -to be used in most calls to the function. +Los *argumentos con nombre* son una característica muy conveniente para la definición de funciones con un número variable de argumentos, sobre todo cuando los valores por defecto se usan en la mayoría de las llamadas a la función. -Passing by value ----------------- +Paso por valor +-------------- -Can you modify the value of a variable inside a function? Most languages -(C, Java, ...) distinguish "passing by value" and "passing by reference". -In Python, such a distinction is somewhat artificial, and it is a bit -subtle whether your variables are going to be modified or not. -Fortunately, there exist clear rules. - -Parameters to functions are references to objects, which are passed by -value. When you pass a variable to a function, python passes the -reference to the object to which the variable refers (the **value**). -Not the variable itself. - -If the **value** is immutable, the function does not modify the caller's -variable. If the **value** is mutable, the function may modify the -caller's variable in-place:: - - >>> def try_to_modify(x, y, z): - ... x = 23 - ... y.append(42) - ... z = [99] # new reference - ... print(x) - ... print(y) - ... print(z) - ... - >>> a = 77 # immutable variable - >>> b = [99] # mutable variable - >>> c = [28] - >>> try_to_modify(a, b, c) - 23 - [99, 42] - [99] - >>> print(a) - 77 - >>> print(b) - [99, 42] - >>> print(c) - [28] - - - -Functions have a local variable table called a *local namespace*. - -The variable ``x`` only exists within the function *try_to_modify*. - - -Global variables ----------------- +.. tip:: Se puede modificar el valor de una variable dentro una función? La mayoría de los lenguajes (C, Java, ...) distinguen ``el paso por valor`` y ``el paso por referencia``. En Python, tal distinción es un tanto artificial, y es un poco sutil si las variables serán modificadas o no. Afortunadamente, existen reglas claras. -Variables declared outside the function can be referenced within the -function: +Los parámetros a funciones son referencias a los objetos, que se pasan por valor. Cuando se pasa una variable a una función, Python pasa la referencia al objeto al que hace referencia la variable (el **valor**). No es la propia variable. -.. sourcecode:: ipython +Si el **valor** pasado a una función es inmutable, la función no modifica la variable llamada. Si el **valor** es mutable, la función puede modificar la variable + +.. code-block:: python - In [114]: x = 5 + >>> def intenta_modificar(x, y, z): + ... x = 23 + ... y.append(42) + ... z = [99] # nueva referencia + ... print x + ... print y + ... print z + ... + >>> a = 77 # variable immutable + >>> b = [99] # variable mutable + >>> c = [28] + >>> intenta_modificar(a, b, c) + 23 + [99, 42] + [99] + >>> print a + 77 + >>> print b + [99, 42] + >>> print c + [28] - In [115]: def addx(y): - .....: return x + y - .....: +Las funciones tienen una tabla de variables locales llamada *local namespace*. - In [116]: addx(10) - Out[116]: 15 +La variable ``x`` sólo existe dentro la función *intenta_modificar*. -But these "global" variables cannot be modified within the function, -unless declared **global** in the function. +Variables globales +------------------ -This doesn't work: +Las variables declaradas fuera de una función pueden referenciarse a una función: .. sourcecode:: ipython - In [117]: def setx(y): - .....: x = y - .....: print('x is %d' % x) - .....: - .....: + In [114]: x = 5 - In [118]: setx(10) - x is 10 + In [115]: def suma_x(y): + .....: return x + y + .....: - In [120]: x - Out[120]: 5 + In [116]: suma_x(10) + Out[116]: 15 -This works: +Pero estas variables ``globales`` no se pueden modificar dentro de la función, a menos que se declare como **global** en la función. + +Esto no funciona: .. sourcecode:: ipython - In [121]: def setx(y): - .....: global x - .....: x = y - .....: print('x is %d' % x) - .....: - .....: + In [117]: def asigna_x(y): + .....: x = y + .....: print 'x is %d' % x + .....: + .....: + + In [118]: asigna_x(10) + x is 10 - In [122]: setx(10) - x is 10 + In [120]: x + Out[120]: 5 - In [123]: x - Out[123]: 10 +Esto si funciona: + +.. sourcecode:: ipython + In [121]: def asigna_x(y): + .....: global x + .....: x = y + .....: print 'x is %d' % x + .....: + .....: -Variable number of parameters + In [122]: asigna_x(10) + x is 10 + + In [123]: x + Out[123]: 10 + +Número variable de parámetros ----------------------------- -Special forms of parameters: - * ``*args``: any number of positional arguments packed into a tuple - * ``**kwargs``: any number of keyword arguments packed into a dictionary +Formas especiales de los parámetros: -.. sourcecode:: ipython +* ``*args``: cualquier número de argumentos posicionales en una tupla - In [35]: def variable_args(*args, **kwargs): - ....: print 'args is', args - ....: print 'kwargs is', kwargs - ....: +* ``**kwargs``: cualquier número de argumentos con nombre en un diccionario - In [36]: variable_args('one', 'two', x=1, y=2, z=3) - args is ('one', 'two') - kwargs is {'y': 2, 'x': 1, 'z': 3} +.. sourcecode:: ipython + + In [35]: def argumentos_variables(*args, **kwargs): + ....: print 'args es', args + ....: print 'kwargs es', kwargs + ....: + In [36]: argumentos_variables('uno', 'dos', x=1, y=2, z=3) + args es ('uno', 'dos') + kwargs es {'y': 2, 'x': 1, 'z': 3} Docstrings ---------- -Documentation about what the function does and its parameters. General -convention: +Documentación sobre lo que hace la función y sus parámetros. Convención general: .. sourcecode:: ipython - In [67]: def funcname(params): - ....: """Concise one-line sentence describing the function. - ....: - ....: Extended summary which can contain multiple paragraphs. - ....: """ - ....: # function body - ....: pass - ....: - - In [68]: funcname? - Type: function - Base Class: type 'function'> - String Form: - Namespace: Interactive - File: - Definition: funcname(params) - Docstring: - Concise one-line sentence describing the function. - - Extended summary which can contain multiple paragraphs. - -.. Note:: **Docstring guidelines** - - - For the sake of standardization, the `Docstring - Conventions `_ webpage - documents the semantics and conventions associated with Python - docstrings. - - Also, the Numpy and Scipy modules have defined a precise standard - for documenting scientific functions, that you may want to follow for - your own functions, with a ``Parameters`` section, an ``Examples`` - section, etc. See - http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard - and http://projects.scipy.org/numpy/browser/trunk/doc/example.py#L37 - -Functions are objects ---------------------- -Functions are first-class objects, which means they can be: - * assigned to a variable - * an item in a list (or any collection) - * passed as an argument to another function. + In [67]: def funcion_ejemplo(parametros): + ....: """Frase concisa de una línea que describe la funcion. + ....: + ....: Resumen extendido que puede contener varios parrafos. + ....: """ + ....: # cuerpo de funcion + ....: pass + ....: -.. sourcecode:: ipython + In [68]: funcion_ejemplo? + Type: function + String Form: + File: /home/claudio/ + Definition: funcion_ejemplo(parametros) + Docstring: + Frase concisa de una línea que describe la funcion. - In [38]: va = variable_args + Resumen extendido que puede contener varios parrafos. - In [39]: va('three', x=1, y=2) - args is ('three',) - kwargs is {'y': 2, 'x': 1} +.. note:: **Guia para docstrings** + Para estandarizar la documentación, revise la página web `Docstring Conventions `_ contiene documentos de semántica y convenios relacionados con Python docstrings. -Methods -------- + Además, los módulos numpy y scipy han definido un estándar preciso para la documentación de las funciones científicas, es posible que desee seguir para sus propias funciones, con una sección ``Parámetros`` , una sección ``Ejemplos``, etc. Ver http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard y http://projects.scipy.org/numpy/browser/trunk/doc/example.py#L37 -Methods are functions attached to objects. You've seen these in our -examples on *lists*, *dictionaries*, *strings*, etc... +Las funciones son objectos +-------------------------- +Las funciones son la primera clase de objetos, lo que significa que puede: -Exercises ---------- +* asignarse a una variable + +* ser un elemento de una lista (o cualquier colección) + +* ser pasado como argumento a otra función. + +.. sourcecode:: ipython + + In [38]: va = argumentos_variables + + In [39]: va('tres', x=1, y=2) + args es ('tres',) + kwargs es {'y': 2, 'x': 1} + +Métodos +------- + +Los métodos son funciones vinculadas a los objetos. Usted ha visto esto en los ejemplos de *listas*, *diccionarios*, *cadenas*, etc .. + +Ejercicios +---------- -.. topic:: Exercise: Fibonacci sequence - :class: green +.. topic:: Ejercicio: Serie de Fibonacci + :class: green - Write a function that displays the ``n`` first terms of the Fibonacci - sequence, defined by: + Escriba una función que muestre los ``n`` primeros términos de la serie de Fibonacci, definido por: * ``u_0 = 1; u_1 = 1`` * ``u_(n+2) = u_(n+1) + u_n`` .. :ref:`fibonacci` -.. topic:: Exercise: Quicksort - :class: green +.. topic:: Ejercicio: Quicksort + :class: green - Implement the quicksort algorithm, as defined by wikipedia:: + Implemente el algoritmo quicksort, definido por wikipedia:: - function quicksort(array) - var list less, greater - if length(array) < 2 - return array - select and remove a pivot value pivot from array - for each x in array - if x < pivot + 1 then append x to less - else append x to greater - return concatenate(quicksort(less), pivot, quicksort(greater)) + function quicksort(array) + var list less, greater + if length(array) < 2 + return array + select and remove a pivot value pivot from array + for each x in array + if x < pivot + 1 then append x to less + else append x to greater + return concatenate(quicksort(less), pivot, quicksort(greater)) .. :ref:`quick_sort` diff --git a/intro/language/io.rst b/intro/language/io.rst index a119406..f26ca39 100644 --- a/intro/language/io.rst +++ b/intro/language/io.rst @@ -1,65 +1,63 @@ -Input and Output +Entrada y Salida ================ -To be exhaustive, here are some information about input and output in Python. -Since we will use the Numpy methods to read and write files, you may skip this -chapter at first reading. +Para ser más exhaustivos, he aquí algo de información sobre la entrada y salida en Python. -We write or read **strings** to/from files (other types must be converted to -strings). To write in a file:: +Solamente las **cadenas** se escriben o leen a/desde archivos (otros tipos deben convertirse a cadenas). Para escribir en un archivo +.. code-block:: python - >>> f = open('workfile', 'w') # opens the workfile file - >>> type(f) - - >>> f.write('This is a test \nand another test') - >>> f.close() + >>> f = open('archivo_ejemplo', 'w') # creo un archivo + >>> type(f) + + >>> f.write('Esto es una prueba\ny otra prueba') + >>> f.close() -To read from a file +Para leer un archivo .. sourcecode:: ipython - In [1]: f = open('workfile', 'r') + In [1]: f = open('archivo_ejemplo', 'r') - In [2]: s = f.read() + In [2]: s = f.read() - In [3]: print(s) - This is a test - and another test + In [3]: print s + Esto es una prueba + y otra prueba - In [4]: f.close() + In [4]: f.close() +Para más detalles: http://docs.python.org/tutorial/inputoutput.html -For more details: http://docs.python.org/tutorial/inputoutput.html - -Iterating over a file -~~~~~~~~~~~~~~~~~~~~~ +Iterando sobre un archivo +~~~~~~~~~~~~~~~~~~~~~~~~~ .. sourcecode:: ipython - In [6]: f = open('workfile', 'r') + In [6]: f = open('archivo_ejemplo', 'r') + + In [7]: for linea in f: + ...: print linea + ...: + Esto es una prueba + + y otra prueba - In [7]: for line in f: - ...: print line - ...: - ...: - This is a test + In [8]: f.close() - and another test +Modos de archivo +---------------- - In [8]: f.close() +* Solamente lectura: ``r`` -File modes ----------- +* Solamente escritura: ``w`` -* Read-only: ``r`` -* Write-only: ``w`` + * Nota: Crear un nuevo archivo o *sobreescribir* el archivo existente. - * Note: Create a new file or *overwrite* existing file. +* Agregar al archivo: ``a`` -* Append a file: ``a`` -* Read and Write: ``r+`` -* Binary mode: ``b`` +* Leer y escribir: ``r+`` - * Note: Use for binary files, especially on Windows. +* Modo binario: ``b`` + * Nota: Usar para archivos binarios, especialmente en Windows. diff --git a/intro/language/oop.rst b/intro/language/oop.rst index 7f72721..817e386 100644 --- a/intro/language/oop.rst +++ b/intro/language/oop.rst @@ -1,58 +1,46 @@ -Object-oriented programming (OOP) -================================= - -Python supports object-oriented programming (OOP). The goals of OOP are: - - * to organize the code, and - - * to re-use code in similar contexts. - - -Here is a small example: we create a Student *class*, which is an object -gathering several custom functions (*methods*) and variables (*attributes*), -we will be able to use:: - - >>> class Student(object): - ... def __init__(self, name): - ... self.name = name - ... def set_age(self, age): - ... self.age = age - ... def set_major(self, major): - ... self.major = major - ... - >>> anna = Student('anna') - >>> anna.set_age(21) - >>> anna.set_major('physics') - -In the previous example, the Student class has ``__init__``, ``set_age`` and -``set_major`` methods. Its attributes are ``name``, ``age`` and ``major``. We -can call these methods and attributes with the following notation: -``classinstance.method`` or ``classinstance.attribute``. The ``__init__`` -constructor is a special method we call with: ``MyClass(init parameters if -any)``. - -Now, suppose we want to create a new class MasterStudent with the same -methods and attributes as the previous one, but with an additional -``internship`` attribute. We won't copy the previous class, but -**inherit** from it:: - - >>> class MasterStudent(Student): - ... internship = 'mandatory, from March to June' - ... - >>> james = MasterStudent('james') - >>> james.internship - 'mandatory, from March to June' - >>> james.set_age(23) - >>> james.age - 23 - -The MasterStudent class inherited from the Student attributes and methods. - -Thanks to classes and object-oriented programming, we can organize code -with different classes corresponding to different objects we encounter -(an Experiment class, an Image class, a Flow class, etc.), with their own -methods and attributes. Then we can use inheritance to consider -variations around a base class and **re-use** code. Ex : from a Flow -base class, we can create derived StokesFlow, TurbulentFlow, -PotentialFlow, etc. +Programación Orientada a Objetos (POO) +====================================== +Python soporta la programación orientada a objetos (POO). Los objetivos de la programación orientada a objetos son: + +* organizar el código, y + +* volver a utilizar el código en contextos similares. + +He aquí un pequeño ejemplo: creamos la *clase* Estudiante, es un objeto +que reune varias funciones personalizadas (*métodos*) y variables (*atributos*), que pueden usarse + +.. code-block:: python + + >>> class Estudiante(objecto): + ... def __init__(self, nombre): + ... self.nombre = nombre + ... def establece_edad(self, edad): + ... self.edad = edad + ... def establece_licenciatura(self, licenciatura): + ... self.licenciatura = licenciatura + ... + >>> anna = Estudiante('anna') + >>> anna.establece_edad(21) + >>> anna.establece_licenciatura('fisica') + +En el ejemplo anterior, la clase Estudiante tiene los métodos ``__init__``, ``establece_edad`` y ``establece_licenciatura``. Sus atributos son ``nombre``, ``edad`` y ``licenciatura``. Nosotros podemos llamar a estos métodos y atributos con la siguiente notación: ``classinstance.método`` o ``classinstance.atributo``. El constructor ``__init__`` es un método especial que llamamos con: ``MiClase(parámetros de inicio cualquiera)``. + +Ahora, supongamos que queremos crear una nueva clase EstudianteMaestria con los mismos métodos y atributos que el anterior, pero con un atributo adicional ``practicas``. No copiaremos la clase anterior, pero si **heredarlos** de ella + +.. code-block:: python + + >>> class EstudianteMaestria(Estudiante): + ... practicas = 'obligatorias, de marzo a junio' + ... + + >>> james = EstudianteMaestria('james') + >>> james.practicas + 'obligatorias, de marzo a junio' + >>> james.establece_edad(23) + >>> james.edad + 23 + +La clase EstudianteMaestria hereda los atributos y métodos de la clase Estudiante. + +Gracias a las clases y a la programación orientada a objetos, podemos organizar el código en distintas clases correspondientes a diferentes objetos que nos encontramos (clase Experimento, clase Imagen, clase Flujo, etc), con sus propios métodos y atributos. También podemos utilizar la herencia para considerar variaciones en torno a una clase base y **reutilizar** código. Ejemplo: a partir de la clase Flujo, podemos crear sus derivados FlujoStokes, FlujoTurbulento, FlujoPotencial, etc. diff --git a/intro/language/python_language.rst b/intro/language/python_language.rst index 7f4f7ee..b2b9139 100644 --- a/intro/language/python_language.rst +++ b/intro/language/python_language.rst @@ -1,53 +1,36 @@ -The Python language -===================================== +El lenguaje Python +================== -:authors: Chris Burns, Christophe Combelles, Emmanuelle Gouillart, Gaël Varoquaux +:Autores: Chris Burns, Christophe Combelles, Emmanuelle Gouillart, Gaël Varoquaux -.. topic:: Python for scientific computing +.. topic:: Python para computacíon científica - We introduce here the Python language. Only the bare minimum - necessary for getting started with Numpy and Scipy is addressed here. - To learn more about the language, consider going through the - excellent tutorial http://docs.python.org/tutorial. Dedicated books - are also available, such as http://diveintopython.org/. + Esta introducción al lenguaje Python aborda sólo el mínimo necesario para empezar con Numpy y Scipy. Para aprender más sobre el lenguaje, considere revisar este excelente tutorial http://docs.python.org/tutorial. Libros dedicados también están disponibles, tales como http://diveintopython.org/. .. image:: python-logo.png :align: right -Python is a **programming language**, as are C, Fortran, BASIC, PHP, -etc. Some specific features of Python are as follows: +.. tip:: -* an *interpreted* (as opposed to *compiled*) language. Contrary to e.g. - C or Fortran, one does not compile Python code before executing it. In - addition, Python can be used **interactively**: many Python - interpreters are available, from which commands and scripts can be - executed. + Python es un **lenguaje de programación**, al igual que C, Fortran, BASIC, PHP, etc. Algunas de las características específicas de Python son: -* a free software released under an **open-source** license: Python can - be used and distributed free of charge, even for building commercial - software. + * un lenguaje *interpretado* (opuesto a *compilado*). Al contrario de C o Fortran, no se puede compilar código Python antes de ejecutarlo. Además, Python se usa **interactivamente**: muchos intérpretes de Python están disponibles, puede ser ejecutado desde la línea de comandos y mediante scripts. -* **multi-platform**: Python is available for all major operating - systems, Windows, Linux/Unix, MacOS X, most likely your mobile phone - OS, etc. + * Es software libre publicado bajo una licencia **open-source**: Python puede ser utilizado y distribuido de forma gratuita, incluso para la construcción de software comercial. -* a very readable language with clear non-verbose syntax + * **Multiplataforma**: Python está disponible para los principales sistemas operativos, Windows, Linux/Unix, MacOS X, probablemente en su teléfono móvil OS, etc -* a language for which a large variety of high-quality packages are - available for various applications, from web frameworks to scientific - computing. + * Un lenguaje de fácil lectura con una sintaxis clara -* a language very easy to interface with other languages, in particular C - and C++. + * Un lenguaje con una gran variedad de paquetes de alta calidad disponibles para diversas aplicaciones, desde web frameworks hasta cálculos científicos. -* Some other features of the language are illustrated just below. For - example, Python is an object-oriented language, with dynamic typing - (the same variable can contain objects of different types during the - course of a program). + * Un lenguaje de muy fácil interfaz con otros lenguajes, en particular C + y C++. + * Algunas otras características del lenguaje se ilustran más abajo. Por ejemplo, Python es un lenguaje orientado a objetos, con tipado dinámico (la misma variable puede contener objetos de diferentes tipos durante el transcurso de un programa). -See http://www.python.org/about/ for more information about -distinguishing features of Python. + Visite http://www.python.org/about/ para más información acerca de las + distinguidas capacidades de Python. _____ diff --git a/intro/language/reusing_code.rst b/intro/language/reusing_code.rst index 38eee86..b4f410e 100644 --- a/intro/language/reusing_code.rst +++ b/intro/language/reusing_code.rst @@ -1,520 +1,415 @@ -Reusing code: scripts and modules -================================= +Reusando código: scripts y módulos +================================== -For now, we have typed all instructions in the interpreter. For longer -sets of instructions we need to change tack and write the code in text -files (using a text editor), that we will call either *scripts* or -*modules*. Use your favorite text editor (provided it offers syntax -highlighting for Python), or the editor that comes with the Scientific -Python Suite you may be using (e.g., Scite with Python(x,y)). +Por ahora, hemos escrito todas las instrucciones en un intérprete. Para un mayor número de instrucciones debemos cambiar de rumbo y escribir código en archivos de texto (utilizando un editor de texto), que vamos a llamar a *scripts* o *módulos*. Utilice su editor de texto favorito (siempre que ofrezca un coloreado de sintaxis para Python) o el editor que viene con el con la distribución científica de Python que utiliza (por ejemplo, Scite en Python(x,y)). Scripts ------- -Let us first write a *script*, that is a file with a sequence of -instructions that are executed each time the script is called. +.. tip:: Primero vamos a escribir un *script*, que es un archivo con una secuencia de instrucciones que se ejecutan cada vez que el script se llama. Las instrucciones pueden ser, por ejemplo código copiado y pegado desde el intérprete (pero tenga cuidado con las reglas de indentado!). -Instructions may be e.g. copied-and-pasted from the interpreter -(but take care to respect indentation rules!). The extension for Python -files is ``.py``. Write or copy-and-paste the following lines in a file -called ``test.py`` :: +La extensión de los archivos Python son ``.py``. Escriba o copie y pegue las +siguientes líneas en un archivo llamado ``prueba.py`` - message = "Hello how are you?" - for word in message.split(): - print word +.. code-block:: python -Let us now execute the script interactively, that is inside the Ipython -interpreter. This is maybe the most common use of scripts in scientific -computing. + mensaje = "Hola como estas?" + for palabras in mensaje.split(): + print palabras -.. note:: +.. tip:: Ahora vamos a ejecutar el script de una forma interactiva, es decir, dentro del intérprete IPython. Este es quizás el uso más común de scripts en cálculo científico. - in Ipython, the syntax to execute a script is ``%run script.py``. For - example, +.. note:: en IPython, la sintaxis para ejecutar un script es ``%run script.py``. Por ejemplo, -.. sourcecode:: ipython - - In [1]: %run test.py - Hello - how - are - you? + .. sourcecode:: ipython - In [2]: message - Out[2]: 'Hello how are you?' + In [1]: %run prueba.py + Hola + como + estas? + In [2]: mensaje + Out[2]: 'Hola como estas?' -The script has been executed. Moreover the variables defined in the -script (such as ``message``) are now available inside the interpeter's -namespace. + El script ha sido ejecutado. Por otra parte las variables definidas en el script (como ``mensaje``) están disponibles en el intérprete. -Other interpreters also offer the possibility to execute scripts (e.g., -``execfile`` in the plain Python interpreter, etc.). +.. tip:: Otros intérpretes también ofrecen la posibilidad de ejecutar scripts(por ejemplo, ``execfile`` en el intérprete de Python estandar, etc.) -It is also possible In order to execute this script as a *standalone -program*, by executing the script inside a shell terminal (Linux/Mac -console or cmd Windows console). For example, if we are in the same -directory as the test.py file, we can execute this in a console: +También es posible ejecutar este script como un *programa independiente*, mediante la ejecución de la secuencia de comandos en una terminal (consola Linux/Mac o la consola cmd de Windows). Por ejemplo, si estamos en la mismo directorio que el archivo prueba.py, se puede ejecutar esto en una consola: .. sourcecode:: bash - $ python test.py - Hello - how - are - you? - -Standalone scripts may also take command-line arguments + $ python prueba.py + Hola + como + estas? -In ``file.py``:: +.. tip:: Los scripts independientes también pueden tener argumentos. - import sys - print sys.argv +En ``archivo.py`` -.. sourcecode:: bash +.. code-block:: python - $ python file.py test arguments - ['file.py', 'test', 'arguments'] + import sys + print sys.argv -.. note:: +.. sourcecode:: bash - Don't implement option parsing yourself. Use modules such as - ``optparse`` or ``argparse`` . + $ python archivo.py argumento1 argumento2 + ['archivo.py', 'argumento1', 'argumento2'] +.. note:: No implemente una opción de parseado usted mismo. Utilice módulos como ``optparse`` o ``argparse``. -Importing objects from modules ------------------------------- +Importando objectos desde módulos +--------------------------------- .. sourcecode:: ipython - In [1]: import os + In [1]: import os - In [2]: os - Out[2]: + In [2]: os + Out[2]: - In [3]: os.listdir('.') - Out[3]: - ['conf.py', - 'basic_types.rst', - 'control_flow.rst', - 'functions.rst', - 'python_language.rst', - 'reusing.rst', - 'file_io.rst', - 'exceptions.rst', - 'workflow.rst', - 'index.rst'] + In [3]: os.listdir('.') + Out[3]: + ['conf.py', + 'basic_types.rst', + 'control_flow.rst', + 'functions.rst', + 'python_language.rst', + 'reusing.rst', + 'file_io.rst', + 'exceptions.rst', + 'workflow.rst', + 'index.rst'] -And also: +O también: .. sourcecode:: ipython - In [4]: from os import listdir - -Importing shorthands: + In [4]: from os import listdir + In [5]: listdir('.') + Out[5]: + ['conf.py', + 'basic_types.rst', + 'control_flow.rst', + 'functions.rst', + 'python_language.rst', + 'reusing.rst', + 'file_io.rst', + 'exceptions.rst', + 'workflow.rst', + 'index.rst'] + +Importando con abreviaturas: .. sourcecode:: ipython - In [5]: import numpy as np + In [6]: import numpy as np .. warning:: - :: + .. code-block:: python - from os import * + from os import * - This is called the *star import* and please, **Use it with caution** + Esto se conoce como *importar una estrella* y por favor, **Debe usarlo con precaución** - * Makes the code harder to read and understand: where do symbols come - from? + * Hace que el código sea más difícil de leer y entender: de dónde vienen estas variables? - * Makes it impossible to guess the functionality by the context and - the name (hint: `os.name` is the name of the OS), and to profit - usefully from tab completion. + * Hace que sea imposible adivinar su funcionalidad por contexto y nombre (pista: `os.name` es el nombre del sistema operativo), y utilizar el autocompletado con tabulador. - * Restricts the variable names you can use: `os.name` might override - `name`, or vise-versa. + * Limita los nombres de las variables que se pueden utilizar: `os.name` podría anular `name`, o vice-versa. - * Creates possible name clashes between modules. + * Crea posibles conflictos de nombres entre módulos. - * Makes the code impossible to statically check for undefined - symbols. + * Hace que el código sea imposible de comprobar estáticamente para variables indefinidas. -Modules are thus a good way to organize code in a hierarchical way. Actually, -all the scientific computing tools we are going to use are modules:: +.. tip:: Los módulos son una buena forma de organizar el código de una manera jerárquica. En realidad, todas las herramientas de cálculo científico que utilizamos son módulos - >>> import numpy as np # data arrays - >>> np.linspace(0, 10, 6) - array([ 0., 2., 4., 6., 8., 10.]) - >>> import scipy # scientific computing +.. code-block:: python + >>> import numpy as np # arreglos optimizados + >>> np.linspace(0, 10, 6) + array([ 0., 2., 4., 6., 8., 10.]) + >>> import scipy # cálculo científico -In Python(x,y), Ipython(x,y) executes the following imports at startup:: +En Python(x,y), Ipython(x,y) estos módulos se importan automaticamente al inicio: - >>> import numpy - >>> import numpy as np - >>> from pylab import * - >>> import scipy +.. code-block:: python -and it is not necessary to re-import these modules. + >>> import numpy + >>> import numpy as np + >>> from pylab import * + >>> import scipy +y no es necesario volver a importar estos módulos. -Creating modules ------------------ +Creando módulos +--------------- -If we want to write larger and better organized programs (compared to -simple scripts), where some objects are defined, (variables, functions, -classes) and that we want to reuse several times, we have to create our -own *modules*. +.. tip:: Si queremos escribir programas organizados más grandes y mejores (comparados con scripts simples), donde se definen algunos objetos, (variables, funciones, clases) y queremos volver a utilizar varias veces, tenemos crear nuestros propios *módulos*. -Let us create a module ``demo`` contained in the file ``demo.py``: +Vamos a crear el módulo ``demo`` contenido en el archivo ``demo.py``: - .. literalinclude:: demo.py - -In this file, we defined two functions ``print_a`` and ``print_b``. Suppose -we want to call the ``print_a`` function from the interpreter. We could -execute the file as a script, but since we just want to have access to -the function ``print_a``, we are rather going to **import it as a module**. -The syntax is as follows. +.. literalinclude:: demo.py +.. tip:: En este archivo, definimos dos funciones ``print_a`` y ``print_b``. Si queremos llamar a la función ``print_a`` desde el intérprete. Podríamos ejecutar el archivo como un script, pero ya que sólo se quiere tener acceso a la función ``print_a``, es mejor **importarlo como un módulo**. + La sintaxis es la siguiente. .. sourcecode:: ipython - In [1]: import demo - - - In [2]: demo.print_a() - a + In [1]: import demo - In [3]: demo.print_b() - b + In [2]: demo.print_a() + a -Importing the module gives access to its objects, using the -``module.object`` syntax. Don't forget to put the module's name before the -object's name, otherwise Python won't recognize the instruction. + In [3]: demo.print_b() + b +Importar un módulo permite el acceso a sus objetos, utilizando la sintaxis ``módulo.objecto``. No se olvide de poner el nombre del módulo antes del nombre del objeto, de lo contrario Python no reconocerá la instrucción. -Introspection +Introspección .. sourcecode:: ipython - In [4]: demo? - Type: module - Base Class: - String Form: - Namespace: Interactive - File: /home/varoquau/Projects/Python_talks/scipy_2009_tutorial/source/demo.py - Docstring: - A demo module. - - - In [5]: who - demo - - In [6]: whos - Variable Type Data/Info - ------------------------------ - demo module - - In [7]: dir(demo) - Out[7]: - ['__builtins__', - '__doc__', - '__file__', - '__name__', - '__package__', - 'c', - 'd', - 'print_a', - 'print_b'] - - - In [8]: demo. - demo.__builtins__ demo.__init__ demo.__str__ - demo.__class__ demo.__name__ demo.__subclasshook__ - demo.__delattr__ demo.__new__ demo.c - demo.__dict__ demo.__package__ demo.d - demo.__doc__ demo.__reduce__ demo.print_a - demo.__file__ demo.__reduce_ex__ demo.print_b - demo.__format__ demo.__repr__ demo.py - demo.__getattribute__ demo.__setattr__ demo.pyc - demo.__hash__ demo.__sizeof__ - - -Importing objects from modules into the main namespace + In [4]: demo? + Type: module + String Form: + File: /home/varoquau/Projects/Python_talks/scipy_2009_tutorial/source/demo.py + Docstring: Módulo demo. + + + In [5]: who + demo + + In [6]: whos + Variable Type Data/Info + ------------------------------ + demo module + + In [7]: dir(demo) + Out[7]: + ['__builtins__', + '__doc__', + '__file__', + '__name__', + '__package__', + 'c', + 'd', + 'print_a', + 'print_b'] + + + In [8]: demo. + demo.__builtins__ demo.__init__ demo.__str__ + demo.__class__ demo.__name__ demo.__subclasshook__ + demo.__delattr__ demo.__new__ demo.c + demo.__dict__ demo.__package__ demo.d + demo.__doc__ demo.__reduce__ demo.print_a + demo.__file__ demo.__reduce_ex__ demo.print_b + demo.__format__ demo.__repr__ demo.py + demo.__getattribute__ demo.__setattr__ demo.pyc + demo.__hash__ demo.__sizeof__ + +Importando objetos a partir de módulos en el espacio de nombres principal .. sourcecode:: ipython - In [9]: from demo import print_a, print_b + In [9]: from demo import print_a, print_b - In [10]: whos - Variable Type Data/Info - -------------------------------- - demo module - print_a function - print_b function - - In [11]: print_a() - a - -.. warning:: + In [10]: whos + Variable Type Data/Info + -------------------------------- + demo module + print_a function + print_b function - **Module caching** + In [11]: print_a() + a - Modules are cached: if you modify ``demo.py`` and re-import it in the - old session, you will get the old one. +.. warning:: **Módulos almacenados en caché** - Solution: + Los módulos se almacenan en caché: si modifica ``demo.py`` y lo vuelve a importar, obtendrá el módulo antiguo. - .. sourcecode :: ipython + Solución: - In [10]: reload(demo) + .. sourcecode :: ipython + In [10]: reload(demo) + Out[10]: -'__main__' and module loading ------------------------------- +'__main__' y cargando módulos +----------------------------- -File ``demo2.py``: +Archivo ``demo2.py``: - .. literalinclude:: demo2.py +.. literalinclude:: demo2.py -Importing it: +Importando: .. sourcecode:: ipython - In [11]: import demo2 - b + In [11]: import demo2 + b - In [12]: import demo2 + In [12]: import demo2 -Running it: +Ejecutando: .. sourcecode:: ipython - In [13]: %run demo2 - b - a + In [13]: %run demo2 + b + a +Scripts o módulos? Cómo organizar su código +------------------------------------------- -Scripts or modules? How to organize your code ---------------------------------------------- +.. note:: Regla de oro -.. Note:: Rule of thumb + * Los conjuntos de instrucciones que se llaman varias veces deben estar escritos dentro de **funciones** para una mejor reutilización del código. - * Sets of instructions that are called several times should be - written inside **functions** for better code reusability. + * Funciones (u otras partes de código) que se llaman varias veces desde scripts deben ser escritos dentro de un **módulo**, de modo que el módulo es importado en los demás scripts (no copie y pegue sus funciones en los demás scripts!). - * Functions (or other bits of code) that are called from several - scripts should be written inside a **module**, so that only the - module is imported in the different scripts (do not copy-and-paste - your functions in the different scripts!). +Cómo encontrar módulos e importarlos +.................................... -.. Note:: How to import a module from a remote directory? +Cuando se ejecuta ``import mimodulo``, el módulo ``mimodulo`` se busca en una lista de directorios. Esta lista incluye por defecto una lista de la ruta de instalación (por ejemplo, ``/usr/lib/python``) así como la lista de los directorios especificados por la variable de entorno ``PYTHONPATH``. - .. +La lista de directorios en los que busca Python viene dada por la variable ``sys.path`` - Many solutions exist, depending mainly on your operating system. When - the ``import mymodule`` statement is executed, the module ``mymodule`` - is searched in a given list of directories. This list includes a list - of installation-dependent default path (e.g., ``/usr/lib/python``) as - well as the list of directories specified by the environment variable - ``PYTHONPATH``. - - The list of directories searched by Python is given by the ``sys.path`` - variable - - .. sourcecode:: ipython +.. sourcecode:: ipython - In [1]: import sys + In [1]: import sys - In [2]: sys.path - Out[2]: - ['', - '/usr/bin', - '/usr/local/include/enthought.traits-1.1.0', - '/usr/lib/python2.6', - '/usr/lib/python2.6/plat-linux2', - '/usr/lib/python2.6/lib-tk', - '/usr/lib/python2.6/lib-old', - '/usr/lib/python2.6/lib-dynload', - '/usr/lib/python2.6/dist-packages', - '/usr/lib/pymodules/python2.6', - '/usr/lib/pymodules/python2.6/gtk-2.0', - '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', - '/usr/local/lib/python2.6/dist-packages', - '/usr/lib/python2.6/dist-packages', - '/usr/lib/pymodules/python2.6/IPython/Extensions', - u'/home/gouillar/.ipython'] + In [2]: sys.path + Out[2]: + ['', + '/home/varoquau/.local/bin', + '/usr/lib/python2.7', + '/home/varoquau/.local/lib/python2.7/site-packages', + '/usr/lib/python2.7/dist-packages', + '/usr/local/lib/python2.7/dist-packages', + ...] - Modules must be located in the search path, therefore you can: +Los módulos deben estar ubicados en la ruta de búsqueda, por lo tanto, se puede: - * write your own modules within directories already defined in the - search path (e.g. ``/usr/local/lib/python2.6/dist-packages``). You - may use symbolic links (on Linux) to keep the code somewhere else. +* Escribir sus propios módulos dentro de los directorios que ya están definidas en el ruta de búsqueda (por ejemplo, ``$HOME/.local/lib/python2.7/dist-packages``). También puede usar enlaces simbólicos (en Linux) para mantener el código de otro sitio. - * modify the environment variable ``PYTHONPATH`` to include the - directories containing the user-defined modules. On Linux/Unix, add - the following line to a file read by the shell at startup (e.g. - /etc/profile, .profile) +* Modificar la variable de entorno ``PYTHONPATH`` para incluir el directorios que contienen los módulos definidos por el usuario. - :: +.. tip:: En Linux/Unix, agregue la siguiente línea en un archivo para que sea leido por el shell al inicio (por ejemplo, /etc/profile, . profile) - export PYTHONPATH=$PYTHONPATH:/home/emma/user_defined_modules + .. code-block:: python + export PYTHONPATH=$PYTHONPATH:/home/emma/user_defined_modules - On Windows, http://support.microsoft.com/kb/310519 explains how to - handle environment variables. +En Windows, http://support.microsoft.com/kb/310519 explica cómo manejar las variables de entorno. - * or modify the ``sys.path`` variable itself within a Python script. +* o modifique la variable ``sys.path`` con un script Python. - :: +.. tip:: - import sys - new_path = '/home/emma/user_defined_modules' - if new_path not in sys.path: - sys.path.append(new_path) + .. code-block:: python - This method is not very robust, however, because it makes the code - less portable (user-dependent path) and because you have to add the - directory to your sys.path each time you want to import from a module in - this directory. + import sys + nuevo_path = '/home/emma/user_defined_modules' + if nuevo_path not in sys.path: + sys.path.append(nuevo_path) -See http://docs.python.org/tutorial/modules.html for more information -about modules. + Este método no es muy robusto, sin embargo, hace que el código sea menos portable (la ruta depende del usuario) y porque hay que añadir el directorio a su sys.path cada vez que desee importar un módulo en este directorio. + + Vea http://docs.python.org/tutorial/modules.html para más información acerca de los módulos. -Packages +Paquetes -------- -A directory that contains many modules is called a *package*. A package -is a module with submodules (which can have submodules themselves, etc.). -A special file called ``__init__.py`` (which may be empty) tells Python -that the directory is a Python package, from which modules can be -imported. +Un directorio que contiene muchos módulos se llama un *paquete*. Un paquete +es un módulo con submódulos (submódulos con submódulos, etc). +Un archivo especial llamado ``__init__.py`` (que puede estar vacío) le dice a Python que el directorio es un paquete Python, del cual los módulos pueden ser importados. .. sourcecode:: bash - $ ls - cluster/ io/ README.txt@ stsci/ - __config__.py@ LATEST.txt@ setup.py@ __svn_version__.py@ - __config__.pyc lib/ setup.pyc __svn_version__.pyc - constants/ linalg/ setupscons.py@ THANKS.txt@ - fftpack/ linsolve/ setupscons.pyc TOCHANGE.txt@ - __init__.py@ maxentropy/ signal/ version.py@ - __init__.pyc misc/ sparse/ version.pyc - INSTALL.txt@ ndimage/ spatial/ weave/ - integrate/ odr/ special/ - interpolate/ optimize/ stats/ - $ cd ndimage - $ ls - doccer.py@ fourier.pyc interpolation.py@ morphology.pyc setup.pyc - doccer.pyc info.py@ interpolation.pyc _nd_image.so - setupscons.py@ - filters.py@ info.pyc measurements.py@ _ni_support.py@ - setupscons.pyc - filters.pyc __init__.py@ measurements.pyc _ni_support.pyc tests/ - fourier.py@ __init__.pyc morphology.py@ setup.py@ - - -From Ipython: + $ ls + cluster/ io/ README.txt@ stsci/ + __config__.py@ LATEST.txt@ setup.py@ __svn_version__.py@ + __config__.pyc lib/ setup.pyc __svn_version__.pyc + constants/ linalg/ setupscons.py@ THANKS.txt@ + fftpack/ linsolve/ setupscons.pyc TOCHANGE.txt@ + __init__.py@ maxentropy/ signal/ version.py@ + __init__.pyc misc/ sparse/ version.pyc + INSTALL.txt@ ndimage/ spatial/ weave/ + integrate/ odr/ special/ + interpolate/ optimize/ stats/ + $ cd ndimage + $ ls + doccer.py@ fourier.pyc interpolation.py@ morphology.pyc setup.pyc + doccer.pyc info.py@ interpolation.pyc _nd_image.so + setupscons.py@ + filters.py@ info.pyc measurements.py@ _ni_support.py@ + setupscons.pyc + filters.pyc __init__.py@ measurements.pyc _ni_support.pyc tests/ + fourier.py@ __init__.pyc morphology.py@ setup.py@ + + +Desde Ipython: .. sourcecode:: ipython - In [1]: import scipy - - In [2]: scipy.__file__ - Out[2]: '/usr/lib/python2.6/dist-packages/scipy/__init__.pyc' - - In [3]: import scipy.version - - In [4]: scipy.version.version - Out[4]: '0.7.0' + In [1]: import scipy - In [5]: import scipy.ndimage.morphology + In [2]: scipy.__file__ + Out[2]: '/usr/lib/python2.7/dist-packages/scipy/__init__.pyc' - In [6]: from scipy.ndimage import morphology + In [3]: scipy.__version__ + Out[3]: '0.9.0' - In [17]: morphology.binary_dilation? - Type: function - Base Class: - String Form: - Namespace: Interactive - File: /usr/lib/python2.6/dist-packages/scipy/ndimage/morphology.py - Definition: morphology.binary_dilation(input, structure=None, - iterations=1, mask=None, output=None, border_value=0, origin=0, - brute_force=False) - Docstring: - Multi-dimensional binary dilation with the given structure. + In [4]: import scipy.ndimage.morphology - An output array can optionally be provided. The origin parameter - controls the placement of the filter. If no structuring element is - provided an element is generated with a squared connectivity equal - to one. The dilation operation is repeated iterations times. If - iterations is less than 1, the dilation is repeated until the - result does not change anymore. If a mask is given, only those - elements with a true value at the corresponding mask element are - modified at each iteration. + In [5]: from scipy.ndimage import morphology + In [6]: morphology.binary_dilation? + Type: function + String Form: + File: /usr/lib/python2.7/dist-packages/scipy/ndimage/morphology.py + Definition: morphology.binary_dilation(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False) +Buenas practicas +---------------- +* Use **nombres significativos** para los objetos -Good practices --------------- +* **Indentado: no es opcional!** -.. Note:: **Good practices** + .. tip:: El indentado es obligatorio en Python! Cada bloque de comandos después de un ``:`` aumenta un nivel de indentado adicional con respecto a la línea anterior. Como también, después de ``def f():`` o ``while:``. Al final de tales bloques lógicos, se debera disminuir la profundidad de indentado (o aumentar si se introduce un nuevo bloque, etc) - * **Indentation: no choice!** + El uso estricto del indentado es el precio a pagar por deshacerse de ``{`` or ``;`` caracteres que delimitan bloques lógicos en otros lenguajes. La indentación inadecuada produce errores tales como: - Indenting is compulsory in Python! Every command block following a - colon bears an additional indentation level with respect to the - previous line with a colon. One must therefore indent after - ``def f():`` or ``while:``. At the end of such logical blocks, one - decreases the indentation depth (and re-increases it if a new block - is entered, etc.) - - Strict respect of indentation is the price to pay for getting rid of - ``{`` or ``;`` characters that delineate logical blocks in other - languages. Improper indentation leads to errors such as - - .. sourcecode:: ipython + .. sourcecode:: ipython ------------------------------------------------------------ - IndentationError: unexpected indent (test.py, line 2) - - All this indentation business can be a bit confusing in the - beginning. However, with the clear indentation, and in the absence of - extra characters, the resulting code is very nice to read compared to - other languages. - - * **Indentation depth**: - - Inside your text editor, you may choose to - indent with any positive number of spaces (1, 2, 3, 4, ...). However, - it is considered good practice to **indent with 4 spaces**. You may - configure your editor to map the ``Tab`` key to a 4-space - indentation. In Python(x,y), the editor ``Scite`` is already - configured this way. + IndentationError: unexpected indent (prueba.py, line 2) - * **Style guidelines** + El indentado puede ser un poco confuso al principio. Sin embargo, con una clara indentación y en ausencia de caracteres extra, el código es muy agradable de leer en comparación con otros lenguajes. - **Long lines**: you should not write very long lines that span over more - than (e.g.) 80 characters. Long lines can be broken with the ``\`` - character :: +* **Profundidad de indentado**: En un editor de texto, el indentado puede ser cualquier número positivo de espacios (1, 2, 3, 4, ...). Sin embargo, se considera una buena práctica **indentar con 4 espacios**. Usted puede configurar el editor para asignar a la tecla ``tab`` un indentado de 4 espacio. En Python(x,y), el editor es ya configurado de esa manera. - >>> long_line = "Here is a very very long line \ - ... that we break in two parts." +* **Normas de estilo** - **Spaces** + **Líneas Largas**: no se debe escribir líneas muy largas que se extiendan por más de (por ejemplo) 80 caracteres. Las líneas largas se pueden dividir con el carácter ``\`` + + .. code-block:: python - Write well-spaced code: put whitespaces after commas, around arithmetic - operators, etc.:: + >>> linea_larga = "Esta una línea muy muy larga \ + ... que se divide en dos partes." - >>> a = 1 # yes - >>> a=1 # too cramped + **Espacios** - A certain number of rules - for writing "beautiful" code (and more importantly using the same - conventions as anybody else!) are given in the `Style Guide for Python - Code `_. + Escriba código bien espaciado: ponga espacios en blanco después de las comas, ponga espacios en blanco antes y después de los operadores aritméticos, etc. - * Use **meaningful** object **names** + .. code-block:: python + >>> a = 1 # si + >>> a=1 # demasiado estrecho + Un cierto número de normas para escribir código ``hermoso`` (y lo más importante el uso de la misma convención para cualquier persona!) se dan en `Style Guide for Python Code `_. diff --git a/intro/language/standard_library.rst b/intro/language/standard_library.rst index f579a49..f2dfa45 100644 --- a/intro/language/standard_library.rst +++ b/intro/language/standard_library.rst @@ -1,306 +1,309 @@ -Standard Library -================ +Biblioteca estándar +=================== -.. note:: Reference document for this section: +.. note:: Documentos de referencia para esta sección: - * The Python Standard Library documentation: - http://docs.python.org/library/index.html + * The Python Standard Library documentation: + http://docs.python.org/library/index.html - * Python Essential Reference, David Beazley, Addison-Wesley Professional + * Python Essential Reference, David Beazley, Addison-Wesley Professional -``os`` module: operating system functionality ------------------------------------------------ +``os`` módulo: funciones del sistema operativo +---------------------------------------------- -*"A portable way of using operating system dependent functionality."* +*La manera portátil de usar el sistema operativo depende de sus funciones.* -Directory and file manipulation -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Manipulación de directorios y archivos +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Current directory: +Carpeta actual: .. sourcecode:: ipython - In [17]: os.getcwd() - Out[17]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source' + In [16]: import os -List a directory: + In [17]: os.getcwd() + Out[17]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source' + +Lista de carpetas: .. sourcecode:: ipython - In [31]: os.listdir(os.curdir) - Out[31]: - ['.index.rst.swo', - '.python_language.rst.swp', - '.view_array.py.swp', - '_static', - '_templates', - 'basic_types.rst', - 'conf.py', - 'control_flow.rst', - 'debugging.rst', - ... - -Make a directory: + In [31]: os.listdir(os.curdir) + Out[31]: + ['.index.rst.swo', + '.python_language.rst.swp', + '.view_array.py.swp', + '_static', + '_templates', + 'basic_types.rst', + 'conf.py', + 'control_flow.rst', + 'debugging.rst', + ... + +Creando una carpeta: .. sourcecode:: ipython - In [32]: os.mkdir('junkdir') + In [32]: os.mkdir('junkdir') - In [33]: 'junkdir' in os.listdir(os.curdir) - Out[33]: True + In [33]: 'junkdir' in os.listdir(os.curdir) + Out[33]: True -Rename the directory: +Renombrando una carpeta: .. sourcecode:: ipython - In [36]: os.rename('junkdir', 'foodir') + In [36]: os.rename('junkdir', 'foodir') - In [37]: 'junkdir' in os.listdir(os.curdir) - Out[37]: False + In [37]: 'junkdir' in os.listdir(os.curdir) + Out[37]: False - In [38]: 'foodir' in os.listdir(os.curdir) - Out[38]: True + In [38]: 'foodir' in os.listdir(os.curdir) + Out[38]: True + +Borrando una carpeta: + +.. sourcecode:: ipython - In [41]: os.rmdir('foodir') + In [41]: os.rmdir('foodir') - In [42]: 'foodir' in os.listdir(os.curdir) - Out[42]: False + In [42]: 'foodir' in os.listdir(os.curdir) + Out[42]: False -Delete a file: +Creando un archivo: .. sourcecode:: ipython - In [44]: fp = open('junk.txt', 'w') + In [44]: fp = open('junk.txt', 'w') - In [45]: fp.close() + In [45]: fp.close() - In [46]: 'junk.txt' in os.listdir(os.curdir) - Out[46]: True + In [46]: 'junk.txt' in os.listdir(os.curdir) + Out[46]: True - In [47]: os.remove('junk.txt') +Borrando un archivo: - In [48]: 'junk.txt' in os.listdir(os.curdir) - Out[48]: False +.. sourcecode:: ipython + + In [47]: os.remove('junk.txt') + + In [48]: 'junk.txt' in os.listdir(os.curdir) + Out[48]: False -``os.path``: path manipulations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +``os.path``: manipulanado el path +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -``os.path`` provides common operations on pathnames. +``os.path`` proporciona operaciones comunes con el path. .. sourcecode:: ipython - In [70]: fp = open('junk.txt', 'w') + In [70]: fp = open('junk.txt', 'w') - In [71]: fp.close() + In [71]: fp.close() - In [72]: a = os.path.abspath('junk.txt') + In [72]: a = os.path.abspath('junk.txt') - In [73]: a - Out[73]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source/junk.txt' + In [73]: a + Out[73]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source/junk.txt' - In [74]: os.path.split(a) - Out[74]: ('/Users/cburns/src/scipy2009/scipy_2009_tutorial/source', + In [74]: os.path.split(a) + Out[74]: ('/Users/cburns/src/scipy2009/scipy_2009_tutorial/source', 'junk.txt') - In [78]: os.path.dirname(a) - Out[78]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source' + In [78]: os.path.dirname(a) + Out[78]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source' - In [79]: os.path.basename(a) - Out[79]: 'junk.txt' + In [79]: os.path.basename(a) + Out[79]: 'junk.txt' - In [80]: os.path.splitext(os.path.basename(a)) - Out[80]: ('junk', '.txt') + In [80]: os.path.splitext(os.path.basename(a)) + Out[80]: ('junk', '.txt') - In [84]: os.path.exists('junk.txt') - Out[84]: True + In [84]: os.path.exists('junk.txt') + Out[84]: True - In [86]: os.path.isfile('junk.txt') - Out[86]: True + In [86]: os.path.isfile('junk.txt') + Out[86]: True - In [87]: os.path.isdir('junk.txt') - Out[87]: False + In [87]: os.path.isdir('junk.txt') + Out[87]: False - In [88]: os.path.expanduser('~/local') - Out[88]: '/Users/cburns/local' + In [88]: os.path.expanduser('~/local') + Out[88]: '/Users/cburns/local' - In [92]: os.path.join(os.path.expanduser('~'), 'local', 'bin') - Out[92]: '/Users/cburns/local/bin' + In [92]: os.path.join(os.path.expanduser('~'), 'local', 'bin') + Out[92]: '/Users/cburns/local/bin' -Running an external command -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Ejecutando un comando externo +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. sourcecode:: ipython - In [8]: os.system('ls') - basic_types.rst demo.py functions.rst python_language.rst standard_library.rst - control_flow.rst exceptions.rst io.rst python-logo.png - demo2.py first_steps.rst oop.rst reusing_code.rst + In [8]: os.system('ls') + basic_types.rst demo.py functions.rst python_language.rst standard_library.rst + control_flow.rst exceptions.rst io.rst python-logo.png + demo2.py first_steps.rst oop.rst reusing_code.rst -.. note:: Alternative to ``os.system`` +.. note:: Alternativa a ``os.system`` - A noteworthy alternative to ``os.system`` is the `sh module - `_. Which provides much more convenient ways to - obtain the output, error stream and exit code of the external command. + Una notable alternativa a ``os.system`` es el `módulo sh `_. Que proporciona una manera mucho más conveniente de obtener la salida, flujo de errores y código a la salida de un comando externo. - .. sourcecode:: ipython + .. sourcecode:: ipython - In [20]: import sh - In [20]: com = sh.ls() + In [20]: import sh + In [20]: com = sh.ls() - In [21]: print com - basic_types.rst exceptions.rst oop.rst standard_library.rst - control_flow.rst first_steps.rst python_language.rst - demo2.py functions.rst python-logo.png - demo.py io.rst reusing_code.rst + In [21]: print com + basic_types.rst exceptions.rst oop.rst standard_library.rst + control_flow.rst first_steps.rst python_language.rst + demo2.py functions.rst python-logo.png + demo.py io.rst reusing_code.rst - In [22]: print com.exit_code - 0 - In [23]: type(com) - Out[23]: sh.RunningCommand + In [22]: print com.exit_code + 0 + In [23]: type(com) + Out[23]: sh.RunningCommand - -Walking a directory +Recorrer una carpeta ~~~~~~~~~~~~~~~~~~~~ -``os.path.walk`` generates a list of filenames in a directory tree. +``os.path.walk`` genera una lista de nombres de archivos en un árbol de carpetas. .. sourcecode:: ipython - In [10]: for dirpath, dirnames, filenames in os.walk(os.curdir): - ....: for fp in filenames: - ....: print os.path.abspath(fp) - ....: - ....: - /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/.index.rst.swo - /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/.view_array.py.swp - /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/basic_types.rst - /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/conf.py - /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/control_flow.rst - ... - -Environment variables: -~~~~~~~~~~~~~~~~~~~~~~ + In [10]: for dirpath, dirnames, filenames in os.walk(os.curdir): + ....: for fp in filenames: + ....: print os.path.abspath(fp) + ....: + ....: + /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/.index.rst.swo + /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/.view_array.py.swp + /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/basic_types.rst + /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/conf.py + /Users/cburns/src/scipy2009/scipy_2009_tutorial/source/control_flow.rst + ... + +Variables de entorno: +~~~~~~~~~~~~~~~~~~~~~ .. sourcecode:: ipython - In [9]: import os - - In [11]: os.environ.keys() - Out[11]: - ['_', - 'FSLDIR', - 'TERM_PROGRAM_VERSION', - 'FSLREMOTECALL', - 'USER', - 'HOME', - 'PATH', - 'PS1', - 'SHELL', - 'EDITOR', - 'WORKON_HOME', - 'PYTHONPATH', - ... - - In [12]: os.environ['PYTHONPATH'] - Out[12]: '.:/Users/cburns/src/utils:/Users/cburns/src/nitools: - /Users/cburns/local/lib/python2.5/site-packages/: - /usr/local/lib/python2.5/site-packages/: - /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5' + In [9]: import os + + In [11]: os.environ.keys() + Out[11]: + ['_', + 'FSLDIR', + 'TERM_PROGRAM_VERSION', + 'FSLREMOTECALL', + 'USER', + 'HOME', + 'PATH', + 'PS1', + 'SHELL', + 'EDITOR', + 'WORKON_HOME', + 'PYTHONPATH', + ... - In [16]: os.getenv('PYTHONPATH') - Out[16]: '.:/Users/cburns/src/utils:/Users/cburns/src/nitools: - /Users/cburns/local/lib/python2.5/site-packages/: - /usr/local/lib/python2.5/site-packages/: - /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5' + In [12]: os.environ['PYTHONPATH'] + Out[12]: '.:/Users/cburns/src/utils:/Users/cburns/src/nitools: + /Users/cburns/local/lib/python2.5/site-packages/: + /usr/local/lib/python2.5/site-packages/: + /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5' + In [16]: os.getenv('PYTHONPATH') + Out[16]: '.:/Users/cburns/src/utils:/Users/cburns/src/nitools: + /Users/cburns/local/lib/python2.5/site-packages/: + /usr/local/lib/python2.5/site-packages/: + /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5' -``shutil``: high-level file operations ---------------------------------------- +``shutil``: Operaciones de alto nivel con archivos +-------------------------------------------------- -The ``shutil`` provides useful file operations: +El módulo ``shutil`` proporciona operaciones útiles con archivos: - * ``shutil.rmtree``: Recursively delete a directory tree. - * ``shutil.move``: Recursively move a file or directory to another location. - * ``shutil.copy``: Copy files or directories. + * ``shutil.rmtree``: Borrado recursivo de un árbol de directorios. + * ``shutil.move``: Copia recursiva de un archivo o directorio a otra ubicación. + * ``shutil.copy``: Copiar archivos o directorios. -``glob``: Pattern matching on files -------------------------------------- +``glob``: Coincidencia de patrones en archivos +---------------------------------------------- -The ``glob`` module provides convenient file pattern matching. +El módulo ``glob`` provee búsqueda por coincidencia de patrones en archivos. -Find all files ending in ``.txt``: +Buscar todos los archivos que terminen en ``.txt``: .. sourcecode:: ipython - In [18]: import glob - - In [19]: glob.glob('*.txt') - Out[19]: ['holy_grail.txt', 'junk.txt', 'newfile.txt'] + In [18]: import glob + In [19]: glob.glob('*.txt') + Out[19]: ['holy_grail.txt', 'junk.txt', 'newfile.txt'] +``sys``: Información específica del sistema +------------------------------------------- -``sys`` module: system-specific information --------------------------------------------- +Sistema de información específica relacionada con el intérprete de Python. -System-specific information related to the Python interpreter. - -* Which version of python are you running and where is it installed: +* Qué versión de Python estás ejecutando y donde está instalado: .. sourcecode:: ipython - In [117]: sys.platform - Out[117]: 'darwin' + In [116]: import sys - In [118]: sys.version - Out[118]: '2.5.2 (r252:60911, Feb 22 2008, 07:57:53) \n - [GCC 4.0.1 (Apple Computer, Inc. build 5363)]' + In [117]: sys.platform + Out[117]: 'linux2' - In [119]: sys.prefix - Out[119]: '/Library/Frameworks/Python.framework/Versions/2.5' + In [118]: sys.version + Out[118]: '2.7.3 (default, Apr 10 2013, 05:46:21) \n[GCC 4.6.3]' -* List of command line arguments passed to a Python script: + In [119]: sys.prefix + Out[119]: '/usr' - .. sourcecode:: ipython +* Lista de argumentos de la línea de comandos pasados ​​a un script Python: - In [100]: sys.argv - Out[100]: ['/Users/cburns/local/bin/ipython'] + .. sourcecode:: ipython + In [120]: sys.argv + Out[120]: ['/usr/bin/ipython'] -``sys.path`` is a list of strings that specifies the search path for -modules. Initialized from PYTHONPATH: +``sys.path`` es una lista de cadenas que especifica la ruta de búsqueda de +módulos. Iniciada desde PYTHONPATH: .. sourcecode:: ipython - In [121]: sys.path - Out[121]: - ['', - '/Users/cburns/local/bin', - '/Users/cburns/local/lib/python2.5/site-packages/grin-1.1-py2.5.egg', - '/Users/cburns/local/lib/python2.5/site-packages/argparse-0.8.0-py2.5.egg', - '/Users/cburns/local/lib/python2.5/site-packages/urwid-0.9.7.1-py2.5.egg', - '/Users/cburns/local/lib/python2.5/site-packages/yolk-0.4.1-py2.5.egg', - '/Users/cburns/local/lib/python2.5/site-packages/virtualenv-1.2-py2.5.egg', - ... + In [121]: sys.path + Out[121]: + ['', + '/Users/cburns/local/bin', + '/Users/cburns/local/lib/python2.5/site-packages/grin-1.1-py2.5.egg', + '/Users/cburns/local/lib/python2.5/site-packages/argparse-0.8.0-py2.5.egg', + '/Users/cburns/local/lib/python2.5/site-packages/urwid-0.9.7.1-py2.5.egg', + '/Users/cburns/local/lib/python2.5/site-packages/yolk-0.4.1-py2.5.egg', + '/Users/cburns/local/lib/python2.5/site-packages/virtualenv-1.2-py2.5.egg', + ... -``pickle``: easy persistence -------------------------------- +``pickle``: fácil persistencia +------------------------------ -Useful to store arbitrary objects to a file. Not safe or fast! +Útil para almacenar objetos arbitrarios a un archivo. No es seguro o rápido! .. sourcecode:: ipython - In [1]: import pickle - - In [2]: l = [1, None, 'Stan'] + In [1]: import pickle - In [3]: pickle.dump(l, file('test.pkl', 'w')) + In [2]: l = [1, None, 'Stan'] - In [4]: pickle.load(file('test.pkl')) - Out[4]: [1, None, 'Stan'] + In [3]: pickle.dump(l, file('test.pkl', 'w')) + In [4]: pickle.load(file('test.pkl')) + Out[4]: [1, None, 'Stan'] -.. topic:: Exercise +.. topic:: Ejercicio - Write a program to search your ``PYTHONPATH`` for the module ``site.py``. + Escriba un programa para buscar su ``PYTHONPATH`` para el módulo ``site.py`` . :ref:`path_site` diff --git a/intro/matplotlib/auto_examples/images/plot_aliased_1.png b/intro/matplotlib/auto_examples/images/plot_aliased_1.png new file mode 100644 index 0000000..a38d9d6 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_aliased_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_alpha_1.png b/intro/matplotlib/auto_examples/images/plot_alpha_1.png new file mode 100644 index 0000000..cc2e414 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_alpha_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_antialiased_1.png b/intro/matplotlib/auto_examples/images/plot_antialiased_1.png new file mode 100644 index 0000000..81b8ef6 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_antialiased_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_axes-2_1.png b/intro/matplotlib/auto_examples/images/plot_axes-2_1.png new file mode 100644 index 0000000..c6d8d4c Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_axes-2_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_axes_1.png b/intro/matplotlib/auto_examples/images/plot_axes_1.png new file mode 100644 index 0000000..8866a86 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_axes_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_axes_2_1.png b/intro/matplotlib/auto_examples/images/plot_axes_2_1.png new file mode 100644 index 0000000..63cc2d8 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_axes_2_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_bad_1.png b/intro/matplotlib/auto_examples/images/plot_bad_1.png new file mode 100644 index 0000000..48e1f67 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_bad_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_bar_1.png b/intro/matplotlib/auto_examples/images/plot_bar_1.png new file mode 100644 index 0000000..4f2c152 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_bar_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_bar_ex_1.png b/intro/matplotlib/auto_examples/images/plot_bar_ex_1.png new file mode 100644 index 0000000..7a2ee8e Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_bar_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_boxplot_1.png b/intro/matplotlib/auto_examples/images/plot_boxplot_1.png new file mode 100644 index 0000000..f6bf658 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_boxplot_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_color_1.png b/intro/matplotlib/auto_examples/images/plot_color_1.png new file mode 100644 index 0000000..773af2a Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_color_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_colormaps_1.png b/intro/matplotlib/auto_examples/images/plot_colormaps_1.png new file mode 100644 index 0000000..0e0d58a Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_colormaps_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_contour_1.png b/intro/matplotlib/auto_examples/images/plot_contour_1.png new file mode 100644 index 0000000..1b551bb Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_contour_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_contour_ex_1.png b/intro/matplotlib/auto_examples/images/plot_contour_ex_1.png new file mode 100644 index 0000000..472183f Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_contour_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_dash_capstyle_1.png b/intro/matplotlib/auto_examples/images/plot_dash_capstyle_1.png new file mode 100644 index 0000000..8c8db37 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_dash_capstyle_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_dash_joinstyle_1.png b/intro/matplotlib/auto_examples/images/plot_dash_joinstyle_1.png new file mode 100644 index 0000000..e438833 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_dash_joinstyle_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_10_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_10_1.png new file mode 100644 index 0000000..5db2460 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_10_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_1_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_1_1.png new file mode 100644 index 0000000..18fbd78 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_1_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_2_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_2_1.png new file mode 100644 index 0000000..18fbd78 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_2_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_3_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_3_1.png new file mode 100644 index 0000000..8ef9e33 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_3_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_4_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_4_1.png new file mode 100644 index 0000000..9634058 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_4_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_5_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_5_1.png new file mode 100644 index 0000000..3287393 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_5_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_6_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_6_1.png new file mode 100644 index 0000000..7e09390 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_6_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_7_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_7_1.png new file mode 100644 index 0000000..a406704 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_7_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_8_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_8_1.png new file mode 100644 index 0000000..44a60a6 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_8_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_exercice_9_1.png b/intro/matplotlib/auto_examples/images/plot_exercice_9_1.png new file mode 100644 index 0000000..28e5f9b Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_exercice_9_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_good_1.png b/intro/matplotlib/auto_examples/images/plot_good_1.png new file mode 100644 index 0000000..6c21c54 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_good_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_grid_1.png b/intro/matplotlib/auto_examples/images/plot_grid_1.png new file mode 100644 index 0000000..1785253 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_grid_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_grid_ex_1.png b/intro/matplotlib/auto_examples/images/plot_grid_ex_1.png new file mode 100644 index 0000000..2e548fb Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_grid_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_gridspec_1.png b/intro/matplotlib/auto_examples/images/plot_gridspec_1.png new file mode 100644 index 0000000..5ce4bee Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_gridspec_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_imshow_1.png b/intro/matplotlib/auto_examples/images/plot_imshow_1.png new file mode 100644 index 0000000..2e6bf2b Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_imshow_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_imshow_ex_1.png b/intro/matplotlib/auto_examples/images/plot_imshow_ex_1.png new file mode 100644 index 0000000..61067b9 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_imshow_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_linestyles_1.png b/intro/matplotlib/auto_examples/images/plot_linestyles_1.png new file mode 100644 index 0000000..e865f1f Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_linestyles_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_linewidth_1.png b/intro/matplotlib/auto_examples/images/plot_linewidth_1.png new file mode 100644 index 0000000..dd06f26 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_linewidth_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_mec_1.png b/intro/matplotlib/auto_examples/images/plot_mec_1.png new file mode 100644 index 0000000..a147575 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_mec_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_mew_1.png b/intro/matplotlib/auto_examples/images/plot_mew_1.png new file mode 100644 index 0000000..0429504 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_mew_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_mfc_1.png b/intro/matplotlib/auto_examples/images/plot_mfc_1.png new file mode 100644 index 0000000..eec1802 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_mfc_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_ms_1.png b/intro/matplotlib/auto_examples/images/plot_ms_1.png new file mode 100644 index 0000000..983e500 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_ms_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_multiplot_1.png b/intro/matplotlib/auto_examples/images/plot_multiplot_1.png new file mode 100644 index 0000000..04be523 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_multiplot_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_multiplot_ex_1.png b/intro/matplotlib/auto_examples/images/plot_multiplot_ex_1.png new file mode 100644 index 0000000..3f7574c Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_multiplot_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_pie_1.png b/intro/matplotlib/auto_examples/images/plot_pie_1.png new file mode 100644 index 0000000..e31d9fa Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_pie_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_pie_ex_1.png b/intro/matplotlib/auto_examples/images/plot_pie_ex_1.png new file mode 100644 index 0000000..9b5aa6b Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_pie_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_plot3d-2_1.png b/intro/matplotlib/auto_examples/images/plot_plot3d-2_1.png new file mode 100644 index 0000000..4a8001c Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_plot3d-2_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_plot3d_1.png b/intro/matplotlib/auto_examples/images/plot_plot3d_1.png new file mode 100644 index 0000000..63301e0 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_plot3d_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_plot3d_2_1.png b/intro/matplotlib/auto_examples/images/plot_plot3d_2_1.png new file mode 100644 index 0000000..535a36b Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_plot3d_2_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_plot3d_ex_1.png b/intro/matplotlib/auto_examples/images/plot_plot3d_ex_1.png new file mode 100644 index 0000000..8f2e9ed Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_plot3d_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_plot_1.png b/intro/matplotlib/auto_examples/images/plot_plot_1.png new file mode 100644 index 0000000..51fc9de Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_plot_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_plot_ex_1.png b/intro/matplotlib/auto_examples/images/plot_plot_ex_1.png new file mode 100644 index 0000000..df72179 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_plot_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_polar_1.png b/intro/matplotlib/auto_examples/images/plot_polar_1.png new file mode 100644 index 0000000..8f99781 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_polar_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_polar_ex_1.png b/intro/matplotlib/auto_examples/images/plot_polar_ex_1.png new file mode 100644 index 0000000..f5cb0d8 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_polar_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_quiver_1.png b/intro/matplotlib/auto_examples/images/plot_quiver_1.png new file mode 100644 index 0000000..4c741ad Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_quiver_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_quiver_ex_1.png b/intro/matplotlib/auto_examples/images/plot_quiver_ex_1.png new file mode 100644 index 0000000..8948bb3 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_quiver_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_scatter_1.png b/intro/matplotlib/auto_examples/images/plot_scatter_1.png new file mode 100644 index 0000000..63de245 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_scatter_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_scatter_ex_1.png b/intro/matplotlib/auto_examples/images/plot_scatter_ex_1.png new file mode 100644 index 0000000..02842b7 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_scatter_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_solid_capstyle_1.png b/intro/matplotlib/auto_examples/images/plot_solid_capstyle_1.png new file mode 100644 index 0000000..eacd763 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_solid_capstyle_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_solid_joinstyle_1.png b/intro/matplotlib/auto_examples/images/plot_solid_joinstyle_1.png new file mode 100644 index 0000000..a25b6ce Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_solid_joinstyle_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_subplot-grid_1.png b/intro/matplotlib/auto_examples/images/plot_subplot-grid_1.png new file mode 100644 index 0000000..b88a52a Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_subplot-grid_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_subplot-horizontal_1.png b/intro/matplotlib/auto_examples/images/plot_subplot-horizontal_1.png new file mode 100644 index 0000000..43d1fe4 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_subplot-horizontal_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_subplot-vertical_1.png b/intro/matplotlib/auto_examples/images/plot_subplot-vertical_1.png new file mode 100644 index 0000000..01b6836 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_subplot-vertical_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_subplot_grid_1.png b/intro/matplotlib/auto_examples/images/plot_subplot_grid_1.png new file mode 100644 index 0000000..f22f6d6 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_subplot_grid_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_subplot_horizontal_1.png b/intro/matplotlib/auto_examples/images/plot_subplot_horizontal_1.png new file mode 100644 index 0000000..0bdfd63 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_subplot_horizontal_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_subplot_vertical_1.png b/intro/matplotlib/auto_examples/images/plot_subplot_vertical_1.png new file mode 100644 index 0000000..89b3113 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_subplot_vertical_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_text_1.png b/intro/matplotlib/auto_examples/images/plot_text_1.png new file mode 100644 index 0000000..8b7ceca Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_text_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_text_ex_1.png b/intro/matplotlib/auto_examples/images/plot_text_ex_1.png new file mode 100644 index 0000000..31b445b Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_text_ex_1.png differ diff --git a/intro/matplotlib/auto_examples/images/plot_ugly_1.png b/intro/matplotlib/auto_examples/images/plot_ugly_1.png new file mode 100644 index 0000000..084cc8f Binary files /dev/null and b/intro/matplotlib/auto_examples/images/plot_ugly_1.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_aliased.png b/intro/matplotlib/auto_examples/images/thumb/plot_aliased.png new file mode 100644 index 0000000..5c886c7 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_aliased.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_alpha.png b/intro/matplotlib/auto_examples/images/thumb/plot_alpha.png new file mode 100644 index 0000000..ed55ec5 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_alpha.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_antialiased.png b/intro/matplotlib/auto_examples/images/thumb/plot_antialiased.png new file mode 100644 index 0000000..1f46085 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_antialiased.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_axes-2.png b/intro/matplotlib/auto_examples/images/thumb/plot_axes-2.png new file mode 100644 index 0000000..6352f53 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_axes-2.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_axes.png b/intro/matplotlib/auto_examples/images/thumb/plot_axes.png new file mode 100644 index 0000000..0e5bbf5 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_axes.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_axes_2.png b/intro/matplotlib/auto_examples/images/thumb/plot_axes_2.png new file mode 100644 index 0000000..2e0b945 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_axes_2.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_bad.png b/intro/matplotlib/auto_examples/images/thumb/plot_bad.png new file mode 100644 index 0000000..ab74493 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_bad.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_bar.png b/intro/matplotlib/auto_examples/images/thumb/plot_bar.png new file mode 100644 index 0000000..2243f8e Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_bar.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_bar_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_bar_ex.png new file mode 100644 index 0000000..9fd0141 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_bar_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_boxplot.png b/intro/matplotlib/auto_examples/images/thumb/plot_boxplot.png new file mode 100644 index 0000000..477668e Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_boxplot.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_color.png b/intro/matplotlib/auto_examples/images/thumb/plot_color.png new file mode 100644 index 0000000..e67bf32 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_color.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_colormaps.png b/intro/matplotlib/auto_examples/images/thumb/plot_colormaps.png new file mode 100644 index 0000000..181c2c9 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_colormaps.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_contour.png b/intro/matplotlib/auto_examples/images/thumb/plot_contour.png new file mode 100644 index 0000000..a495094 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_contour.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_contour_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_contour_ex.png new file mode 100644 index 0000000..9037cf1 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_contour_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_dash_capstyle.png b/intro/matplotlib/auto_examples/images/thumb/plot_dash_capstyle.png new file mode 100644 index 0000000..2b2f412 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_dash_capstyle.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_dash_joinstyle.png b/intro/matplotlib/auto_examples/images/thumb/plot_dash_joinstyle.png new file mode 100644 index 0000000..cbf1aef Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_dash_joinstyle.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_1.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_1.png new file mode 100644 index 0000000..0a01354 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_1.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_10.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_10.png new file mode 100644 index 0000000..17a3338 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_10.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_2.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_2.png new file mode 100644 index 0000000..0a01354 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_2.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_3.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_3.png new file mode 100644 index 0000000..a2a1468 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_3.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_4.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_4.png new file mode 100644 index 0000000..63d98fc Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_4.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_5.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_5.png new file mode 100644 index 0000000..4f3b7e2 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_5.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_6.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_6.png new file mode 100644 index 0000000..8d99bc1 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_6.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_7.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_7.png new file mode 100644 index 0000000..6653e83 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_7.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_8.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_8.png new file mode 100644 index 0000000..e07206d Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_8.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_exercice_9.png b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_9.png new file mode 100644 index 0000000..41ce62b Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_exercice_9.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_good.png b/intro/matplotlib/auto_examples/images/thumb/plot_good.png new file mode 100644 index 0000000..fb99536 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_good.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_grid.png b/intro/matplotlib/auto_examples/images/thumb/plot_grid.png new file mode 100644 index 0000000..52c231f Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_grid.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_grid_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_grid_ex.png new file mode 100644 index 0000000..8789c1d Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_grid_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_gridspec.png b/intro/matplotlib/auto_examples/images/thumb/plot_gridspec.png new file mode 100644 index 0000000..be9e085 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_gridspec.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_imshow.png b/intro/matplotlib/auto_examples/images/thumb/plot_imshow.png new file mode 100644 index 0000000..c5bd000 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_imshow.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_imshow_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_imshow_ex.png new file mode 100644 index 0000000..1a1ac00 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_imshow_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_linestyles.png b/intro/matplotlib/auto_examples/images/thumb/plot_linestyles.png new file mode 100644 index 0000000..6ec3b6a Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_linestyles.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_linewidth.png b/intro/matplotlib/auto_examples/images/thumb/plot_linewidth.png new file mode 100644 index 0000000..4379431 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_linewidth.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_markers.png b/intro/matplotlib/auto_examples/images/thumb/plot_markers.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_markers.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_mec.png b/intro/matplotlib/auto_examples/images/thumb/plot_mec.png new file mode 100644 index 0000000..a017831 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_mec.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_mew.png b/intro/matplotlib/auto_examples/images/thumb/plot_mew.png new file mode 100644 index 0000000..913a951 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_mew.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_mfc.png b/intro/matplotlib/auto_examples/images/thumb/plot_mfc.png new file mode 100644 index 0000000..543d057 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_mfc.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_ms.png b/intro/matplotlib/auto_examples/images/thumb/plot_ms.png new file mode 100644 index 0000000..ae78d56 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_ms.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_multiplot.png b/intro/matplotlib/auto_examples/images/thumb/plot_multiplot.png new file mode 100644 index 0000000..ee9a14b Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_multiplot.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_multiplot_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_multiplot_ex.png new file mode 100644 index 0000000..36677ad Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_multiplot_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_pie.png b/intro/matplotlib/auto_examples/images/thumb/plot_pie.png new file mode 100644 index 0000000..1d93a27 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_pie.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_pie_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_pie_ex.png new file mode 100644 index 0000000..df4a0a8 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_pie_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_plot.png b/intro/matplotlib/auto_examples/images/thumb/plot_plot.png new file mode 100644 index 0000000..197da4f Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_plot.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_plot3d-2.png b/intro/matplotlib/auto_examples/images/thumb/plot_plot3d-2.png new file mode 100644 index 0000000..22885a6 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_plot3d-2.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_plot3d.png b/intro/matplotlib/auto_examples/images/thumb/plot_plot3d.png new file mode 100644 index 0000000..4d3781c Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_plot3d.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_plot3d_2.png b/intro/matplotlib/auto_examples/images/thumb/plot_plot3d_2.png new file mode 100644 index 0000000..0e3fbab Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_plot3d_2.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_plot3d_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_plot3d_ex.png new file mode 100644 index 0000000..570fcb1 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_plot3d_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_plot_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_plot_ex.png new file mode 100644 index 0000000..1732a17 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_plot_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_polar.png b/intro/matplotlib/auto_examples/images/thumb/plot_polar.png new file mode 100644 index 0000000..49cce0b Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_polar.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_polar_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_polar_ex.png new file mode 100644 index 0000000..bd8c2f8 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_polar_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_quiver.png b/intro/matplotlib/auto_examples/images/thumb/plot_quiver.png new file mode 100644 index 0000000..6dc3782 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_quiver.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_quiver_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_quiver_ex.png new file mode 100644 index 0000000..5347a2f Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_quiver_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_scatter.png b/intro/matplotlib/auto_examples/images/thumb/plot_scatter.png new file mode 100644 index 0000000..15488bf Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_scatter.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_scatter_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_scatter_ex.png new file mode 100644 index 0000000..edac85e Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_scatter_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_solid_capstyle.png b/intro/matplotlib/auto_examples/images/thumb/plot_solid_capstyle.png new file mode 100644 index 0000000..6288345 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_solid_capstyle.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_solid_joinstyle.png b/intro/matplotlib/auto_examples/images/thumb/plot_solid_joinstyle.png new file mode 100644 index 0000000..dac31cb Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_solid_joinstyle.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_subplot-grid.png b/intro/matplotlib/auto_examples/images/thumb/plot_subplot-grid.png new file mode 100644 index 0000000..a249fe4 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_subplot-grid.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_subplot-horizontal.png b/intro/matplotlib/auto_examples/images/thumb/plot_subplot-horizontal.png new file mode 100644 index 0000000..86f8810 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_subplot-horizontal.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_subplot-vertical.png b/intro/matplotlib/auto_examples/images/thumb/plot_subplot-vertical.png new file mode 100644 index 0000000..9724dd4 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_subplot-vertical.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_subplot_grid.png b/intro/matplotlib/auto_examples/images/thumb/plot_subplot_grid.png new file mode 100644 index 0000000..c3d15f5 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_subplot_grid.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_subplot_horizontal.png b/intro/matplotlib/auto_examples/images/thumb/plot_subplot_horizontal.png new file mode 100644 index 0000000..d661846 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_subplot_horizontal.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_subplot_vertical.png b/intro/matplotlib/auto_examples/images/thumb/plot_subplot_vertical.png new file mode 100644 index 0000000..029f488 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_subplot_vertical.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_text.png b/intro/matplotlib/auto_examples/images/thumb/plot_text.png new file mode 100644 index 0000000..aa6b976 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_text.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_text_ex.png b/intro/matplotlib/auto_examples/images/thumb/plot_text_ex.png new file mode 100644 index 0000000..2158668 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_text_ex.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_ticks.png b/intro/matplotlib/auto_examples/images/thumb/plot_ticks.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_ticks.png differ diff --git a/intro/matplotlib/auto_examples/images/thumb/plot_ugly.png b/intro/matplotlib/auto_examples/images/thumb/plot_ugly.png new file mode 100644 index 0000000..14c8e2e Binary files /dev/null and b/intro/matplotlib/auto_examples/images/thumb/plot_ugly.png differ diff --git a/intro/matplotlib/auto_examples/index.rst b/intro/matplotlib/auto_examples/index.rst new file mode 100644 index 0000000..31c242c --- /dev/null +++ b/intro/matplotlib/auto_examples/index.rst @@ -0,0 +1,341 @@ + +.. raw:: html + + + +Examples +======== + +.. _examples-index: +.. figure:: ./images/thumb/plot_aliased.png + :target: ./plot_aliased.html + + :ref:`example_plot_aliased.py` + +.. figure:: ./images/thumb/plot_alpha.png + :target: ./plot_alpha.html + + :ref:`example_plot_alpha.py` + +.. figure:: ./images/thumb/plot_antialiased.png + :target: ./plot_antialiased.html + + :ref:`example_plot_antialiased.py` + +.. figure:: ./images/thumb/plot_axes.png + :target: ./plot_axes.html + + :ref:`example_plot_axes.py` + +.. figure:: ./images/thumb/plot_axes_2.png + :target: ./plot_axes_2.html + + :ref:`example_plot_axes_2.py` + +.. figure:: ./images/thumb/plot_bad.png + :target: ./plot_bad.html + + :ref:`example_plot_bad.py` + +.. figure:: ./images/thumb/plot_bar.png + :target: ./plot_bar.html + + :ref:`example_plot_bar.py` + +.. figure:: ./images/thumb/plot_bar_ex.png + :target: ./plot_bar_ex.html + + :ref:`example_plot_bar_ex.py` + +.. figure:: ./images/thumb/plot_boxplot.png + :target: ./plot_boxplot.html + + :ref:`example_plot_boxplot.py` + +.. figure:: ./images/thumb/plot_color.png + :target: ./plot_color.html + + :ref:`example_plot_color.py` + +.. figure:: ./images/thumb/plot_colormaps.png + :target: ./plot_colormaps.html + + :ref:`example_plot_colormaps.py` + +.. figure:: ./images/thumb/plot_contour.png + :target: ./plot_contour.html + + :ref:`example_plot_contour.py` + +.. figure:: ./images/thumb/plot_contour_ex.png + :target: ./plot_contour_ex.html + + :ref:`example_plot_contour_ex.py` + +.. figure:: ./images/thumb/plot_dash_capstyle.png + :target: ./plot_dash_capstyle.html + + :ref:`example_plot_dash_capstyle.py` + +.. figure:: ./images/thumb/plot_dash_joinstyle.png + :target: ./plot_dash_joinstyle.html + + :ref:`example_plot_dash_joinstyle.py` + +.. figure:: ./images/thumb/plot_exercice_1.png + :target: ./plot_exercice_1.html + + :ref:`example_plot_exercice_1.py` + +.. figure:: ./images/thumb/plot_exercice_10.png + :target: ./plot_exercice_10.html + + :ref:`example_plot_exercice_10.py` + +.. figure:: ./images/thumb/plot_exercice_2.png + :target: ./plot_exercice_2.html + + :ref:`example_plot_exercice_2.py` + +.. figure:: ./images/thumb/plot_exercice_3.png + :target: ./plot_exercice_3.html + + :ref:`example_plot_exercice_3.py` + +.. figure:: ./images/thumb/plot_exercice_4.png + :target: ./plot_exercice_4.html + + :ref:`example_plot_exercice_4.py` + +.. figure:: ./images/thumb/plot_exercice_5.png + :target: ./plot_exercice_5.html + + :ref:`example_plot_exercice_5.py` + +.. figure:: ./images/thumb/plot_exercice_6.png + :target: ./plot_exercice_6.html + + :ref:`example_plot_exercice_6.py` + +.. figure:: ./images/thumb/plot_exercice_7.png + :target: ./plot_exercice_7.html + + :ref:`example_plot_exercice_7.py` + +.. figure:: ./images/thumb/plot_exercice_8.png + :target: ./plot_exercice_8.html + + :ref:`example_plot_exercice_8.py` + +.. figure:: ./images/thumb/plot_exercice_9.png + :target: ./plot_exercice_9.html + + :ref:`example_plot_exercice_9.py` + +.. figure:: ./images/thumb/plot_good.png + :target: ./plot_good.html + + :ref:`example_plot_good.py` + +.. figure:: ./images/thumb/plot_grid.png + :target: ./plot_grid.html + + :ref:`example_plot_grid.py` + +.. figure:: ./images/thumb/plot_grid_ex.png + :target: ./plot_grid_ex.html + + :ref:`example_plot_grid_ex.py` + +.. figure:: ./images/thumb/plot_gridspec.png + :target: ./plot_gridspec.html + + :ref:`example_plot_gridspec.py` + +.. figure:: ./images/thumb/plot_imshow.png + :target: ./plot_imshow.html + + :ref:`example_plot_imshow.py` + +.. figure:: ./images/thumb/plot_imshow_ex.png + :target: ./plot_imshow_ex.html + + :ref:`example_plot_imshow_ex.py` + +.. figure:: ./images/thumb/plot_linestyles.png + :target: ./plot_linestyles.html + + :ref:`example_plot_linestyles.py` + +.. figure:: ./images/thumb/plot_linewidth.png + :target: ./plot_linewidth.html + + :ref:`example_plot_linewidth.py` + +.. figure:: ./images/thumb/plot_markers.png + :target: ./plot_markers.html + + :ref:`example_plot_markers.py` + +.. figure:: ./images/thumb/plot_mec.png + :target: ./plot_mec.html + + :ref:`example_plot_mec.py` + +.. figure:: ./images/thumb/plot_mew.png + :target: ./plot_mew.html + + :ref:`example_plot_mew.py` + +.. figure:: ./images/thumb/plot_mfc.png + :target: ./plot_mfc.html + + :ref:`example_plot_mfc.py` + +.. figure:: ./images/thumb/plot_ms.png + :target: ./plot_ms.html + + :ref:`example_plot_ms.py` + +.. figure:: ./images/thumb/plot_multiplot.png + :target: ./plot_multiplot.html + + :ref:`example_plot_multiplot.py` + +.. figure:: ./images/thumb/plot_multiplot_ex.png + :target: ./plot_multiplot_ex.html + + :ref:`example_plot_multiplot_ex.py` + +.. figure:: ./images/thumb/plot_pie.png + :target: ./plot_pie.html + + :ref:`example_plot_pie.py` + +.. figure:: ./images/thumb/plot_pie_ex.png + :target: ./plot_pie_ex.html + + :ref:`example_plot_pie_ex.py` + +.. figure:: ./images/thumb/plot_plot.png + :target: ./plot_plot.html + + :ref:`example_plot_plot.py` + +.. figure:: ./images/thumb/plot_plot3d.png + :target: ./plot_plot3d.html + + :ref:`example_plot_plot3d.py` + +.. figure:: ./images/thumb/plot_plot3d_2.png + :target: ./plot_plot3d_2.html + + :ref:`example_plot_plot3d_2.py` + +.. figure:: ./images/thumb/plot_plot3d_ex.png + :target: ./plot_plot3d_ex.html + + :ref:`example_plot_plot3d_ex.py` + +.. figure:: ./images/thumb/plot_plot_ex.png + :target: ./plot_plot_ex.html + + :ref:`example_plot_plot_ex.py` + +.. figure:: ./images/thumb/plot_polar.png + :target: ./plot_polar.html + + :ref:`example_plot_polar.py` + +.. figure:: ./images/thumb/plot_polar_ex.png + :target: ./plot_polar_ex.html + + :ref:`example_plot_polar_ex.py` + +.. figure:: ./images/thumb/plot_quiver.png + :target: ./plot_quiver.html + + :ref:`example_plot_quiver.py` + +.. figure:: ./images/thumb/plot_quiver_ex.png + :target: ./plot_quiver_ex.html + + :ref:`example_plot_quiver_ex.py` + +.. figure:: ./images/thumb/plot_scatter.png + :target: ./plot_scatter.html + + :ref:`example_plot_scatter.py` + +.. figure:: ./images/thumb/plot_scatter_ex.png + :target: ./plot_scatter_ex.html + + :ref:`example_plot_scatter_ex.py` + +.. figure:: ./images/thumb/plot_solid_capstyle.png + :target: ./plot_solid_capstyle.html + + :ref:`example_plot_solid_capstyle.py` + +.. figure:: ./images/thumb/plot_solid_joinstyle.png + :target: ./plot_solid_joinstyle.html + + :ref:`example_plot_solid_joinstyle.py` + +.. figure:: ./images/thumb/plot_subplot_grid.png + :target: ./plot_subplot_grid.html + + :ref:`example_plot_subplot_grid.py` + +.. figure:: ./images/thumb/plot_subplot_horizontal.png + :target: ./plot_subplot_horizontal.html + + :ref:`example_plot_subplot_horizontal.py` + +.. figure:: ./images/thumb/plot_subplot_vertical.png + :target: ./plot_subplot_vertical.html + + :ref:`example_plot_subplot_vertical.py` + +.. figure:: ./images/thumb/plot_text.png + :target: ./plot_text.html + + :ref:`example_plot_text.py` + +.. figure:: ./images/thumb/plot_text_ex.png + :target: ./plot_text_ex.html + + :ref:`example_plot_text_ex.py` + +.. figure:: ./images/thumb/plot_ticks.png + :target: ./plot_ticks.html + + :ref:`example_plot_ticks.py` + +.. figure:: ./images/thumb/plot_ugly.png + :target: ./plot_ugly.html + + :ref:`example_plot_ugly.py` + + +.. raw:: html + +
    + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_aliased.py b/intro/matplotlib/auto_examples/plot_aliased.py new file mode 100644 index 0000000..161d42f --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_aliased.py @@ -0,0 +1,19 @@ +import pylab as pl + +size = 128, 16 +dpi = 72.0 +figsize= size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) + +pl.axes([0, 0, 1, 1], frameon=False) + +pl.rcParams['text.antialiased'] = False +pl.text(0.5, 0.5, "Aliased", ha='center', va='center') + +pl.xlim(0, 1) +pl.ylim(0, 1) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_aliased.rst b/intro/matplotlib/auto_examples/plot_aliased.rst new file mode 100644 index 0000000..0ea0d23 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_aliased.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_aliased.py: + + + + +.. image:: images/plot_aliased_1.png + :align: center + + +**Python source code:** :download:`plot_aliased.py ` + +.. literalinclude:: plot_aliased.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_alpha.py b/intro/matplotlib/auto_examples/plot_alpha.py new file mode 100644 index 0000000..b882b30 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_alpha.py @@ -0,0 +1,16 @@ +import pylab as pl + +size = 256,16 +dpi = 72.0 +figsize= size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0.1, 1, .8], frameon=False) + +for i in range(1, 11): + pl.axvline(i, linewidth=1, color='blue', alpha= .25 + .75 * i / 10.) + +pl.xlim(0, 11) +pl.xticks(()) +pl.yticks(()) +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_alpha.rst b/intro/matplotlib/auto_examples/plot_alpha.rst new file mode 100644 index 0000000..2bf579d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_alpha.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_alpha.py: + + + + +.. image:: images/plot_alpha_1.png + :align: center + + +**Python source code:** :download:`plot_alpha.py ` + +.. literalinclude:: plot_alpha.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_antialiased.py b/intro/matplotlib/auto_examples/plot_antialiased.py new file mode 100644 index 0000000..5fcb59f --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_antialiased.py @@ -0,0 +1,18 @@ +import pylab as pl + +size = 128, 16 +dpi = 72.0 +figsize= size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0, 1, 1], frameon=False) + +pl.rcParams['text.antialiased'] = True +pl.text(0.5, 0.5, "Anti-aliased", ha='center', va='center') + +pl.xlim(0, 1) +pl.ylim(0, 1) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_antialiased.rst b/intro/matplotlib/auto_examples/plot_antialiased.rst new file mode 100644 index 0000000..1b29f51 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_antialiased.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_antialiased.py: + + + + +.. image:: images/plot_antialiased_1.png + :align: center + + +**Python source code:** :download:`plot_antialiased.py ` + +.. literalinclude:: plot_antialiased.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/examples/plot_axes-2.py b/intro/matplotlib/auto_examples/plot_axes-2.py similarity index 100% rename from intro/matplotlib/examples/plot_axes-2.py rename to intro/matplotlib/auto_examples/plot_axes-2.py diff --git a/intro/matplotlib/auto_examples/plot_axes-2.rst b/intro/matplotlib/auto_examples/plot_axes-2.rst new file mode 100644 index 0000000..122833d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_axes-2.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_axes-2.py: + + + + +.. image:: images/plot_axes-2_1.png + :align: center + + +**Python source code:** :download:`plot_axes-2.py ` + +.. literalinclude:: plot_axes-2.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_axes.py b/intro/matplotlib/auto_examples/plot_axes.py new file mode 100644 index 0000000..f31eca7 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_axes.py @@ -0,0 +1,15 @@ +import pylab as pl + +pl.axes([.1, .1, .8, .8]) +pl.xticks(()) +pl.yticks(()) +pl.text(.6, .6, 'axes([0.1,0.1,.8,.8])', ha='center', va='center', + size=20, alpha=.5) + +pl.axes([.2, .2, .3, .3]) +pl.xticks(()) +pl.yticks(()) +pl.text(.5, .5, 'axes([0.2,0.2,.3,.3])', ha='center', va='center', + size=16, alpha=.5) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_axes.rst b/intro/matplotlib/auto_examples/plot_axes.rst new file mode 100644 index 0000000..c2fc03e --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_axes.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_axes.py: + + + + +.. image:: images/plot_axes_1.png + :align: center + + +**Python source code:** :download:`plot_axes.py ` + +.. literalinclude:: plot_axes.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_axes_2.py b/intro/matplotlib/auto_examples/plot_axes_2.py new file mode 100644 index 0000000..13505f6 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_axes_2.py @@ -0,0 +1,27 @@ +import pylab as pl + +pl.axes([.1, .1, .5, .5]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.1, 0.1, 'axes([0.1,0.1,.8,.8])', ha='left', va='center', + size=16, alpha=.5) + +pl.axes([.2, .2, .5, .5]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.1, 0.1, 'axes([0.2,0.2,.5,.5])', ha='left', va='center', + size=16, alpha=.5) + +pl.axes([0.3, 0.3, .5, .5]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.1, 0.1, 'axes([0.3,0.3,.5,.5])', ha='left', va='center', + size=16, alpha=.5) + +pl.axes([.4, .4, .5, .5]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.1, 0.1, 'axes([0.4,0.4,.5,.5])', ha='left', va='center', + size=16, alpha=.5) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_axes_2.rst b/intro/matplotlib/auto_examples/plot_axes_2.rst new file mode 100644 index 0000000..f249cee --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_axes_2.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_axes_2.py: + + + + +.. image:: images/plot_axes_2_1.png + :align: center + + +**Python source code:** :download:`plot_axes_2.py ` + +.. literalinclude:: plot_axes_2.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_bad.py b/intro/matplotlib/auto_examples/plot_bad.py new file mode 100644 index 0000000..7c6e9af --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_bad.py @@ -0,0 +1,14 @@ +import numpy as np +import matplotlib +matplotlib.use('Agg') +import pylab as pl + +fig = pl.figure(figsize=(5, 4), dpi=72) +axes = fig.add_axes([0.01, 0.01, .98, 0.98]) +X = np.linspace(0, 2, 200, endpoint=True) +Y = np.sin(2 * np.pi * X) +pl.plot(X, Y, lw=.25, c='k') +pl.xticks(np.arange(0.0, 2.0, 0.1)) +pl.yticks(np.arange(-1.0, 1.0, 0.1)) +pl.grid() +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_bad.rst b/intro/matplotlib/auto_examples/plot_bad.rst new file mode 100644 index 0000000..35b5cb7 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_bad.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_bad.py: + + + + +.. image:: images/plot_bad_1.png + :align: center + + +**Python source code:** :download:`plot_bad.py ` + +.. literalinclude:: plot_bad.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_bar.py b/intro/matplotlib/auto_examples/plot_bar.py new file mode 100644 index 0000000..b7f4420 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_bar.py @@ -0,0 +1,28 @@ +import pylab as pl +import numpy as np + +n = 16 +X = np.arange(n) +Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) +Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) +pl.bar(X, Y1, facecolor='#9999ff', edgecolor='white') +pl.bar(X, -Y2, facecolor='#ff9999', edgecolor='white') +pl.xlim(-.5, n) +pl.xticks(()) +pl.ylim(-1, 1) +pl.yticks(()) + +pl.text(-0.05, 1.02, " Bar Plot: pl.bar(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) + +pl.text(-0.05, 1.01, "\n\n Make a bar plot with rectangles ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_bar.rst b/intro/matplotlib/auto_examples/plot_bar.rst new file mode 100644 index 0000000..4baf286 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_bar.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_bar.py: + + + + +.. image:: images/plot_bar_1.png + :align: center + + +**Python source code:** :download:`plot_bar.py ` + +.. literalinclude:: plot_bar.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_bar_ex.py b/intro/matplotlib/auto_examples/plot_bar_ex.py new file mode 100644 index 0000000..76b8baa --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_bar_ex.py @@ -0,0 +1,24 @@ +import pylab as pl +import numpy as np + +n = 12 +X = np.arange(n) +Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) +Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n) + +pl.axes([0.025, 0.025, 0.95, 0.95]) +pl.bar(X, +Y1, facecolor='#9999ff', edgecolor='white') +pl.bar(X, -Y2, facecolor='#ff9999', edgecolor='white') + +for x, y in zip(X, Y1): + pl.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va= 'bottom') + +for x, y in zip(X, Y2): + pl.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va= 'top') + +pl.xlim(-.5, n) +pl.xticks(()) +pl.ylim(-1.25, 1.25) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_bar_ex.rst b/intro/matplotlib/auto_examples/plot_bar_ex.rst new file mode 100644 index 0000000..ad55b6f --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_bar_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_bar_ex.py: + + + + +.. image:: images/plot_bar_ex_1.png + :align: center + + +**Python source code:** :download:`plot_bar_ex.py ` + +.. literalinclude:: plot_bar_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_boxplot.py b/intro/matplotlib/auto_examples/plot_boxplot.py new file mode 100644 index 0000000..a1172ae --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_boxplot.py @@ -0,0 +1,31 @@ +import numpy as np +import matplotlib +matplotlib.use('Agg') +import pylab as pl + +fig = pl.figure(figsize=(8, 5), dpi=72) +fig.patch.set_alpha(0.0) +axes = pl.subplot(111) + +n = 5 +Z = np.zeros((n, 4)) +X = np.linspace(0, 2, n, endpoint=True) +Y = np.random.random((n, 4)) +pl.boxplot(Y) + +pl.xticks(()), pl.yticks(()) + +pl.text(-0.05, 1.02, " Box Plot: pl.boxplot(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=axes.transAxes) + +pl.text(-0.05, 1.01, " Make a box and whisker plot ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=axes.transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_boxplot.rst b/intro/matplotlib/auto_examples/plot_boxplot.rst new file mode 100644 index 0000000..601ac84 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_boxplot.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_boxplot.py: + + + + +.. image:: images/plot_boxplot_1.png + :align: center + + +**Python source code:** :download:`plot_boxplot.py ` + +.. literalinclude:: plot_boxplot.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_color.py b/intro/matplotlib/auto_examples/plot_color.py new file mode 100644 index 0000000..845aedb --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_color.py @@ -0,0 +1,16 @@ +import pylab as pl + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0.1, 1, .8], frameon=False) + +for i in range(1,11): + pl.plot([i, i], [0, 1], lw=1.5) + +pl.xlim(0, 11) +pl.xticks(()) +pl.yticks(()) +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_color.rst b/intro/matplotlib/auto_examples/plot_color.rst new file mode 100644 index 0000000..3c864a5 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_color.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_color.py: + + + + +.. image:: images/plot_color_1.png + :align: center + + +**Python source code:** :download:`plot_color.py ` + +.. literalinclude:: plot_color.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_colormaps.py b/intro/matplotlib/auto_examples/plot_colormaps.py new file mode 100644 index 0000000..e93c666 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_colormaps.py @@ -0,0 +1,19 @@ +import pylab as pl +import numpy as np + +pl.rc('text', usetex=False) +a = np.outer(np.arange(0, 1, 0.01), np.ones(10)) + +pl.figure(figsize=(10, 5)) +pl.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99) +maps = [m for m in pl.cm.datad if not m.endswith("_r")] +maps.sort() +l = len(maps) + 1 + +for i, m in enumerate(maps): + pl.subplot(1, l, i+1) + pl.axis("off") + pl.imshow(a, aspect='auto', cmap=pl.get_cmap(m), origin="lower") + pl.title(m, rotation=90, fontsize=10, va='bottom') + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_colormaps.rst b/intro/matplotlib/auto_examples/plot_colormaps.rst new file mode 100644 index 0000000..c8e8e1d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_colormaps.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_colormaps.py: + + + + +.. image:: images/plot_colormaps_1.png + :align: center + + +**Python source code:** :download:`plot_colormaps.py ` + +.. literalinclude:: plot_colormaps.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_contour.py b/intro/matplotlib/auto_examples/plot_contour.py new file mode 100644 index 0000000..bf1ace8 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_contour.py @@ -0,0 +1,31 @@ +import pylab as pl +import numpy as np + +def f(x,y): + return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) + +n = 256 +x = np.linspace(-3, 3, n) +y = np.linspace(-3, 3, n) +X, Y = np.meshgrid(x, y) + +pl.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=pl.cm.hot) +C = pl.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5) +pl.clabel(C, inline=1, fontsize=10) +pl.xticks(()) +pl.yticks(()) + +pl.text(-0.05, 1.02, " Contour Plot: pl.contour(..)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) + +pl.text(-0.05, 1.01, "\n\n Draw contour lines and filled contours ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_contour.rst b/intro/matplotlib/auto_examples/plot_contour.rst new file mode 100644 index 0000000..4c66d96 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_contour.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_contour.py: + + + + +.. image:: images/plot_contour_1.png + :align: center + + +**Python source code:** :download:`plot_contour.py ` + +.. literalinclude:: plot_contour.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_contour_ex.py b/intro/matplotlib/auto_examples/plot_contour_ex.py new file mode 100644 index 0000000..cd5339e --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_contour_ex.py @@ -0,0 +1,20 @@ +import pylab as pl +import numpy as np + +def f(x,y): + return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2) + +n = 256 +x = np.linspace(-3, 3, n) +y = np.linspace(-3, 3, n) +X,Y = np.meshgrid(x, y) + +pl.axes([0.025, 0.025, 0.95, 0.95]) + +pl.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=pl.cm.hot) +C = pl.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5) +pl.clabel(C, inline=1, fontsize=10) + +pl.xticks(()) +pl.yticks(()) +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_contour_ex.rst b/intro/matplotlib/auto_examples/plot_contour_ex.rst new file mode 100644 index 0000000..f53c4b0 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_contour_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_contour_ex.py: + + + + +.. image:: images/plot_contour_ex_1.png + :align: center + + +**Python source code:** :download:`plot_contour_ex.py ` + +.. literalinclude:: plot_contour_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_dash_capstyle.py b/intro/matplotlib/auto_examples/plot_dash_capstyle.py new file mode 100644 index 0000000..65fea8a --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_dash_capstyle.py @@ -0,0 +1,24 @@ +import pylab as pl +import numpy as np + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0, 1, 1], frameon=False) + +pl.plot(np.arange(4), np.ones(4), color="blue", dashes=[15, 15], + linewidth=8, dash_capstyle='butt') + +pl.plot(5 + np.arange(4), np.ones(4), color="blue", dashes=[15, 15], + linewidth=8, dash_capstyle='round') + +pl.plot(10 + np.arange(4), np.ones(4), color="blue", dashes=[15, 15], + linewidth=8, dash_capstyle='projecting') + +pl.xlim(0, 14) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_dash_capstyle.rst b/intro/matplotlib/auto_examples/plot_dash_capstyle.rst new file mode 100644 index 0000000..c66bd9a --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_dash_capstyle.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_dash_capstyle.py: + + + + +.. image:: images/plot_dash_capstyle_1.png + :align: center + + +**Python source code:** :download:`plot_dash_capstyle.py ` + +.. literalinclude:: plot_dash_capstyle.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_dash_joinstyle.py b/intro/matplotlib/auto_examples/plot_dash_joinstyle.py new file mode 100644 index 0000000..8d620ea --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_dash_joinstyle.py @@ -0,0 +1,23 @@ +import pylab as pl +import numpy as np + +size = 256, 16 +dpi = 72.0 +figsize= size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0, 1, 1], frameon=False) + +pl.plot(np.arange(3), [0, 1, 0], color="blue", dashes=[12, 5], linewidth=8, + dash_joinstyle='miter') +pl.plot(4 + np.arange(3), [0, 1, 0], color="blue", dashes=[12, 5], + linewidth=8, dash_joinstyle='bevel') +pl.plot(8 + np.arange(3), [0, 1, 0], color="blue", dashes=[12, 5], + linewidth=8, dash_joinstyle='round') + +pl.xlim(0, 12) +pl.ylim(-1, 2) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_dash_joinstyle.rst b/intro/matplotlib/auto_examples/plot_dash_joinstyle.rst new file mode 100644 index 0000000..a766ea0 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_dash_joinstyle.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_dash_joinstyle.py: + + + + +.. image:: images/plot_dash_joinstyle_1.png + :align: center + + +**Python source code:** :download:`plot_dash_joinstyle.py ` + +.. literalinclude:: plot_dash_joinstyle.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_1.py b/intro/matplotlib/auto_examples/plot_exercice_1.py new file mode 100644 index 0000000..3b0eb5f --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_1.py @@ -0,0 +1,10 @@ +import pylab as pl +import numpy as np + +n = 256 +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +C,S = np.cos(X), np.sin(X) +pl.plot(X, C) +pl.plot(X,S) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_1.rst b/intro/matplotlib/auto_examples/plot_exercice_1.rst new file mode 100644 index 0000000..d92b23c --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_1.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_1.py: + + + + +.. image:: images/plot_exercice_1_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_1.py ` + +.. literalinclude:: plot_exercice_1.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_10.py b/intro/matplotlib/auto_examples/plot_exercice_10.py new file mode 100644 index 0000000..3ef5e94 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_10.py @@ -0,0 +1,52 @@ +import pylab as pl +import numpy as np + +pl.figure(figsize=(8, 5), dpi=80) +pl.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +C, S = np.cos(X), np.sin(X) + +pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +pl.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + +ax = pl.gca() +ax.spines['right'].set_color('none') +ax.spines['top'].set_color('none') +ax.xaxis.set_ticks_position('bottom') +ax.spines['bottom'].set_position(('data', 0)) +ax.yaxis.set_ticks_position('left') +ax.spines['left'].set_position(('data', 0)) + +pl.xlim(X.min() * 1.1, X.max() * 1.1) +pl.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], + [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) + +pl.ylim(C.min() * 1.1, C.max() * 1.1) +pl.yticks([-1, 1], + [r'$-1$', r'$+1$']) + +pl.legend(loc='upper left') + +t = 2*np.pi/3 +pl.plot([t, t], [0, np.cos(t)], + color='blue', linewidth=1.5, linestyle="--") +pl.scatter([t, ], [np.cos(t), ], 50, color='blue') +pl.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', + xy=(t, np.sin(t)), xycoords='data', + xytext=(10, 30), textcoords='offset points', fontsize=16, + arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) + +pl.plot([t, t], [0, np.sin(t)], + color='red', linewidth=1.5, linestyle="--") +pl.scatter([t, ], [np.sin(t), ], 50, color ='red') +pl.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), + xycoords='data', xytext=(-90, -50), + textcoords='offset points', fontsize=16, + arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) + +for label in ax.get_xticklabels() + ax.get_yticklabels(): + label.set_fontsize(16) + label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65 )) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_10.rst b/intro/matplotlib/auto_examples/plot_exercice_10.rst new file mode 100644 index 0000000..be98272 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_10.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_10.py: + + + + +.. image:: images/plot_exercice_10_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_10.py ` + +.. literalinclude:: plot_exercice_10.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_2.py b/intro/matplotlib/auto_examples/plot_exercice_2.py new file mode 100644 index 0000000..7963ade --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_2.py @@ -0,0 +1,32 @@ +import pylab as pl +import numpy as np + +# Create a new figure of size 8x6 points, using 100 dots per inch +pl.figure(figsize=(8, 6), dpi=80) + +# Create a new subplot from a grid of 1x1 +pl.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +C, S = np.cos(X), np.sin(X) + +# Plot cosine using blue color with a continuous line of width 1 (pixels) +pl.plot(X, C, color="blue", linewidth=1.0, linestyle="-") + +# Plot sine using green color with a continuous line of width 1 (pixels) +pl.plot(X, S, color="green", linewidth=1.0, linestyle="-") + +# Set x limits +pl.xlim(-4., 4.) + +# Set x ticks +pl.xticks(np.linspace(-4, 4, 9, endpoint=True)) + +# Set y limits +pl.ylim(-1.0, 1.0) + +# Set y ticks +pl.yticks(np.linspace(-1, 1, 5, endpoint=True)) + +# Show result on screen +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_2.rst b/intro/matplotlib/auto_examples/plot_exercice_2.rst new file mode 100644 index 0000000..485d29c --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_2.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_2.py: + + + + +.. image:: images/plot_exercice_2_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_2.py ` + +.. literalinclude:: plot_exercice_2.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_3.py b/intro/matplotlib/auto_examples/plot_exercice_3.py new file mode 100644 index 0000000..ae43cf5 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_3.py @@ -0,0 +1,19 @@ +import pylab as pl +import numpy as np + +pl.figure(figsize=(8, 5), dpi=80) +pl.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +C, S = np.cos(X), np.sin(X) + +pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +pl.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +pl.xlim(-4.0, 4.0) +pl.xticks(np.linspace(-4, 4, 9, endpoint=True)) + +pl.ylim(-1.0, 1.0) +pl.yticks(np.linspace(-1, 1, 5, endpoint=True)) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_3.rst b/intro/matplotlib/auto_examples/plot_exercice_3.rst new file mode 100644 index 0000000..53c3327 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_3.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_3.py: + + + + +.. image:: images/plot_exercice_3_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_3.py ` + +.. literalinclude:: plot_exercice_3.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_4.py b/intro/matplotlib/auto_examples/plot_exercice_4.py new file mode 100644 index 0000000..6e7a62b --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_4.py @@ -0,0 +1,17 @@ +import pylab as pl +import numpy as np + +pl.figure(figsize=(8, 5), dpi=80) +pl.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +S = np.sin(X) +C = np.cos(X) + +pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +pl.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +pl.xlim(X.min() * 1.1, X.max() * 1.1) +pl.ylim(C.min() * 1.1, C.max() * 1.1) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_4.rst b/intro/matplotlib/auto_examples/plot_exercice_4.rst new file mode 100644 index 0000000..538ebc3 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_4.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_4.py: + + + + +.. image:: images/plot_exercice_4_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_4.py ` + +.. literalinclude:: plot_exercice_4.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_5.py b/intro/matplotlib/auto_examples/plot_exercice_5.py new file mode 100644 index 0000000..84d0639 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_5.py @@ -0,0 +1,20 @@ +import pylab as pl +import numpy as np + +pl.figure(figsize=(8, 5), dpi=80) +pl.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +S = np.sin(X) +C = np.cos(X) + +pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +pl.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +pl.xlim(X.min() * 1.1, X.max() * 1.1) +pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) + +pl.ylim(C.min() * 1.1, C.max() * 1.1) +pl.yticks([-1, 0, +1]) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_5.rst b/intro/matplotlib/auto_examples/plot_exercice_5.rst new file mode 100644 index 0000000..c7419a8 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_5.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_5.py: + + + + +.. image:: images/plot_exercice_5_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_5.py ` + +.. literalinclude:: plot_exercice_5.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_6.py b/intro/matplotlib/auto_examples/plot_exercice_6.py new file mode 100644 index 0000000..88b2f85 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_6.py @@ -0,0 +1,22 @@ +import pylab as pl +import numpy as np + +pl.figure(figsize=(8, 5), dpi=80) +pl.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +C = np.cos(X) +S = np.sin(X) + +pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +pl.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +pl.xlim(X.min() * 1.1, X.max() * 1.1) +pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], + [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) + +pl.ylim(C.min() * 1.1, C.max() * 1.1) +pl.yticks([-1, 0, +1], + [r'$-1$', r'$0$', r'$+1$']) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_6.rst b/intro/matplotlib/auto_examples/plot_exercice_6.rst new file mode 100644 index 0000000..85e9b65 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_6.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_6.py: + + + + +.. image:: images/plot_exercice_6_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_6.py ` + +.. literalinclude:: plot_exercice_6.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_7.py b/intro/matplotlib/auto_examples/plot_exercice_7.py new file mode 100644 index 0000000..5a29d60 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_7.py @@ -0,0 +1,30 @@ +import pylab as pl +import numpy as np + +pl.figure(figsize=(8,5), dpi=80) +pl.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256,endpoint=True) +C = np.cos(X) +S = np.sin(X) + +pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-") +pl.plot(X, S, color="red", linewidth=2.5, linestyle="-") + +ax = pl.gca() +ax.spines['right'].set_color('none') +ax.spines['top'].set_color('none') +ax.xaxis.set_ticks_position('bottom') +ax.spines['bottom'].set_position(('data',0)) +ax.yaxis.set_ticks_position('left') +ax.spines['left'].set_position(('data',0)) + +pl.xlim(X.min() * 1.1, X.max() * 1.1) +pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], + [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) + +pl.ylim(C.min() * 1.1, C.max() * 1.1) +pl.yticks([-1, 0, +1], + [r'$-1$', r'$0$', r'$+1$']) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_7.rst b/intro/matplotlib/auto_examples/plot_exercice_7.rst new file mode 100644 index 0000000..089e701 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_7.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_7.py: + + + + +.. image:: images/plot_exercice_7_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_7.py ` + +.. literalinclude:: plot_exercice_7.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_8.py b/intro/matplotlib/auto_examples/plot_exercice_8.py new file mode 100644 index 0000000..c4c7553 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_8.py @@ -0,0 +1,32 @@ +import pylab as pl +import numpy as np + +pl.figure(figsize=(8,5), dpi=80) +pl.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256,endpoint=True) +C = np.cos(X) +S = np.sin(X) + +pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +pl.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + +ax = pl.gca() +ax.spines['right'].set_color('none') +ax.spines['top'].set_color('none') +ax.xaxis.set_ticks_position('bottom') +ax.spines['bottom'].set_position(('data',0)) +ax.yaxis.set_ticks_position('left') +ax.spines['left'].set_position(('data',0)) + +pl.xlim(X.min() * 1.1, X.max() * 1.1) +pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], + [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) + +pl.ylim(C.min() * 1.1, C.max() * 1.1) +pl.yticks([-1, +1], + [r'$-1$', r'$+1$']) + +pl.legend(loc='upper left') + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_8.rst b/intro/matplotlib/auto_examples/plot_exercice_8.rst new file mode 100644 index 0000000..b0422cc --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_8.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_8.py: + + + + +.. image:: images/plot_exercice_8_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_8.py ` + +.. literalinclude:: plot_exercice_8.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_exercice_9.py b/intro/matplotlib/auto_examples/plot_exercice_9.py new file mode 100644 index 0000000..bcea10e --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_9.py @@ -0,0 +1,49 @@ +import pylab as pl +import numpy as np + +pl.figure(figsize=(8, 5), dpi=80) +pl.subplot(111) + +X = np.linspace(-np.pi, np.pi, 256,endpoint=True) +C = np.cos(X) +S = np.sin(X) + +pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") +pl.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") + +ax = pl.gca() +ax.spines['right'].set_color('none') +ax.spines['top'].set_color('none') +ax.xaxis.set_ticks_position('bottom') +ax.spines['bottom'].set_position(('data',0)) +ax.yaxis.set_ticks_position('left') +ax.spines['left'].set_position(('data',0)) + +pl.xlim(X.min() * 1.1, X.max() * 1.1) +pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], + [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) + +pl.ylim(C.min() * 1.1, C.max() * 1.1) +pl.yticks([-1, +1], + [r'$-1$', r'$+1$']) + +t = 2*np.pi/3 +pl.plot([t, t], [0, np.cos(t)], + color='blue', linewidth=1.5, linestyle="--") +pl.scatter([t, ], [np.cos(t), ], 50, color='blue') +pl.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', + xy=(t, np.sin(t)), xycoords='data', + xytext=(+10, +30), textcoords='offset points', fontsize=16, + arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) + +pl.plot([t, t], [0, np.sin(t)], + color='red', linewidth=1.5, linestyle="--") +pl.scatter([t, ], [np.sin(t), ], 50, color='red') +pl.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), + xycoords='data', xytext=(-90, -50), textcoords='offset points', + fontsize=16, + arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) + +pl.legend(loc='upper left') + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_exercice_9.rst b/intro/matplotlib/auto_examples/plot_exercice_9.rst new file mode 100644 index 0000000..25a20d6 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_exercice_9.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_exercice_9.py: + + + + +.. image:: images/plot_exercice_9_1.png + :align: center + + +**Python source code:** :download:`plot_exercice_9.py ` + +.. literalinclude:: plot_exercice_9.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_good.py b/intro/matplotlib/auto_examples/plot_good.py new file mode 100644 index 0000000..6d372d9 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_good.py @@ -0,0 +1,14 @@ +import numpy as np +import matplotlib +matplotlib.use('Agg') +import pylab as pl + +fig = pl.figure(figsize=(5, 4), dpi=72) +axes = fig.add_axes([0.01, 0.01, .98, 0.98]) +X = np.linspace(0, 2, 200, endpoint=True) +Y = np.sin(2*np.pi*X) +pl.plot(X, Y, lw=2) +pl.ylim(-1.1, 1.1) +pl.grid() + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_good.rst b/intro/matplotlib/auto_examples/plot_good.rst new file mode 100644 index 0000000..0b285ee --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_good.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_good.py: + + + + +.. image:: images/plot_good_1.png + :align: center + + +**Python source code:** :download:`plot_good.py ` + +.. literalinclude:: plot_good.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_grid.py b/intro/matplotlib/auto_examples/plot_grid.py new file mode 100644 index 0000000..4be9b76 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_grid.py @@ -0,0 +1,32 @@ +import pylab as pl +from matplotlib.ticker import MultipleLocator + +fig = pl.figure(figsize=(8, 6), dpi=72, facecolor="white") +axes = pl.subplot(111) +axes.set_xlim(0, 4) +axes.set_ylim(0, 3) + +axes.xaxis.set_major_locator(MultipleLocator(1.0)) +axes.xaxis.set_minor_locator(MultipleLocator(0.1)) +axes.yaxis.set_major_locator(MultipleLocator(1.0)) +axes.yaxis.set_minor_locator(MultipleLocator(0.1)) +axes.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75') +axes.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75') +axes.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75') +axes.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75') +axes.set_xticklabels([]) +axes.set_yticklabels([]) + +pl.text(-0.05, 1.02, " Grid: pl.grid(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=axes.transAxes) + +pl.text(-0.05, 1.01, "\n\n Draw ticks and grid ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=axes.transAxes) + diff --git a/intro/matplotlib/auto_examples/plot_grid.rst b/intro/matplotlib/auto_examples/plot_grid.rst new file mode 100644 index 0000000..82d7ac8 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_grid.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_grid.py: + + + + +.. image:: images/plot_grid_1.png + :align: center + + +**Python source code:** :download:`plot_grid.py ` + +.. literalinclude:: plot_grid.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_grid_ex.py b/intro/matplotlib/auto_examples/plot_grid_ex.py new file mode 100644 index 0000000..530261b --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_grid_ex.py @@ -0,0 +1,18 @@ +import pylab as pl + +ax = pl.axes([0.025, 0.025, 0.95, 0.95]) + +ax.set_xlim(0,4) +ax.set_ylim(0,3) +ax.xaxis.set_major_locator(pl.MultipleLocator(1.0)) +ax.xaxis.set_minor_locator(pl.MultipleLocator(0.1)) +ax.yaxis.set_major_locator(pl.MultipleLocator(1.0)) +ax.yaxis.set_minor_locator(pl.MultipleLocator(0.1)) +ax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75') +ax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75') +ax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75') +ax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75') +ax.set_xticklabels([]) +ax.set_yticklabels([]) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_grid_ex.rst b/intro/matplotlib/auto_examples/plot_grid_ex.rst new file mode 100644 index 0000000..5a726e6 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_grid_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_grid_ex.py: + + + + +.. image:: images/plot_grid_ex_1.png + :align: center + + +**Python source code:** :download:`plot_grid_ex.py ` + +.. literalinclude:: plot_grid_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_gridspec.py b/intro/matplotlib/auto_examples/plot_gridspec.py new file mode 100644 index 0000000..09ba1a1 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_gridspec.py @@ -0,0 +1,33 @@ +import pylab as pl +import matplotlib.gridspec as gridspec + +pl.figure(figsize=(6, 4)) +G = gridspec.GridSpec(3, 3) + +axes_1 = pl.subplot(G[0, :]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'Axes 1', ha='center', va='center', size=24, alpha=.5) + +axes_2 = pl.subplot(G[1, :-1]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'Axes 2', ha='center', va='center', size=24, alpha=.5) + +axes_3 = pl.subplot(G[1:, -1]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'Axes 3', ha='center', va='center', size=24, alpha=.5) + +axes_4 = pl.subplot(G[-1, 0]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'Axes 4', ha='center', va='center', size=24, alpha=.5) + +axes_5 = pl.subplot(G[-1, -2]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'Axes 5', ha='center', va='center', size=24, alpha=.5) + +pl.tight_layout() +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_gridspec.rst b/intro/matplotlib/auto_examples/plot_gridspec.rst new file mode 100644 index 0000000..e8ed890 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_gridspec.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_gridspec.py: + + + + +.. image:: images/plot_gridspec_1.png + :align: center + + +**Python source code:** :download:`plot_gridspec.py ` + +.. literalinclude:: plot_gridspec.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_imshow.py b/intro/matplotlib/auto_examples/plot_imshow.py new file mode 100644 index 0000000..91912be --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_imshow.py @@ -0,0 +1,30 @@ +import pylab as pl +import numpy as np + +def f(x, y): + return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) + +n = 10 +x = np.linspace(-3, 3, 8 * n) +y = np.linspace(-3, 3, 6 * n) +X, Y = np.meshgrid(x, y) +Z = f(X, Y) +pl.imshow(Z, interpolation='nearest', cmap='bone', origin='lower') +pl.xticks(()) +pl.yticks(()) + +pl.text(-0.05, 1.02, " Imshow: pl.imshow(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) + +pl.text(-0.05, 1.01, "\n\n Display an image to current axes ", + horizontalalignment='left', + verticalalignment='top', + family='Lint McCree Intl BB', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_imshow.rst b/intro/matplotlib/auto_examples/plot_imshow.rst new file mode 100644 index 0000000..932ed89 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_imshow.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_imshow.py: + + + + +.. image:: images/plot_imshow_1.png + :align: center + + +**Python source code:** :download:`plot_imshow.py ` + +.. literalinclude:: plot_imshow.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_imshow_ex.py b/intro/matplotlib/auto_examples/plot_imshow_ex.py new file mode 100644 index 0000000..b07a8cd --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_imshow_ex.py @@ -0,0 +1,19 @@ +import pylab as pl +import numpy as np + +def f(x, y): + return (1 - x / 2 + x ** 5 + y ** 3 ) * np.exp(-x ** 2 - y ** 2) + +n = 10 +x = np.linspace(-3, 3, 3.5 * n) +y = np.linspace(-3, 3, 3.0 * n) +X, Y = np.meshgrid(x, y) +Z = f(X, Y) + +pl.axes([0.025, 0.025, 0.95, 0.95]) +pl.imshow(Z, interpolation='nearest', cmap='bone', origin='lower') +pl.colorbar(shrink=.92) + +pl.xticks(()) +pl.yticks(()) +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_imshow_ex.rst b/intro/matplotlib/auto_examples/plot_imshow_ex.rst new file mode 100644 index 0000000..f936263 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_imshow_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_imshow_ex.py: + + + + +.. image:: images/plot_imshow_ex_1.png + :align: center + + +**Python source code:** :download:`plot_imshow_ex.py ` + +.. literalinclude:: plot_imshow_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_linestyles.py b/intro/matplotlib/auto_examples/plot_linestyles.py new file mode 100644 index 0000000..0d08c6a --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_linestyles.py @@ -0,0 +1,29 @@ +import pylab as pl +import numpy as np + +def linestyle(ls, i): + X = i * .5 * np.ones(11) + Y = np.arange(11) + pl.plot(X, Y, ls, color=(.0, .0, 1, 1), lw=3, ms=8, + mfc=(.75, .75, 1, 1), mec=(0, 0, 1, 1)) + pl.text(.5 * i, 10.25, ls, rotation=90, fontsize=15, va='bottom') + +linestyles = ['-', '--', ':', '-.', '.', ',', 'o', '^', 'v', '<', '>', 's', + '+', 'x', 'd', '1', '2', '3', '4', 'h', 'p', '|', '_', 'D', 'H'] +n_lines = len(linestyles) + +size = 20 * n_lines, 300 +dpi = 72.0 +figsize= size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0.01, 1, .9], frameon=False) + +for i, ls in enumerate(linestyles): + linestyle(ls, i) + +pl.xlim(-.2, .2 + .5*n_lines) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_linestyles.rst b/intro/matplotlib/auto_examples/plot_linestyles.rst new file mode 100644 index 0000000..dc1b8c2 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_linestyles.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_linestyles.py: + + + + +.. image:: images/plot_linestyles_1.png + :align: center + + +**Python source code:** :download:`plot_linestyles.py ` + +.. literalinclude:: plot_linestyles.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_linewidth.py b/intro/matplotlib/auto_examples/plot_linewidth.py new file mode 100644 index 0000000..11bb8c4 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_linewidth.py @@ -0,0 +1,18 @@ +import pylab as pl + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, .1, 1, .8], frameon=False) + +for i in range(1, 11): + pl.plot([i, i], [0, 1], color='b', lw=i/2.) + +pl.xlim(0, 11) +pl.ylim(0, 1) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_linewidth.rst b/intro/matplotlib/auto_examples/plot_linewidth.rst new file mode 100644 index 0000000..95235f8 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_linewidth.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_linewidth.py: + + + + +.. image:: images/plot_linewidth_1.png + :align: center + + +**Python source code:** :download:`plot_linewidth.py ` + +.. literalinclude:: plot_linewidth.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_markers.py b/intro/matplotlib/auto_examples/plot_markers.py new file mode 100644 index 0000000..dc31ce9 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_markers.py @@ -0,0 +1,32 @@ +import pylab as pl +import numpy as np + +def marker(m, i): + X = i * .5 * np.ones(11) + Y = np.arange(11) + + pl.plot(X, Y, color='None', lw=1, marker=m, ms=10, mfc=(.75, .75, 1, 1), + mec=(0, 0, 1, 1)) + pl.text(.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va='bottom') + +markers = [0, 1, 2, 3, 4, 5, 6, 7, 'o', 'h', '_', '1', '2', '3', '4', + '8', 'p', '^', 'v', '<', '>', '|', 'd', ',', '+', 's', '*', + '|', 'x', 'D', 'H', '.'] + +n_markers = len(markers) + +size = 20 * n_markers, 300 +dpi = 72.0 +figsize= size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0.01, 1, .9], frameon=False) + +for i, m in enumerate(markers): + marker(m, i) + +pl.xlim(-.2, .2 + .5 * n_markers) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_markers.rst b/intro/matplotlib/auto_examples/plot_markers.rst new file mode 100644 index 0000000..b07f382 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_markers.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_markers.py: + + + + +.. rst-class:: horizontal + + + +**Python source code:** :download:`plot_markers.py ` + +.. literalinclude:: plot_markers.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_mec.py b/intro/matplotlib/auto_examples/plot_mec.py new file mode 100644 index 0000000..c61e81d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_mec.py @@ -0,0 +1,20 @@ +import pylab as pl +import numpy as np + +size = 256,16 +dpi = 72.0 +figsize= size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0, 1, 1], frameon=False) + +for i in range(1, 11): + r, g, b = np.random.uniform(0, 1, 3) + pl.plot([i, ], [1, ], 's', markersize=5, markerfacecolor='w', + markeredgewidth=1.5, markeredgecolor=(r, g, b, 1)) + +pl.xlim(0, 11) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_mec.rst b/intro/matplotlib/auto_examples/plot_mec.rst new file mode 100644 index 0000000..db442b4 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_mec.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_mec.py: + + + + +.. image:: images/plot_mec_1.png + :align: center + + +**Python source code:** :download:`plot_mec.py ` + +.. literalinclude:: plot_mec.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_mew.py b/intro/matplotlib/auto_examples/plot_mew.py new file mode 100644 index 0000000..2268575 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_mew.py @@ -0,0 +1,17 @@ +import pylab as pl + +size = 256, 16 +dpi = 72.0 +figsize= size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0, 1, 1], frameon=False) + +for i in range(1,11): + pl.plot([i, ], [1, ], 's', markersize=5, + markeredgewidth=1 + i/10., markeredgecolor='k', markerfacecolor='w') +pl.xlim(0, 11) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_mew.rst b/intro/matplotlib/auto_examples/plot_mew.rst new file mode 100644 index 0000000..144ca4d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_mew.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_mew.py: + + + + +.. image:: images/plot_mew_1.png + :align: center + + +**Python source code:** :download:`plot_mew.py ` + +.. literalinclude:: plot_mew.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_mfc.py b/intro/matplotlib/auto_examples/plot_mfc.py new file mode 100644 index 0000000..5da3061 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_mfc.py @@ -0,0 +1,18 @@ +import pylab as pl +import numpy as np + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0, 1, 1], frameon=False) + +for i in range(1, 11): + r, g, b = np.random.uniform(0, 1, 3) + pl.plot([i, ], [1, ], 's', markersize=8, markerfacecolor=(r, g, b, 1), + markeredgewidth=.1, markeredgecolor=(0, 0, 0, .5)) +pl.xlim(0, 11) +pl.xticks(()) +pl.yticks(()) +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_mfc.rst b/intro/matplotlib/auto_examples/plot_mfc.rst new file mode 100644 index 0000000..5be4fe4 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_mfc.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_mfc.py: + + + + +.. image:: images/plot_mfc_1.png + :align: center + + +**Python source code:** :download:`plot_mfc.py ` + +.. literalinclude:: plot_mfc.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_ms.py b/intro/matplotlib/auto_examples/plot_ms.py new file mode 100644 index 0000000..e34a187 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_ms.py @@ -0,0 +1,18 @@ +import pylab as pl + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0, 1, 1], frameon=False) + +for i in range(1, 11): + pl.plot([i, ], [1, ], 's', markersize=i, markerfacecolor='w', + markeredgewidth=.5, markeredgecolor='k') + +pl.xlim(0, 11) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_ms.rst b/intro/matplotlib/auto_examples/plot_ms.rst new file mode 100644 index 0000000..1aa1b5f --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_ms.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_ms.py: + + + + +.. image:: images/plot_ms_1.png + :align: center + + +**Python source code:** :download:`plot_ms.py ` + +.. literalinclude:: plot_ms.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_multiplot.py b/intro/matplotlib/auto_examples/plot_multiplot.py new file mode 100644 index 0000000..8a982c3 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_multiplot.py @@ -0,0 +1,27 @@ +import pylab as pl + +ax = pl.subplot(2, 1, 1) +ax.set_xticklabels([]) +ax.set_yticklabels([]) + +pl.text(-0.05, 1.02, " Multiplot: pl.subplot(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=ax.transAxes) +pl.text(-0.05, 1.01, "\n\n Plot several plots at once ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=ax.transAxes) + +ax = pl.subplot(2, 2, 3) +ax.set_xticklabels([]) +ax.set_yticklabels([]) + +ax = pl.subplot(2, 2, 4) +ax.set_xticklabels([]) +ax.set_yticklabels([]) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_multiplot.rst b/intro/matplotlib/auto_examples/plot_multiplot.rst new file mode 100644 index 0000000..f8879f3 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_multiplot.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_multiplot.py: + + + + +.. image:: images/plot_multiplot_1.png + :align: center + + +**Python source code:** :download:`plot_multiplot.py ` + +.. literalinclude:: plot_multiplot.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_multiplot_ex.py b/intro/matplotlib/auto_examples/plot_multiplot_ex.py new file mode 100644 index 0000000..e3066a2 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_multiplot_ex.py @@ -0,0 +1,21 @@ +import pylab as pl + +fig = pl.figure() +fig.subplots_adjust(bottom=0.025, left=0.025, top = 0.975, right=0.975) + +pl.subplot(2, 1, 1) +pl.xticks(()), pl.yticks(()) + +pl.subplot(2, 3, 4) +pl.xticks(()) +pl.yticks(()) + +pl.subplot(2, 3, 5) +pl.xticks(()) +pl.yticks(()) + +pl.subplot(2, 3, 6) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_multiplot_ex.rst b/intro/matplotlib/auto_examples/plot_multiplot_ex.rst new file mode 100644 index 0000000..0318b6e --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_multiplot_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_multiplot_ex.py: + + + + +.. image:: images/plot_multiplot_ex_1.png + :align: center + + +**Python source code:** :download:`plot_multiplot_ex.py ` + +.. literalinclude:: plot_multiplot_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_pie.py b/intro/matplotlib/auto_examples/plot_pie.py new file mode 100644 index 0000000..e2dc40e --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_pie.py @@ -0,0 +1,31 @@ +import pylab as pl +import numpy as np + +n = 20 +X = np.ones(n) +X[-1] *= 2 +pl.pie(X, explode=X*.05, colors = ['%f' % (i/float(n)) for i in range(n)]) + +fig = pl.gcf() +w, h = fig.get_figwidth(), fig.get_figheight() +r = h / float(w) + +pl.xlim(-1.5, 1.5) +pl.ylim(-1.5 * r, 1.5 * r) +pl.xticks(()) +pl.yticks(()) + +pl.text(-0.05, 1.02, " Pie Chart: pl.pie(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) + +pl.text(-0.05, 1.01, "\n\n Make a pie chart of an array ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_pie.rst b/intro/matplotlib/auto_examples/plot_pie.rst new file mode 100644 index 0000000..8fa663e --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_pie.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_pie.py: + + + + +.. image:: images/plot_pie_1.png + :align: center + + +**Python source code:** :download:`plot_pie.py ` + +.. literalinclude:: plot_pie.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_pie_ex.py b/intro/matplotlib/auto_examples/plot_pie_ex.py new file mode 100644 index 0000000..b1cf196 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_pie_ex.py @@ -0,0 +1,15 @@ +import pylab as pl +import numpy as np + +n = 20 +Z = np.ones(n) +Z[-1] *= 2 + +pl.axes([0.025, 0.025, 0.95, 0.95]) + +pl.pie(Z, explode=Z*.05, colors = ['%f' % (i/float(n)) for i in range(n)]) +pl.axis('equal') +pl.xticks(()) +pl.yticks() + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_pie_ex.rst b/intro/matplotlib/auto_examples/plot_pie_ex.rst new file mode 100644 index 0000000..423264c --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_pie_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_pie_ex.py: + + + + +.. image:: images/plot_pie_ex_1.png + :align: center + + +**Python source code:** :download:`plot_pie_ex.py ` + +.. literalinclude:: plot_pie_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_plot.py b/intro/matplotlib/auto_examples/plot_plot.py new file mode 100644 index 0000000..60367c8 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot.py @@ -0,0 +1,27 @@ +import pylab as pl +import numpy as np + +n = 256 +X = np.linspace(0, 2, n) +Y = np.sin(2 * np.pi * X) + +pl.plot (X, Y, lw=2, color='violet') +pl.xlim(-0.2, 2.2) +pl.xticks(()) +pl.ylim(-1.2, 1.2) +pl.yticks(()) + +pl.text(-0.05, 1.02, " Regular Plot: pl.plot(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) + +pl.text(-0.05, 1.01, "\n\n Plot lines and/or markers ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_plot.rst b/intro/matplotlib/auto_examples/plot_plot.rst new file mode 100644 index 0000000..b2ff71e --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_plot.py: + + + + +.. image:: images/plot_plot_1.png + :align: center + + +**Python source code:** :download:`plot_plot.py ` + +.. literalinclude:: plot_plot.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/examples/plot_plot3d-2.py b/intro/matplotlib/auto_examples/plot_plot3d-2.py similarity index 100% rename from intro/matplotlib/examples/plot_plot3d-2.py rename to intro/matplotlib/auto_examples/plot_plot3d-2.py diff --git a/intro/matplotlib/auto_examples/plot_plot3d-2.rst b/intro/matplotlib/auto_examples/plot_plot3d-2.rst new file mode 100644 index 0000000..2dcd063 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot3d-2.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_plot3d-2.py: + + + + +.. image:: images/plot_plot3d-2_1.png + :align: center + + +**Python source code:** :download:`plot_plot3d-2.py ` + +.. literalinclude:: plot_plot3d-2.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_plot3d.py b/intro/matplotlib/auto_examples/plot_plot3d.py new file mode 100644 index 0000000..693e4ce --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot3d.py @@ -0,0 +1,33 @@ +import pylab as pl +import numpy as np +from mpl_toolkits.mplot3d import Axes3D + +fig = pl.figure() +ax = Axes3D(fig) +X = np.arange(-4, 4, 0.25) +Y = np.arange(-4, 4, 0.25) +X, Y = np.meshgrid(X, Y) +R = np.sqrt(X ** 2 + Y ** 2) +Z = np.sin(R) + +ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=pl.cm.hot) +ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=pl.cm.hot) +ax.set_zlim(-2, 2) +pl.xticks(()) +pl.yticks(()) +ax.set_zticks(()) + +ax.text2D(0.05, .93, " 3D plots \n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) + +ax.text2D(0.05, .87, " Plot 2D or 3D data", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_plot3d.rst b/intro/matplotlib/auto_examples/plot_plot3d.rst new file mode 100644 index 0000000..d4c159f --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot3d.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_plot3d.py: + + + + +.. image:: images/plot_plot3d_1.png + :align: center + + +**Python source code:** :download:`plot_plot3d.py ` + +.. literalinclude:: plot_plot3d.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_plot3d_2.py b/intro/matplotlib/auto_examples/plot_plot3d_2.py new file mode 100644 index 0000000..348f204 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot3d_2.py @@ -0,0 +1,28 @@ +import pylab as pl +from mpl_toolkits.mplot3d import axes3d + +ax = pl.gca(projection='3d') +X, Y, Z = axes3d.get_test_data(0.05) +cset = ax.contourf(X, Y, Z) +ax.clabel(cset, fontsize=9, inline=1) + +pl.xticks(()) +pl.yticks(()) +ax.set_zticks(()) + +ax.text2D(-0.05, 1.05, " 3D plots \n\n", + horizontalalignment='left', + verticalalignment='top', + family='Lint McCree Intl BB', + size='x-large', + bbox=dict(facecolor='white', alpha=1.0, width=350,height=60), + transform=pl.gca().transAxes) + +ax.text2D(-0.05, .975, " Plot 2D or 3D data", + horizontalalignment='left', + verticalalignment='top', + family='Lint McCree Intl BB', + size='medium', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_plot3d_2.rst b/intro/matplotlib/auto_examples/plot_plot3d_2.rst new file mode 100644 index 0000000..df4defc --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot3d_2.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_plot3d_2.py: + + + + +.. image:: images/plot_plot3d_2_1.png + :align: center + + +**Python source code:** :download:`plot_plot3d_2.py ` + +.. literalinclude:: plot_plot3d_2.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_plot3d_ex.py b/intro/matplotlib/auto_examples/plot_plot3d_ex.py new file mode 100644 index 0000000..636d179 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot3d_ex.py @@ -0,0 +1,17 @@ +import pylab as pl +import numpy as np +from mpl_toolkits.mplot3d import Axes3D + +fig = pl.figure() +ax = Axes3D(fig) +X = np.arange(-4, 4, 0.25) +Y = np.arange(-4, 4, 0.25) +X, Y = np.meshgrid(X, Y) +R = np.sqrt(X ** 2 + Y ** 2) +Z = np.sin(R) + +ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=pl.cm.hot) +ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=pl.cm.hot) +ax.set_zlim(-2, 2) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_plot3d_ex.rst b/intro/matplotlib/auto_examples/plot_plot3d_ex.rst new file mode 100644 index 0000000..d7bd878 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot3d_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_plot3d_ex.py: + + + + +.. image:: images/plot_plot3d_ex_1.png + :align: center + + +**Python source code:** :download:`plot_plot3d_ex.py ` + +.. literalinclude:: plot_plot3d_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_plot_ex.py b/intro/matplotlib/auto_examples/plot_plot_ex.py new file mode 100644 index 0000000..06c6baa --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot_ex.py @@ -0,0 +1,22 @@ +import pylab as pl +import numpy as np + +n = 256 +X = np.linspace(-np.pi, np.pi, n, endpoint=True) +Y = np.sin(2 * X) + +pl.axes([0.025, 0.025, 0.95, 0.95]) + +pl.plot(X, Y + 1, color='blue', alpha=1.00) +pl.fill_between(X, 1, Y + 1, color='blue', alpha=.25) + +pl.plot(X, Y - 1, color='blue', alpha=1.00) +pl.fill_between(X, -1, Y - 1, (Y - 1) > -1, color='blue', alpha=.25) +pl.fill_between(X, -1, Y - 1, (Y - 1) < -1, color='red', alpha=.25) + +pl.xlim(-np.pi, np.pi) +pl.xticks(()) +pl.ylim(-2.5, 2.5) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_plot_ex.rst b/intro/matplotlib/auto_examples/plot_plot_ex.rst new file mode 100644 index 0000000..bf16008 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_plot_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_plot_ex.py: + + + + +.. image:: images/plot_plot_ex_1.png + :align: center + + +**Python source code:** :download:`plot_plot_ex.py ` + +.. literalinclude:: plot_plot_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_polar.py b/intro/matplotlib/auto_examples/plot_polar.py new file mode 100644 index 0000000..501daeb --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_polar.py @@ -0,0 +1,29 @@ +import pylab as pl +import numpy as np + +pl.subplot(1, 1, 1, polar=True) + +N = 20 +theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) +radii = 10 * np.random.rand(N) +width = np.pi / 4 * np.random.rand(N) +bars = pl.bar(theta, radii, width=width, bottom=0.0) +for r, bar in zip(radii, bars): + bar.set_facecolor(pl.cm.jet(r / 10.)) + bar.set_alpha(0.5) +pl.gca().set_xticklabels([]) +pl.gca().set_yticklabels([]) + +pl.text(-0.2, 1.02, " Polar Axis\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) +pl.text(-0.2, 1.01, "\n\n Plot anything using polar axis ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_polar.rst b/intro/matplotlib/auto_examples/plot_polar.rst new file mode 100644 index 0000000..3a2e25d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_polar.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_polar.py: + + + + +.. image:: images/plot_polar_1.png + :align: center + + +**Python source code:** :download:`plot_polar.py ` + +.. literalinclude:: plot_polar.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_polar_ex.py b/intro/matplotlib/auto_examples/plot_polar_ex.py new file mode 100644 index 0000000..c727029 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_polar_ex.py @@ -0,0 +1,18 @@ +import pylab as pl +import numpy as np + +ax = pl.axes([0.025, 0.025, 0.95, 0.95], polar=True) + +N = 20 +theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) +radii = 10 * np.random.rand(N) +width = np.pi / 4 * np.random.rand(N) +bars = pl.bar(theta, radii, width=width, bottom=0.0) + +for r,bar in zip(radii, bars): + bar.set_facecolor(pl.cm.jet(r/10.)) + bar.set_alpha(0.5) + +ax.set_xticklabels([]) +ax.set_yticklabels([]) +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_polar_ex.rst b/intro/matplotlib/auto_examples/plot_polar_ex.rst new file mode 100644 index 0000000..34bf35d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_polar_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_polar_ex.py: + + + + +.. image:: images/plot_polar_ex_1.png + :align: center + + +**Python source code:** :download:`plot_polar_ex.py ` + +.. literalinclude:: plot_polar_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_quiver.py b/intro/matplotlib/auto_examples/plot_quiver.py new file mode 100644 index 0000000..eaaaa63 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_quiver.py @@ -0,0 +1,31 @@ +import pylab as pl +import numpy as np + +n = 8 +X, Y = np.mgrid[0:n, 0:n] +T = np.arctan2(Y - n/ 2., X - n / 2.) +R = 10 + np.sqrt((Y - n / 2.) ** 2 + (X - n / 2.) ** 2) +U, V = R * np.cos(T), R * np.sin(T) + +pl.quiver(X, Y, U, V, R, alpha=.5) +pl.quiver(X, Y, U, V, edgecolor='k', facecolor='None', linewidth=.5) + +pl.xlim(-1, n) +pl.xticks(()) +pl.ylim(-1, n) +pl.yticks(()) + +pl.text(-0.05, 1.02, " Quiver Plot: pl.quiver(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) + +pl.text(-0.05, 1.01, "\n\n Plot a 2-D field of arrows ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_quiver.rst b/intro/matplotlib/auto_examples/plot_quiver.rst new file mode 100644 index 0000000..219e060 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_quiver.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_quiver.py: + + + + +.. image:: images/plot_quiver_1.png + :align: center + + +**Python source code:** :download:`plot_quiver.py ` + +.. literalinclude:: plot_quiver.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_quiver_ex.py b/intro/matplotlib/auto_examples/plot_quiver_ex.py new file mode 100644 index 0000000..e39f038 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_quiver_ex.py @@ -0,0 +1,19 @@ +import pylab as pl +import numpy as np + +n = 8 +X, Y = np.mgrid[0:n, 0:n] +T = np.arctan2(Y - n / 2., X - n/2.) +R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) +U, V = R * np.cos(T), R * np.sin(T) + +pl.axes([0.025, 0.025, 0.95, 0.95]) +pl.quiver(X, Y, U, V, R, alpha=.5) +pl.quiver(X, Y, U, V, edgecolor='k', facecolor='None', linewidth=.5) + +pl.xlim(-1, n) +pl.xticks(()) +pl.ylim(-1, n) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_quiver_ex.rst b/intro/matplotlib/auto_examples/plot_quiver_ex.rst new file mode 100644 index 0000000..2461508 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_quiver_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_quiver_ex.py: + + + + +.. image:: images/plot_quiver_ex_1.png + :align: center + + +**Python source code:** :download:`plot_quiver_ex.py ` + +.. literalinclude:: plot_quiver_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_scatter.py b/intro/matplotlib/auto_examples/plot_scatter.py new file mode 100644 index 0000000..32032e1 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_scatter.py @@ -0,0 +1,29 @@ +import pylab as pl +import numpy as np + +n = 1024 +X = np.random.normal(0, 1, n) +Y = np.random.normal(0, 1, n) + +T = np.arctan2(Y,X) + +pl.scatter(X, Y, s=75, c=T, alpha=.5) +pl.xlim(-1.5, 1.5) +pl.xticks(()) +pl.ylim(-1.5, 1.5) +pl.yticks(()) + +pl.text(-0.05, 1.02, " Scatter Plot: pl.scatter(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) + +pl.text(-0.05, 1.01, "\n\n Make a scatter plot of x versus y ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_scatter.rst b/intro/matplotlib/auto_examples/plot_scatter.rst new file mode 100644 index 0000000..b30e0a1 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_scatter.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_scatter.py: + + + + +.. image:: images/plot_scatter_1.png + :align: center + + +**Python source code:** :download:`plot_scatter.py ` + +.. literalinclude:: plot_scatter.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_scatter_ex.py b/intro/matplotlib/auto_examples/plot_scatter_ex.py new file mode 100644 index 0000000..b0c2112 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_scatter_ex.py @@ -0,0 +1,17 @@ +import pylab as pl +import numpy as np + +n = 1024 +X = np.random.normal(0, 1, n) +Y = np.random.normal(0, 1, n) +T = np.arctan2(Y, X) + +pl.axes([0.025, 0.025, 0.95, 0.95]) +pl.scatter(X, Y, s=75, c=T, alpha=.5) + +pl.xlim(-1.5, 1.5) +pl.xticks(()) +pl.ylim(-1.5, 1.5) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_scatter_ex.rst b/intro/matplotlib/auto_examples/plot_scatter_ex.rst new file mode 100644 index 0000000..76987b8 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_scatter_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_scatter_ex.py: + + + + +.. image:: images/plot_scatter_ex_1.png + :align: center + + +**Python source code:** :download:`plot_scatter_ex.py ` + +.. literalinclude:: plot_scatter_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_solid_capstyle.py b/intro/matplotlib/auto_examples/plot_solid_capstyle.py new file mode 100644 index 0000000..39517ba --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_solid_capstyle.py @@ -0,0 +1,24 @@ +import pylab as pl +import numpy as np + +size = 256, 16 +dpi = 72.0 +figsize= size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0, 1, 1], frameon=False) + +pl.plot(np.arange(4), np.ones(4), color="blue", linewidth=8, + solid_capstyle='butt') + +pl.plot(5 + np.arange(4), np.ones(4), color="blue", linewidth=8, + solid_capstyle='round') + +pl.plot(10 + np.arange(4), np.ones(4), color="blue", linewidth=8, + solid_capstyle='projecting') + +pl.xlim(0, 14) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_solid_capstyle.rst b/intro/matplotlib/auto_examples/plot_solid_capstyle.rst new file mode 100644 index 0000000..8ec409d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_solid_capstyle.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_solid_capstyle.py: + + + + +.. image:: images/plot_solid_capstyle_1.png + :align: center + + +**Python source code:** :download:`plot_solid_capstyle.py ` + +.. literalinclude:: plot_solid_capstyle.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_solid_joinstyle.py b/intro/matplotlib/auto_examples/plot_solid_joinstyle.py new file mode 100644 index 0000000..c413e2e --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_solid_joinstyle.py @@ -0,0 +1,23 @@ +import pylab as pl +import numpy as np + +size = 256, 16 +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) +pl.axes([0, 0, 1, 1], frameon=False) + +pl.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=8, + solid_joinstyle='miter') +pl.plot(4 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, + solid_joinstyle='bevel') +pl.plot(8 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, + solid_joinstyle='round') + +pl.xlim(0, 12) +pl.ylim(-1, 2) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_solid_joinstyle.rst b/intro/matplotlib/auto_examples/plot_solid_joinstyle.rst new file mode 100644 index 0000000..49c7115 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_solid_joinstyle.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_solid_joinstyle.py: + + + + +.. image:: images/plot_solid_joinstyle_1.png + :align: center + + +**Python source code:** :download:`plot_solid_joinstyle.py ` + +.. literalinclude:: plot_solid_joinstyle.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/examples/plot_subplot-grid.py b/intro/matplotlib/auto_examples/plot_subplot-grid.py similarity index 100% rename from intro/matplotlib/examples/plot_subplot-grid.py rename to intro/matplotlib/auto_examples/plot_subplot-grid.py diff --git a/intro/matplotlib/auto_examples/plot_subplot-grid.rst b/intro/matplotlib/auto_examples/plot_subplot-grid.rst new file mode 100644 index 0000000..446d247 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot-grid.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_subplot-grid.py: + + + + +.. image:: images/plot_subplot-grid_1.png + :align: center + + +**Python source code:** :download:`plot_subplot-grid.py ` + +.. literalinclude:: plot_subplot-grid.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/examples/plot_subplot-horizontal.py b/intro/matplotlib/auto_examples/plot_subplot-horizontal.py similarity index 100% rename from intro/matplotlib/examples/plot_subplot-horizontal.py rename to intro/matplotlib/auto_examples/plot_subplot-horizontal.py diff --git a/intro/matplotlib/auto_examples/plot_subplot-horizontal.rst b/intro/matplotlib/auto_examples/plot_subplot-horizontal.rst new file mode 100644 index 0000000..6de2c0f --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot-horizontal.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_subplot-horizontal.py: + + + + +.. image:: images/plot_subplot-horizontal_1.png + :align: center + + +**Python source code:** :download:`plot_subplot-horizontal.py ` + +.. literalinclude:: plot_subplot-horizontal.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/examples/plot_subplot-vertical.py b/intro/matplotlib/auto_examples/plot_subplot-vertical.py similarity index 100% rename from intro/matplotlib/examples/plot_subplot-vertical.py rename to intro/matplotlib/auto_examples/plot_subplot-vertical.py diff --git a/intro/matplotlib/auto_examples/plot_subplot-vertical.rst b/intro/matplotlib/auto_examples/plot_subplot-vertical.rst new file mode 100644 index 0000000..3701876 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot-vertical.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_subplot-vertical.py: + + + + +.. image:: images/plot_subplot-vertical_1.png + :align: center + + +**Python source code:** :download:`plot_subplot-vertical.py ` + +.. literalinclude:: plot_subplot-vertical.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_subplot_grid.py b/intro/matplotlib/auto_examples/plot_subplot_grid.py new file mode 100644 index 0000000..e55fa0c --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot_grid.py @@ -0,0 +1,30 @@ +import pylab as pl + +pl.figure(figsize=(6, 4)) +pl.subplot(2, 2, 1) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,2,1)', ha='center', va='center', + size=20, alpha=.5) + +pl.subplot(2, 2, 2) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,2,2)', ha='center', va='center', + size=20, alpha=.5) + +pl.subplot(2, 2, 3) +pl.xticks(()) +pl.yticks(()) + +pl.text(0.5, 0.5, 'subplot(2,2,3)', ha='center', va='center', + size=20, alpha=.5) + +pl.subplot(2, 2, 4) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,2,4)', ha='center', va='center', + size=20, alpha=.5) + +pl.tight_layout() +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_subplot_grid.rst b/intro/matplotlib/auto_examples/plot_subplot_grid.rst new file mode 100644 index 0000000..f023818 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot_grid.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_subplot_grid.py: + + + + +.. image:: images/plot_subplot_grid_1.png + :align: center + + +**Python source code:** :download:`plot_subplot_grid.py ` + +.. literalinclude:: plot_subplot_grid.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_subplot_horizontal.py b/intro/matplotlib/auto_examples/plot_subplot_horizontal.py new file mode 100644 index 0000000..049af79 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot_horizontal.py @@ -0,0 +1,17 @@ +import pylab as pl + +pl.figure(figsize=(6, 4)) +pl.subplot(2, 1, 1) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,1,1)', ha='center', va='center', + size=24, alpha=.5) + +pl.subplot(2, 1, 2) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,1,2)', ha='center', va='center', + size=24, alpha=.5) + +pl.tight_layout() +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_subplot_horizontal.rst b/intro/matplotlib/auto_examples/plot_subplot_horizontal.rst new file mode 100644 index 0000000..e50f85d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot_horizontal.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_subplot_horizontal.py: + + + + +.. image:: images/plot_subplot_horizontal_1.png + :align: center + + +**Python source code:** :download:`plot_subplot_horizontal.py ` + +.. literalinclude:: plot_subplot_horizontal.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_subplot_vertical.py b/intro/matplotlib/auto_examples/plot_subplot_vertical.py new file mode 100644 index 0000000..816c8de --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot_vertical.py @@ -0,0 +1,17 @@ +import pylab as pl + +pl.figure(figsize=(6, 4)) +pl.subplot(1, 2, 1) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(1,2,1)', ha='center', va='center', + size=24, alpha=.5) + +pl.subplot(1, 2, 2) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(1,2,2)', ha='center', va='center', + size=24, alpha=.5) + +pl.tight_layout() +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_subplot_vertical.rst b/intro/matplotlib/auto_examples/plot_subplot_vertical.rst new file mode 100644 index 0000000..511270a --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_subplot_vertical.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_subplot_vertical.py: + + + + +.. image:: images/plot_subplot_vertical_1.png + :align: center + + +**Python source code:** :download:`plot_subplot_vertical.py ` + +.. literalinclude:: plot_subplot_vertical.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_text.py b/intro/matplotlib/auto_examples/plot_text.py new file mode 100644 index 0000000..95b48ef --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_text.py @@ -0,0 +1,37 @@ +import pylab as pl +import numpy as np + +fig = pl.figure() +pl.xticks(()) +pl.yticks(()) + +eqs = [] +eqs.append((r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$")) +eqs.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$")) +eqs.append((r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$")) +eqs.append((r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$")) +eqs.append((r"$F_G = G\frac{m_1m_2}{r^2}$")) + +for i in range(24): + index = np.random.randint(0,len(eqs)) + eq = eqs[index] + size = np.random.uniform(12,32) + x,y = np.random.uniform(0,1,2) + alpha = np.random.uniform(0.25,.75) + pl.text(x, y, eq, ha='center', va='center', color="#11557c", alpha=alpha, + transform=pl.gca().transAxes, fontsize=size, clip_on=True) + +pl.text(-0.05, 1.02, " Text: pl.text(...)\n", + horizontalalignment='left', + verticalalignment='top', + size='xx-large', + bbox=dict(facecolor='white', alpha=1.0, width=400, height=65), + transform=pl.gca().transAxes) + +pl.text(-0.05, 1.01, "\n\n Draw any kind of text ", + horizontalalignment='left', + verticalalignment='top', + size='large', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_text.rst b/intro/matplotlib/auto_examples/plot_text.rst new file mode 100644 index 0000000..e99c31b --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_text.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_text.py: + + + + +.. image:: images/plot_text_1.png + :align: center + + +**Python source code:** :download:`plot_text.py ` + +.. literalinclude:: plot_text.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_text_ex.py b/intro/matplotlib/auto_examples/plot_text_ex.py new file mode 100644 index 0000000..3072ea1 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_text_ex.py @@ -0,0 +1,24 @@ +import pylab as pl +import numpy as np + +eqs = [] +eqs.append((r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$")) +eqs.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$")) +eqs.append((r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$")) +eqs.append((r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$")) +eqs.append((r"$F_G = G\frac{m_1m_2}{r^2}$")) + +pl.axes([0.025, 0.025, 0.95, 0.95]) + +for i in range(24): + index = np.random.randint(0, len(eqs)) + eq = eqs[index] + size = np.random.uniform(12, 32) + x,y = np.random.uniform(0, 1, 2) + alpha = np.random.uniform(0.25, .75) + pl.text(x, y, eq, ha='center', va='center', color="#11557c", alpha=alpha, + transform=pl.gca().transAxes, fontsize=size, clip_on=True) +pl.xticks(()) +pl.yticks(()) + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_text_ex.rst b/intro/matplotlib/auto_examples/plot_text_ex.rst new file mode 100644 index 0000000..0f0ea9f --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_text_ex.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_text_ex.py: + + + + +.. image:: images/plot_text_ex_1.png + :align: center + + +**Python source code:** :download:`plot_text_ex.py ` + +.. literalinclude:: plot_text_ex.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_ticks.py b/intro/matplotlib/auto_examples/plot_ticks.py new file mode 100644 index 0000000..4c1e7fa --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_ticks.py @@ -0,0 +1,44 @@ +import pylab as pl +import numpy as np + + +def tickline(): + pl.xlim(0, 10), pl.ylim(-1, 1), pl.yticks([]) + ax = pl.gca() + ax.spines['right'].set_color('none') + ax.spines['left'].set_color('none') + ax.spines['top'].set_color('none') + ax.xaxis.set_ticks_position('bottom') + ax.spines['bottom'].set_position(('data',0)) + ax.yaxis.set_ticks_position('none') + ax.xaxis.set_minor_locator(pl.MultipleLocator(0.1)) + ax.plot(np.arange(11), np.zeros(11), color='none') + return ax + +locators = [ + 'pl.NullLocator()', + 'pl.MultipleLocator(1.0)', + 'pl.FixedLocator([0, 2, 8, 9, 10])', + 'pl.IndexLocator(3, 1)', + 'pl.LinearLocator(5)', + 'pl.LogLocator(2, [1.0])', + 'pl.AutoLocator()', + ] + +n_locators = len(locators) + +size = 512, 40 * n_locators +dpi = 72.0 +figsize = size[0] / float(dpi), size[1] / float(dpi) +fig = pl.figure(figsize=figsize, dpi=dpi) +fig.patch.set_alpha(0) + + +for i, locator in enumerate(locators): + pl.subplot(n_locators, 1, i + 1) + ax = tickline() + ax.xaxis.set_major_locator(eval(locator)) + pl.text(5, 0.3, locator[3:], ha='center') + +pl.subplots_adjust(bottom=.01, top=.99, left=.01, right=.99) +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_ticks.rst b/intro/matplotlib/auto_examples/plot_ticks.rst new file mode 100644 index 0000000..16eedf5 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_ticks.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_ticks.py: + + + + +.. rst-class:: horizontal + + + +**Python source code:** :download:`plot_ticks.py ` + +.. literalinclude:: plot_ticks.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/auto_examples/plot_ugly.py b/intro/matplotlib/auto_examples/plot_ugly.py new file mode 100644 index 0000000..57f8187 --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_ugly.py @@ -0,0 +1,19 @@ +import numpy as np +import matplotlib +matplotlib.use('Agg') +import pylab as pl + +matplotlib.rc('grid', color='black', linestyle='-', linewidth=1) + +fig = pl.figure(figsize=(5,4),dpi=72) +axes = fig.add_axes([0.01, 0.01, .98, 0.98], axisbg='.75') +X = np.linspace(0, 2, 40, endpoint=True) +Y = np.sin(2 * np.pi * X) +pl.plot(X, Y, lw=.05, c='b', antialiased=False) + +pl.xticks(()) +pl.yticks(np.arange(-1., 1., 0.2)) +pl.grid() +ax = pl.gca() + +pl.show() diff --git a/intro/matplotlib/auto_examples/plot_ugly.rst b/intro/matplotlib/auto_examples/plot_ugly.rst new file mode 100644 index 0000000..47bec3d --- /dev/null +++ b/intro/matplotlib/auto_examples/plot_ugly.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_ugly.py: + + + + +.. image:: images/plot_ugly_1.png + :align: center + + +**Python source code:** :download:`plot_ugly.py ` + +.. literalinclude:: plot_ugly.py + :lines: 2- + \ No newline at end of file diff --git a/intro/matplotlib/examples/plot_axes_2.py b/intro/matplotlib/examples/plot_axes_2.py new file mode 100644 index 0000000..13505f6 --- /dev/null +++ b/intro/matplotlib/examples/plot_axes_2.py @@ -0,0 +1,27 @@ +import pylab as pl + +pl.axes([.1, .1, .5, .5]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.1, 0.1, 'axes([0.1,0.1,.8,.8])', ha='left', va='center', + size=16, alpha=.5) + +pl.axes([.2, .2, .5, .5]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.1, 0.1, 'axes([0.2,0.2,.5,.5])', ha='left', va='center', + size=16, alpha=.5) + +pl.axes([0.3, 0.3, .5, .5]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.1, 0.1, 'axes([0.3,0.3,.5,.5])', ha='left', va='center', + size=16, alpha=.5) + +pl.axes([.4, .4, .5, .5]) +pl.xticks(()) +pl.yticks(()) +pl.text(0.1, 0.1, 'axes([0.4,0.4,.5,.5])', ha='left', va='center', + size=16, alpha=.5) + +pl.show() diff --git a/intro/matplotlib/examples/plot_plot3d_2.py b/intro/matplotlib/examples/plot_plot3d_2.py new file mode 100644 index 0000000..348f204 --- /dev/null +++ b/intro/matplotlib/examples/plot_plot3d_2.py @@ -0,0 +1,28 @@ +import pylab as pl +from mpl_toolkits.mplot3d import axes3d + +ax = pl.gca(projection='3d') +X, Y, Z = axes3d.get_test_data(0.05) +cset = ax.contourf(X, Y, Z) +ax.clabel(cset, fontsize=9, inline=1) + +pl.xticks(()) +pl.yticks(()) +ax.set_zticks(()) + +ax.text2D(-0.05, 1.05, " 3D plots \n\n", + horizontalalignment='left', + verticalalignment='top', + family='Lint McCree Intl BB', + size='x-large', + bbox=dict(facecolor='white', alpha=1.0, width=350,height=60), + transform=pl.gca().transAxes) + +ax.text2D(-0.05, .975, " Plot 2D or 3D data", + horizontalalignment='left', + verticalalignment='top', + family='Lint McCree Intl BB', + size='medium', + transform=pl.gca().transAxes) + +pl.show() diff --git a/intro/matplotlib/examples/plot_subplot_grid.py b/intro/matplotlib/examples/plot_subplot_grid.py new file mode 100644 index 0000000..e55fa0c --- /dev/null +++ b/intro/matplotlib/examples/plot_subplot_grid.py @@ -0,0 +1,30 @@ +import pylab as pl + +pl.figure(figsize=(6, 4)) +pl.subplot(2, 2, 1) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,2,1)', ha='center', va='center', + size=20, alpha=.5) + +pl.subplot(2, 2, 2) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,2,2)', ha='center', va='center', + size=20, alpha=.5) + +pl.subplot(2, 2, 3) +pl.xticks(()) +pl.yticks(()) + +pl.text(0.5, 0.5, 'subplot(2,2,3)', ha='center', va='center', + size=20, alpha=.5) + +pl.subplot(2, 2, 4) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,2,4)', ha='center', va='center', + size=20, alpha=.5) + +pl.tight_layout() +pl.show() diff --git a/intro/matplotlib/examples/plot_subplot_horizontal.py b/intro/matplotlib/examples/plot_subplot_horizontal.py new file mode 100644 index 0000000..049af79 --- /dev/null +++ b/intro/matplotlib/examples/plot_subplot_horizontal.py @@ -0,0 +1,17 @@ +import pylab as pl + +pl.figure(figsize=(6, 4)) +pl.subplot(2, 1, 1) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,1,1)', ha='center', va='center', + size=24, alpha=.5) + +pl.subplot(2, 1, 2) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(2,1,2)', ha='center', va='center', + size=24, alpha=.5) + +pl.tight_layout() +pl.show() diff --git a/intro/matplotlib/examples/plot_subplot_vertical.py b/intro/matplotlib/examples/plot_subplot_vertical.py new file mode 100644 index 0000000..816c8de --- /dev/null +++ b/intro/matplotlib/examples/plot_subplot_vertical.py @@ -0,0 +1,17 @@ +import pylab as pl + +pl.figure(figsize=(6, 4)) +pl.subplot(1, 2, 1) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(1,2,1)', ha='center', va='center', + size=24, alpha=.5) + +pl.subplot(1, 2, 2) +pl.xticks(()) +pl.yticks(()) +pl.text(0.5, 0.5, 'subplot(1,2,2)', ha='center', va='center', + size=24, alpha=.5) + +pl.tight_layout() +pl.show() diff --git a/intro/matplotlib/figures/arrow.png b/intro/matplotlib/figures/arrow.png deleted file mode 100644 index 5a3757b..0000000 Binary files a/intro/matplotlib/figures/arrow.png and /dev/null differ diff --git a/intro/matplotlib/figures/axes.png b/intro/matplotlib/figures/axes.png deleted file mode 100644 index 03b8677..0000000 Binary files a/intro/matplotlib/figures/axes.png and /dev/null differ diff --git a/intro/matplotlib/figures/bar.png b/intro/matplotlib/figures/bar.png deleted file mode 100644 index a8e9468..0000000 Binary files a/intro/matplotlib/figures/bar.png and /dev/null differ diff --git a/intro/matplotlib/figures/barh.png b/intro/matplotlib/figures/barh.png deleted file mode 100644 index 4b25717..0000000 Binary files a/intro/matplotlib/figures/barh.png and /dev/null differ diff --git a/intro/matplotlib/figures/boxplot.png b/intro/matplotlib/figures/boxplot.png deleted file mode 100644 index 40e1610..0000000 Binary files a/intro/matplotlib/figures/boxplot.png and /dev/null differ diff --git a/intro/matplotlib/figures/broken_barh.png b/intro/matplotlib/figures/broken_barh.png deleted file mode 100644 index 24a5c37..0000000 Binary files a/intro/matplotlib/figures/broken_barh.png and /dev/null differ diff --git a/intro/matplotlib/figures/contour.png b/intro/matplotlib/figures/contour.png deleted file mode 100644 index 26a97f2..0000000 Binary files a/intro/matplotlib/figures/contour.png and /dev/null differ diff --git a/intro/matplotlib/figures/contourf.png b/intro/matplotlib/figures/contourf.png deleted file mode 100644 index 35e94bb..0000000 Binary files a/intro/matplotlib/figures/contourf.png and /dev/null differ diff --git a/intro/matplotlib/figures/date.png b/intro/matplotlib/figures/date.png deleted file mode 100644 index 8ad837e..0000000 Binary files a/intro/matplotlib/figures/date.png and /dev/null differ diff --git a/intro/matplotlib/figures/hist.png b/intro/matplotlib/figures/hist.png deleted file mode 100644 index 349b64b..0000000 Binary files a/intro/matplotlib/figures/hist.png and /dev/null differ diff --git a/intro/matplotlib/figures/legend.png b/intro/matplotlib/figures/legend.png deleted file mode 100644 index 22f2a83..0000000 Binary files a/intro/matplotlib/figures/legend.png and /dev/null differ diff --git a/intro/matplotlib/figures/loglog.png b/intro/matplotlib/figures/loglog.png deleted file mode 100644 index 851e44f..0000000 Binary files a/intro/matplotlib/figures/loglog.png and /dev/null differ diff --git a/intro/matplotlib/figures/pie.png b/intro/matplotlib/figures/pie.png deleted file mode 100644 index 07c2e13..0000000 Binary files a/intro/matplotlib/figures/pie.png and /dev/null differ diff --git a/intro/matplotlib/figures/polar.png b/intro/matplotlib/figures/polar.png deleted file mode 100644 index 37f0eae..0000000 Binary files a/intro/matplotlib/figures/polar.png and /dev/null differ diff --git a/intro/matplotlib/figures/quiver.png b/intro/matplotlib/figures/quiver.png deleted file mode 100644 index 0fa395b..0000000 Binary files a/intro/matplotlib/figures/quiver.png and /dev/null differ diff --git a/intro/matplotlib/figures/scatter.png b/intro/matplotlib/figures/scatter.png deleted file mode 100644 index 6a34f35..0000000 Binary files a/intro/matplotlib/figures/scatter.png and /dev/null differ diff --git a/intro/matplotlib/figures/simple.png b/intro/matplotlib/figures/simple.png deleted file mode 100644 index 2dcab92..0000000 Binary files a/intro/matplotlib/figures/simple.png and /dev/null differ diff --git a/intro/matplotlib/figures/spy.png b/intro/matplotlib/figures/spy.png deleted file mode 100644 index 1790904..0000000 Binary files a/intro/matplotlib/figures/spy.png and /dev/null differ diff --git a/intro/matplotlib/figures/stem.png b/intro/matplotlib/figures/stem.png deleted file mode 100644 index 637976d..0000000 Binary files a/intro/matplotlib/figures/stem.png and /dev/null differ diff --git a/intro/matplotlib/figures/subplots_four.png b/intro/matplotlib/figures/subplots_four.png deleted file mode 100644 index d087273..0000000 Binary files a/intro/matplotlib/figures/subplots_four.png and /dev/null differ diff --git a/intro/matplotlib/figures/subplots_horizontal.png b/intro/matplotlib/figures/subplots_horizontal.png deleted file mode 100644 index fde5b26..0000000 Binary files a/intro/matplotlib/figures/subplots_horizontal.png and /dev/null differ diff --git a/intro/matplotlib/figures/subplots_vertical.png b/intro/matplotlib/figures/subplots_vertical.png deleted file mode 100644 index d8d36d9..0000000 Binary files a/intro/matplotlib/figures/subplots_vertical.png and /dev/null differ diff --git a/intro/matplotlib/figures/text.png b/intro/matplotlib/figures/text.png deleted file mode 100644 index 4c982f3..0000000 Binary files a/intro/matplotlib/figures/text.png and /dev/null differ diff --git a/intro/matplotlib/figures/ticks.png b/intro/matplotlib/figures/ticks.png deleted file mode 100644 index c0e8047..0000000 Binary files a/intro/matplotlib/figures/ticks.png and /dev/null differ diff --git a/intro/matplotlib/matplotlib.rst b/intro/matplotlib/matplotlib.rst index 61c0c70..f4971cb 100644 --- a/intro/matplotlib/matplotlib.rst +++ b/intro/matplotlib/matplotlib.rst @@ -1,106 +1,97 @@ -.. _matplotlib: +.. currentmodule:: matplotlib -==================== -Matplotlib: plotting -==================== +.. _matplotlib-label: -:authors: Nicolas Rougier, Mike Müller, Gaël Varoquaux +================================= +Matplotlib: Gráficas usando pylab +================================= -.. sidebar:: **Thanks** +:Autores: Nicolas Rougier, Mike Müller, Gaël Varoquaux - Many thanks to **Bill Wing** and **Christoph Deil** for review and - corrections. +.. sidebar:: **Agradecimientos** -.. contents:: Chapters contents + Muchas gracias a **Bill Wing** y **Christoph Deil** por revisar y corregir. + +.. contents:: Contenido :local: :depth: 2 -Introduction +Introducción ============ -matplotlib is probably the single most used Python package for 2D-graphics. It -provides both a very quick way to visualize data from Python and -publication-quality figures in many formats. We are going to explore -matplotlib in interactive mode covering most common cases. +Matplotlib es probablemente el paquete de Python más utilizado para gráficos 2D. Proporciona una manera muy rápida de visualizar datos y figuras con calidad de publicación en varios formatos. Vamos a explorar Matplotlib en modo interactivo cubriendo los casos más comunes. -IPython and the pylab mode --------------------------- +IPython y el modo pylab +----------------------- -`IPython `_ is an enhanced interactive Python shell that -has lots of interesting features including named inputs and outputs, access to -shell commands, improved debugging and many more. When we start it with the -command line argument -pylab (--pylab since IPython version 0.12), it allows -interactive matplotlib sessions that have Matlab/Mathematica-like functionality. +`IPython `_ es un shell interactivo mejorado de Python que +tiene un montón de características interesantes, incluyendo entradas y salidas con nombre, el acceso a comandos de la shell, la mejora de depuración y mucho más. Cuando se inicia con el argumento -pylab en la ventana de comandos (--pylab desde la versión IPython 0.12), permite sesiones interactivas Matplotlib que tienen la misma funcionalidad que Matlab/Mathematica. pylab ----- -pylab provides a procedural interface to the matplotlib object-oriented -plotting library. It is modeled closely after Matlab(TM). Therefore, the -majority of plotting commands in pylab have Matlab(TM) analogs with similar -arguments. Important commands are explained with interactive examples. - +pylab proporciona una interfaz orientada a objetos a la biblioteca de trazado Matplotlib cercano a Matlab(TM). Por tanto, la mayoría de los comandos de trazado en pylab tiene análogos Matlab(TM) con similares argumentos. Comandos importantes se explican con ejemplos interactivos. -Simple plot -=========== +Gráfica simple +============== -In this section, we want to draw the cosine and sine functions on the same -plot. Starting from the default settings, we'll enrich the figure step by step -to make it nicer. +En esta sección, llamaremos a las funciones seno y coseno en la misma gráfica. A partir de la configuración por defecto, vamos a enriquecer la figura paso a paso para que sea más agradable. -First step is to get the data for the sine and cosine functions: +El primer paso es obtener los datos para las funciones seno y coseno -:: +.. code-block:: python import numpy as np X = np.linspace(-np.pi, np.pi, 256, endpoint=True) + C, S = np.cos(X), np.sin(X) +X es ahora un arreglo numpy con 256 valores que van desde -π a +π (incluido). C es la función coseno (256 valores) y S es la función seno (256 valores). -X is now a numpy array with 256 values ranging from -π to +π (included). C is -the cosine (256 values) and S is the sine (256 values). +Para ejecutar el ejemplo, teclee los comandos en una sesión interactiva IPython -To run the example, you can type them in an IPython interactive session:: +.. sourcecode:: bash - $ ipython --pylab + $ ipython --pylab -This brings us to the IPython prompt: :: +Esto nos lleva a el shell IPython - IPython 0.13 -- An enhanced Interactive Python. - ? -> Introduction to IPython's features. - %magic -> Information about IPython's 'magic' % functions. - help -> Python's own help system. - object? -> Details about 'object'. ?object also works, ?? prints more. - - Welcome to pylab, a matplotlib-based Python environment. - For more information, type 'help(pylab)'. +.. sourcecode:: bash + IPython 0.13 -- An enhanced Interactive Python. + ? -> Introduction to IPython's features. + %magic -> Information about IPython's 'magic' % functions. + help -> Python's own help system. + object? -> Details about 'object'. ?object also works, ?? prints more. + + Welcome to pylab, a matplotlib-based Python environment. + For more information, type 'help(pylab)'. -or you can download each of the examples and run it using regular python:: +o puede descargar cada uno de los ejemplos y ejecutarlo usando el intérprete estandar python - $ python exercice_1.py +.. sourcecode:: bash -You can get source for each step by clicking on the corresponding figure. + $ python exercice_1.py +Usted puede obtener el código para cada paso haciendo clic en la figura correspondiente. -Using defaults --------------- +Valores por defecto +------------------- .. image:: auto_examples/images/plot_exercice_1_1.png :align: right :scale: 35 :target: auto_examples/plot_exercice_1.html -.. hint:: Documentation +.. hint:: Documentación - * `plot tutorial `_ - * `plot() command `_ + * `Tutorial pyplot `_ + * `Comando plot() `_ -Matplotlib comes with a set of default settings that allow customizing all -kinds of properties. You can control the defaults of almost every property in -matplotlib: figure size and dpi, line width, color and style, axes, axis and -grid properties, text and font properties and so on. :: +Matplotlib viene con un conjunto de valores predeterminados que permiten la personalización de todos los tipos de propiedades. Puede controlar los valores predeterminados de casi todas las propiedades en matplotlib: tamaño de figura y dpi, grosor de línea, color y estilo, ejes , ejes y propiedades de cuadrícula, propiedades de texto y fuente, etc. + +.. code-block:: python import pylab as pl import numpy as np @@ -113,8 +104,7 @@ grid properties, text and font properties and so on. :: pl.show() - -Instantiating defaults +Instancias por defecto ---------------------- .. image:: auto_examples/images/plot_exercice_2_1.png @@ -122,68 +112,67 @@ Instantiating defaults :scale: 35 :target: auto_examples/plot_exercice_2.html -.. hint:: Documentation +.. hint:: Documentación - * `Customizing matplotlib `_ + * `Personalizando matplotlib `_ -In the script below, we've instantiated (and commented) all the figure settings -that influence the appearance of the plot. The settings have been explicitly -set to their default values, but now you can interactively play with the values -to explore their affect (see `Line properties`_ and `Line styles`_ below). :: +En el siguiente script, hemos creado una instancia (y comentamos) todos los ajustes de la figura que influyen en la aparición del gráfico. Los ajustes son explícitos para configurar los valores predeterminados, pero usted puede jugar interactivamente con los valores para explorar su efecto (ver `Line properties`_ y `Line styles`_ más abajo). + +.. code-block:: python import pylab as pl import numpy as np - # Create a figure of size 8x6 points, 80 dots per inch + # Crear una figura de 8x6 puntos de tamaño, 80 puntos por pulgada pl.figure(figsize=(8, 6), dpi=80) - # Create a new subplot from a grid of 1x1 + # Crear una nueva subgráfica en una rejilla de 1x1 pl.subplot(1, 1, 1) X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) - # Plot cosine with a blue continuous line of width 1 (pixels) + # Graficar la función coseno con una línea continua azul de 1 pixel de grosor pl.plot(X, C, color="blue", linewidth=1.0, linestyle="-") - # Plot sine with a green continuous line of width 1 (pixels) + # Graficar la función coseno con una línea continua verde de 1 pixel de grosor pl.plot(X, S, color="green", linewidth=1.0, linestyle="-") - # Set x limits + # Establecer límites del eje x pl.xlim(-4.0, 4.0) - # Set x ticks + # Ticks en x pl.xticks(np.linspace(-4, 4, 9, endpoint=True)) - # Set y limits + # Establecer límites del eje y pl.ylim(-1.0, 1.0) - # Set y ticks + # Ticks en y pl.yticks(np.linspace(-1, 1, 5, endpoint=True)) - # Save figure using 72 dots per inch + # Guardar la figura usando 72 puntos por pulgada # savefig("exercice_2.png", dpi=72) - # Show result on screen + # Mostrar resultado en pantalla pl.show() - -Changing colors and line widths --------------------------------- +Cambiar colores y grosor de línea +--------------------------------- .. image:: auto_examples/images/plot_exercice_3_1.png :align: right :scale: 35 :target: auto_examples/plot_exercice_3.html -.. hint:: Documentation +.. hint:: Documentación + + * `Controlando propiedades de línea `_ + * `API línea `_ - * `Controlling line properties `_ - * `Line API `_ +Primer paso, queremos mostrar la función coseno en azul, la función seno en rojo y un +línea ligeramente más gruesa para ambas funciones. También vamos a modificar el tamaño para que sea ligeramente más horizontal. -First step, we want to have the cosine in blue and the sine in red and a -slighty thicker line for both of them. We'll also slightly alter the figure -size to make it more horizontal. :: +.. code-block:: python ... pl.figure(figsize=(10, 6), dpi=80) @@ -191,87 +180,72 @@ size to make it more horizontal. :: pl.plot(X, S, color="red", linewidth=2.5, linestyle="-") ... - -Setting limits --------------- +Establecer límites +------------------ .. image:: auto_examples/images/plot_exercice_4_1.png :align: right :scale: 35 :target: auto_examples/plot_exercice_4.html -.. hint:: Documentation +.. hint:: Documentación - * `xlim() command `_ - * `ylim() command `_ + * `Comando xlim() `_ + * `Comando ylim() `_ +Debido a los límites actuales la figura se muestra un poco ajustada, cambiamos los límites con el fin de ver con claridad todos los puntos. -Current limits of the figure are a bit too tight and we want to make some space -in order to clearly see all data points. - -:: +.. code-block:: python ... pl.xlim(X.min() * 1.1, X.max() * 1.1) pl.ylim(C.min() * 1.1, C.max() * 1.1) ... - - -Setting ticks -------------- +Configurando graduación de ejes +------------------------------- .. image:: auto_examples/images/plot_exercice_5_1.png :align: right :scale: 35 :target: auto_examples/plot_exercice_5.html -.. hint:: Documentation +.. hint:: Documentación - * `xticks() command `_ - * `yticks() command `_ + * `Comando xticks() `_ + * `Comando yticks() `_ * `Tick container `_ * `Tick locating and formatting `_ +Los graduación actual no es ideal, ya que no muestran los valores requeridos +(+/-π,+/-π/2) para la función seno y la función coseno. Los cambiamos de tal manera que sólo muestren estos valores. -Current ticks are not ideal because they do not show the interesting values -(+/-π,+/-π/2) for sine and cosine. We'll change them such that they show only -these values. - -:: +.. code-block:: python ... pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) pl.yticks([-1, 0, +1]) ... - - -Setting tick labels -------------------- +Configurando etiquetas graduadas +-------------------------------- .. image:: auto_examples/images/plot_exercice_6_1.png :align: right :scale: 35 :target: auto_examples/plot_exercice_6.html +.. hint:: Documentación -.. hint:: Documentation - - * `Working with text `_ - * `xticks() command `_ - * `yticks() command `_ + * `Trabajando con texto `_ + * `Comando xticks() `_ + * `Comando yticks() `_ * `set_xticklabels() `_ * `set_yticklabels() `_ +Las graduaciones están correctamente colocadas, pero su etiqueta no es muy explícita. Podríamos suponer que 3.142 es π pero es mejor hacerlo de forma explícita. Cuando establecemos los valores de graduación, también podemos proporcionar una etiqueta correspondiente en el segundo argumento de la lista. Tenga en cuenta que vamos a utilizar látex para permitir una buena renderización de la etiqueta. -Ticks are now properly placed but their label is not very explicit. We could -guess that 3.142 is π but it would be better to make it explicit. When we set -tick values, we can also provide a corresponding label in the second argument -list. Note that we'll use latex to allow for nice rendering of the label. - - -:: +.. code-block:: python ... pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], @@ -281,31 +255,23 @@ list. Note that we'll use latex to allow for nice rendering of the label. [r'$-1$', r'$0$', r'$+1$']) ... - - -Moving spines -------------- +Moviendo spines +--------------- .. image:: auto_examples/images/plot_exercice_7_1.png :align: right :scale: 35 :target: auto_examples/plot_exercice_7.html - -.. hint:: Documentation +.. hint:: Documentación * `Spines `_ * `Axis container `_ * `Transformations tutorial `_ -Spines are the lines connecting the axis tick marks and noting the boundaries -of the data area. They can be placed at arbitrary positions and until now, they -were on the border of the axis. We'll change that since we want to have them in -the middle. Since there are four of them (top/bottom/left/right), we'll discard -the top and right by setting their color to none and we'll move the bottom and -left ones to coordinate 0 in data space coordinates. +Los spines son las líneas que unen las marcas de graduación del eje y muestran los límites de datos. Se pueden colocar en posiciones arbitrarias, hasta ahora estaban en el borde del eje. Vamos a cambiar eso, ya que queremos tener en el medio. Puesto que hay cuatro de ellos (arriba/abajo/izquierda/derecha), vamos a descartar la parte superior y derecha al establecer su color a ninguno y vamos a mover la parte inferior y la izquierdas para coordinar 0 en las coordenadas de datos. -:: +.. code-block:: python ... ax = pl.gca() # gca stands for 'get current axis' @@ -317,10 +283,8 @@ left ones to coordinate 0 in data space coordinates. ax.spines['left'].set_position(('data',0)) ... - - -Adding a legend ---------------- +Agregando una leyenda +--------------------- .. image:: auto_examples/images/plot_exercice_8_1.png :align: right @@ -328,18 +292,15 @@ Adding a legend :target: auto_examples/plot_exercice_8.html -.. hint:: Documentation +.. hint:: Documentación * `Legend guide `_ * `legend() command `_ * `Legend API `_ -Let's add a legend in the upper left corner. This only requires adding the -keyword argument label (that will be used in the legend box) to the plot -commands. +Vamos a añadir una leyenda en la esquina superior izquierda. Esto sólo requiere la adición de la palabra clave label (que se utilizará en el cuadro de la leyenda) en el comando plot. - -:: +.. code-block:: python ... pl.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") @@ -348,29 +309,23 @@ commands. pl.legend(loc='upper left') ... - - -Annotate some points --------------------- +Anotaciones en puntos +--------------------- .. image:: auto_examples/images/plot_exercice_9_1.png :align: right :scale: 35 :target: auto_examples/plot_exercice_9.html - -.. hint:: Documentation +.. hint:: Documentación * `Annotating axis `_ * `annotate() command `_ -Let's annotate some interesting points using the annotate command. We chose the -2π/3 value and we want to annotate both the sine and the cosine. We'll first -draw a marker on the curve as well as a straight dotted line. Then, we'll use -the annotate command to display some text with an arrow. - +Vamos a anotar algunos puntos interesantes utilizando el comando de annotate. Elegimos el valor 2π/3 y queremos anotar tanto en la función seno y el coseno. Haremos primero +dibujar un marcador en la curva, así como una línea de puntos recta. A continuación, vamos a utilizar el comando annotate que muestra parte del texto con una flecha. -:: +.. code-block:: python ... @@ -392,8 +347,6 @@ the annotate command to display some text with an arrow. arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) ... - - Devil is in the details ------------------------ @@ -402,18 +355,16 @@ Devil is in the details :scale: 35 :target: auto_examples/plot_exercice_10_1.html -.. hint:: Documentation +.. hint:: Documentación * `Artists `_ * `BBox `_ -The tick labels are now hardly visible because of the blue and red lines. We can -make them bigger and we can also adjust their properties such that they'll be -rendered on a semi-transparent white background. This will allow us to see both -the data and the labels. +Las etiquetas graduadas ahora son apenas visibles debido a las líneas azules y rojas. Podemos hacerlos más grandes y también podemos ajustar sus propiedades, que van a estar +renderizados en un fondo blanco semi-transparente. Esto nos permitirá ver tanto +los datos y las etiquetas. - -:: +.. code-block:: python ... for label in ax.get_xticklabels() + ax.get_yticklabels(): @@ -421,62 +372,37 @@ the data and the labels. label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65)) ... - - - -Figures, Subplots, Axes and Ticks +Figuras, Subplots, Axes y Ticks ================================= -So far we have used implicit figure and axes creation. This is handy for fast -plots. We can have more control over the display using figure, subplot, and -axes explicitly. A figure in matplotlib means the whole window in the user -interface. Within this figure there can be subplots. While subplot positions -the plots in a regular grid, axes allows free placement within the figure. Both -can be useful depending on your intention. We've already worked with figures -and subplots without explicitly calling them. When we call plot, matplotlib -calls gca() to get the current axes and gca in turn calls gcf() to get the -current figure. If there is none it calls figure() to make one, strictly -speaking, to make a subplot(111). Let's look at the details. - -Figures -------- +Hasta ahora hemos utilizado implícitamente la creación de ejes y figuras. Esto es útil para hacer gráficas rápidas. Podemos tener más control sobre la figura, subplots y ejes explícitamente. Una figura en matplotlib significa toda la ventana en la interfaz de usuario. Dentro de esta figura no pueden haber subplots . Mientras que las posiciones de los subplots en una cuadrícula regular, permite la colocación libre de ejes dentro de la figura. Ambos puede ser útiles dependiendo de su intención. Ya hemos trabajado con figuras y subplots sin llamarlos explícitamente. Cuando llamamos a un gráfico, matplotlib llama a gca() para obtener los ejes actuales y gca a su vez llama a gcf() para obtener la figura actual. Si no hay ninguna figure() es llamada para hacer una, hablando estrictamente, se hace un subplot(111). Echemos un vistazo a los detalles. -A figure is the windows in the GUI that has "Figure #" as title. Figures -are numbered starting from 1 as opposed to the normal Python way starting -from 0. This is clearly MATLAB-style. There are several parameters that -determine what the figure looks like: +Figuras +------- -============== ======================= ============================================ -Argument Default Description -============== ======================= ============================================ -num 1 number of figure -figsize figure.figsize figure size in in inches (width, height) -dpi figure.dpi resolution in dots per inch -facecolor figure.facecolor color of the drawing background -edgecolor figure.edgecolor color of edge around the drawing background -frameon True draw figure frame or not -============== ======================= ============================================ +Una figura es una ventana(s) en el GUI con título "Figure #". Las figuras están numeradas a partir de 1, esto es claramente un 'estilo' MATLAB. Existen varios parámetros que determinar que la figura se vea así: -The defaults can be specified in the resource file and will be used most of the -time. Only the number of the figure is frequently changed. +============== ======================= ============================================== +Argumento Por defecto Descripción +============== ======================= ============================================== +num 1 número de figura +figsize figure.figsize tamaño de figura en pulgadas (ancho, alto) +dpi figure.dpi resolución en puntos por pulgada +facecolor figure.facecolor color de fondo del dibujo +edgecolor figure.edgecolor color del borde alrededor del fondo del dibujo +frameon True dibujar figura en marcos o no +============== ======================= ============================================== -When you work with the GUI you can close a figure by clicking on the x in the -upper right corner. But you can close a figure programmatically by calling -close. Depending on the argument it closes (1) the current figure (no -argument), (2) a specific figure (figure number or figure instance as -argument), or (3) all figures (all as argument). +Los valores por defecto se pueden especificar en el archivo de recursos y se utilizará la mayor parte del tiempo. Sólo el número de la figura se cambia con frecuencia. -As with other objects, you can set figure properties also setp or with the -set_something methods. +Cuando se trabaja con la interfaz gráfica de usuario se puede cerrar una figura haciendo clic en la X de la esquina superior derecha. Sin embargo, se puede cerrar una figura llamando a close. Según el argumento para cerrar (1) la figura actual (sin argumento) , (2) una figura específica (número de la figura o instancia de figura es argumento ), o (3) todas las figuras (all es argumento). +Al igual que con otros objetos, también se puede establecer las propiedades de la figura con setp o con el método set_something. Subplots -------- -With subplot you can arrange plots in a regular grid. You need to specify the -number of rows and columns and the number of the plot. Note that the `gridspec -`_ command is a more -powerful alternative. +Con subplot puede organizar gráficas en una cuadrícula regular. Es necesario especificar el número de filas, columnas y el número del gráfico. Tenga en cuenta que el comando `gridspec `_ es una alternativa más poderosa. .. image:: auto_examples/images/plot_subplot-horizontal_1.png :scale: 28 @@ -491,13 +417,10 @@ powerful alternative. :scale: 28 :target: auto_examples/plot_gridspec.html +Ejes (axes) +----------- -Axes ----- - -Axes are very similar to subplots but allow placement of plots at any location -in the figure. So if we want to put a smaller plot inside a bigger one we do -so with axes. +Los ejes son muy similares a los subplots, permiten colocar gráficos en cualquier ubicación en la figura. Así que si queremos poner un gráfico pequeño dentro de uno más grande con los mismos ejes. .. image:: auto_examples/images/plot_axes_1.png :scale: 35 @@ -506,42 +429,35 @@ so with axes. :scale: 35 :target: auto_examples/plot_axes-2.html +Graduaciones (ticks) +-------------------- -Ticks ------ +Las graduaciones con formato son una parte importante de los gráficos listos para publicar. Matplotlib ofrece un sistema totalmente configurable para graduaciones. Hay +graduaciones localizadoras para especificar dónde deben aparecer las graduaciones y graduaciones con formato para dar el aspecto que desea a las graduaciones. Las graduaciones mayores y menores puede ser localizadas y formateadas de forma independiente el uno del otro. Por defecto no se muestra la graduación menor, +es decir, sólo hay una lista vacía de ellos, ya que estan con NullLocator (ver +a continuación). -Well formatted ticks are an important part of publishing-ready -figures. Matplotlib provides a totally configurable system for ticks. There are -tick locators to specify where ticks should appear and tick formatters to give -ticks the appearance you want. Major and minor ticks can be located and -formatted independently from each other. Per default minor ticks are not shown, -i.e. there is only an empty list for them because it is as NullLocator (see -below). +Localizadoras de graduación (tick locators) +........................................... -Tick Locators -............. +Las localizadoras de graduación controlan las posiciones de las graduaciones. Ellas se establecen como -Tick locators control the positions of the ticks. They are set as -follows:: +.. code-block:: python - ax = pl.gca() - ax.xaxis.set_major_locator(eval(locator)) + ax = pl.gca() + ax.xaxis.set_major_locator(eval(locator)) -There are several locators for different kind of requirements: +Hay varios localizadores para diferentes tipos de requerimientos: .. image:: auto_examples/images/plot_ticks_1.png - :scale: 60 - :target: auto_examples/plot_ticks.html + :scale: 60 + :target: auto_examples/plot_ticks.html +Todos estos localizadores derivan de la clase base matplotlib.ticker.Locator. +Usted puede hacer su propio localizador derivandola de la clase base. Manipulación de fechas con graduaciones puede ser especialmente difícil. Por lo tanto, matplotlib proporciona localizadores especiales en matplotlib.dates. -All of these locators derive from the base class matplotlib.ticker.Locator. -You can make your own locator deriving from it. Handling dates as ticks can be -especially tricky. Therefore, matplotlib provides special locators in -matplotlib.dates. - - -Other Types of Plots: examples and exercises -============================================= +Otros tipos de gráficos: ejemplos y ejercicios +============================================== .. image:: auto_examples/images/plot_plot_1.png :scale: 39 @@ -580,23 +496,20 @@ Other Types of Plots: examples and exercises :scale: 39 :target: `Text`_ - -Regular Plots -------------- +Gráficos regulares +------------------ .. image:: auto_examples/images/plot_plot_ex_1.png :align: right :scale: 35 :target: auto_examples/plot_plot_ex.html -.. hint:: +.. hint:: Es necesario utilizar el comando `fill_between `_. - You need to use the `fill_between - `_ - command. +A partir del código de abajo, trate de reproducir el gráfico en forma correcta +tomando en cuenta las zonas rellenadas -Starting from the code below, try to reproduce the graphic on the right taking -care of filled areas:: +.. code-block:: python n = 256 X = np.linspace(-np.pi, np.pi, n, endpoint=True) @@ -605,26 +518,22 @@ care of filled areas:: pl.plot(X, Y + 1, color='blue', alpha=1.00) pl.plot(X, Y - 1, color='blue', alpha=1.00) -Click on the figure for solution. +Haga clic en la figura para la solución. - -Scatter Plots -------------- +Gráficos de dispersión (scatter) +-------------------------------- .. image:: auto_examples/images/plot_scatter_ex_1.png :align: right :scale: 35 :target: auto_examples/plot_scatter_ex.html -.. hint:: - - Color is given by angle of (X,Y). - +.. hint:: Color está dado por el ángulo de (X, Y). -Starting from the code below, try to reproduce the graphic on the right taking -care of marker size, color and transparency. +A partir del código de abajo, trate de reproducir el gráfico en forma correcta +tomando en cuenta el tamaño de marcas, el color y la transparencia. -:: +.. code-block:: python n = 1024 X = np.random.normal(0,1,n) @@ -632,26 +541,22 @@ care of marker size, color and transparency. pl.scatter(X,Y) -Click on figure for solution. +Haga clic en la figura para la solución. - -Bar Plots ---------- +Gráfico de barras (bar) +----------------------- .. image:: auto_examples/images/plot_bar_ex_1.png :align: right :scale: 35 :target: auto_examples/plot_bar_ex.html -.. hint:: - - You need to take care of text alignment. +.. hint:: Tomar en cuenta la alineación del texto. +A partir del código de abajo, trate de reproducir el gráfico en forma correcta +agregando etiquetas en las barras rojas. -Starting from the code below, try to reproduce the graphic on the right by -adding labels for red bars. - -:: +.. code-block:: python n = 12 X = np.arange(n) @@ -666,28 +571,22 @@ adding labels for red bars. pl.ylim(-1.25, +1.25) -Click on figure for solution. - +Haga clic en la figura para la solución. -Contour Plots -------------- +Gráficos de contorno +-------------------- .. image:: auto_examples/images/plot_contour_ex_1.png :align: right :scale: 35 :target: auto_examples/plot_contour_ex.html +.. hint:: Es necesario utilizar el comando `clabel `_. -.. hint:: - - You need to use the `clabel - `_ - command. +A partir del código de abajo, trate de reproducir el gráfico en forma correcta +tomando en cuneta el colormap (ver `Colormaps`_ más abajo). -Starting from the code below, try to reproduce the graphic on the right taking -care of the colormap (see `Colormaps`_ below). - -:: +.. code-block:: python def f(x, y): return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2) @@ -700,9 +599,7 @@ care of the colormap (see `Colormaps`_ below). pl.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet') C = pl.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5) -Click on figure for solution. - - +Haga clic en la figura para la solución. Imshow ------ @@ -712,18 +609,12 @@ Imshow :scale: 35 :target: auto_examples/plot_imshow_ex.html +.. hint:: Necesita tomar en cuenta el ``origin`` de la imagen en el comando imshow y usar un `colorbar `_. -.. hint:: - - You need to take care of the ``origin`` of the image in the imshow command and - use a `colorbar - `_ +A partir del código de abajo, trate de reproducir el gráfico en forma correcta +teniendo en cuenta el colormap, interpolación de imágenes y el origen. - -Starting from the code below, try to reproduce the graphic on the right taking -care of colormap, image interpolation and origin. - -:: +.. code-block:: python def f(x, y): return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) @@ -734,8 +625,7 @@ care of colormap, image interpolation and origin. X, Y = np.meshgrid(x, y) pl.imshow(f(X, Y)) -Click on the figure for the solution. - +Haga clic en la figura para la solución. Pie Charts ---------- @@ -745,22 +635,17 @@ Pie Charts :scale: 35 :target: auto_examples/plot_pie_ex.html +.. hint:: Debe modificar Z. -.. hint:: - - You need to modify Z. +A partir del código de abajo, trate de reproducir el gráfico en forma correcta +tomando en cuenta los colores y el tamaño de divisiones. -Starting from the code below, try to reproduce the graphic on the right taking -care of colors and slices size. - -:: +.. code-block:: python Z = np.random.uniform(0, 1, 20) pl.pie(Z) -Click on the figure for the solution. - - +Haga clic en la figura para la solución. Quiver Plots ------------ @@ -770,36 +655,31 @@ Quiver Plots :scale: 35 :target: auto_examples/plot_quiver_ex.html +.. hint:: Tienes que dibujar las flechas dos veces. -.. hint:: - - You need to draw arrows twice. +A partir del código anterior, intente reproducir el gráfico en la toma correcta +tomando en cuenta los colores y direcciones. -Starting from the code above, try to reproduce the graphic on the right taking -care of colors and orientations. - -:: +.. code-block:: python n = 8 X, Y = np.mgrid[0:n, 0:n] pl.quiver(X, Y) -Click on figure for solution. - +Haga clic en la figura para la solución. -Grids ------ +Cuadrículas (grids) +------------------- .. image:: auto_examples/images/plot_grid_ex_1.png :align: right :scale: 35 :target: auto_examples/plot_grid_ex.html +A partir del código anterior, intente reproducir el gráfico en la toma correcta +tomando en cuenta los estilos de línea. -Starting from the code below, try to reproduce the graphic on the right taking -care of line styles. - -:: +.. code-block:: python axes = pl.gca() axes.set_xlim(0, 4) @@ -807,51 +687,41 @@ care of line styles. axes.set_xticklabels([]) axes.set_yticklabels([]) +Haga clic en la figura para la solución. -Click on figure for solution. - - -Multi Plots ------------ +Gráficos múltiples +------------------ .. image:: auto_examples/images/plot_multiplot_ex_1.png :align: right :scale: 35 :target: auto_examples/plot_multiplot_ex.html -.. hint:: - - You can use several subplots with different partition. +.. hint:: Puede utilizar varios subplots con diferentes particiones. +A partir del código de abajo, intente reproducir el gráfico de la derecha. -Starting from the code below, try to reproduce the graphic on the right. - -:: +.. code-block:: python pl.subplot(2, 2, 1) pl.subplot(2, 2, 3) pl.subplot(2, 2, 4) -Click on figure for solution. - +Haga clic en la figura para la solución. -Polar Axis ----------- +Ejes polares +------------ .. image:: auto_examples/images/plot_polar_ex_1.png :align: right :scale: 35 :target: auto_examples/plot_polar_ex.html +.. hint:: Tiene que modificar la línea ``axes`` -.. hint:: - - You only need to modify the ``axes`` line +A partir del código de abajo, intente reproducir el gráfico de la derecha. - -Starting from the code below, try to reproduce the graphic on the right. - -:: +.. code-block:: python pl.axes([0, 0, 1, 1]) @@ -865,27 +735,21 @@ Starting from the code below, try to reproduce the graphic on the right. bar.set_facecolor(cm.jet(r / 10.)) bar.set_alpha(0.5) -Click on figure for solution. +Haga clic en la figura para la solución. - -3D Plots --------- +Gráficos 3D +----------- .. image:: auto_examples/images/plot_plot3d_ex_1.png :align: right :scale: 35 :target: auto_examples/plot_plot3d_ex.html +.. hint:: Debe usar `contourf `_ -.. hint:: - - You need to use `contourf - `_ - - -Starting from the code below, try to reproduce the graphic on the right. +A partir del código de abajo, intente reproducir el gráfico de la derecha. -:: +.. code-block:: python from mpl_toolkits.mplot3d import Axes3D @@ -899,38 +763,32 @@ Starting from the code below, try to reproduce the graphic on the right. ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot') -Click on figure for solution. +Haga clic en la figura para la solución. .. seealso:: :ref:`mayavi-label` -Text ----- - +Texto +----- .. image:: auto_examples/images/plot_text_ex_1.png :align: right :scale: 35 :target: auto_examples/plot_text_ex.html +.. hint:: Echa un vistazo a `matplotlib logo `_. -.. hint:: - - Have a look at the `matplotlib logo - `_. - -Try to do the same from scratch ! +Trate de hacer lo mismo desde el principio ! -Click on figure for solution. +Haga clic en la figura para la solución. +Más allá de este tutorial +========================= -Beyond this tutorial -==================== +Matplotlib esta beneficiada con una extensa documentación, así como una gran +comunidad de usuarios y desarrolladores. Estos son algunos enlaces de interés: -Matplotlib benefits from extensive documentation as well as a large -community of users and developpers. Here are some links of interest: - -Tutorials ---------- +Tutoriales +---------- .. hlist:: @@ -981,9 +839,7 @@ Tutorials - Using offset transforms to create a shadow effect - The transformation pipeline - - -Matplotlib documentation +Documentación Matplotlib ------------------------ * `User guide `_ @@ -998,14 +854,13 @@ Matplotlib documentation * `Screenshots `_ +Código de documentación +----------------------- -Code documentation ------------------- - -The code is well documented and you can quickly access a specific command -from within a python session: +El código está bien documentado y se puede acceder rápidamente a un comando específico +dentro una sesión de python: -:: +.. code-block:: python >>> import pylab as pl >>> help(pl.plot) @@ -1027,49 +882,46 @@ from within a python session: will be plotted. ... -Galleries +Galerías --------- -The `matplotlib gallery `_ is -also incredibly useful when you search how to render a given graphic. Each -example comes with its source. - -A smaller gallery is also available `here `_. +La `galería matplotlib `_ es +muy útil cuando se busca la manera de hacer un gráfico dado. Cada +ejemplo viene con su código fuente. +Una galería más pequeña está disponible `aquí `_. -Mailing lists --------------- - -Finally, there is a `user mailing list -`_ where you can -ask for help and a `developers mailing list -`_ that is more -technical. - +Lista de correos +---------------- +Por último, hay una `lista de correo de usuarios +`_ donde se puede +pedir ayuda y una `lista de correo de desarrolladores +`_ que es más +técnica. -Quick references -================ +Referencias rápidas +=================== -Here is a set of tables that show main properties and styles. +Aquí hay una serie de cuadros que muestran las propiedades y estilos principales. -Line properties ----------------- +Propiedades de Línea +-------------------- .. list-table:: :widths: 20 30 50 :header-rows: 1 - * - Property - - Description - - Appearance + * - Propiedad + - Descripción + - Apariencia - * - alpha (or a) - - alpha transparency on 0-1 scale + * - alpha (o a) + - transparencia alpha en escala 0-1 - .. image:: auto_examples/images/plot_alpha_1.png * - antialiased - - True or False - use antialised rendering + - True o False - usar renderizado suavizado - .. image:: auto_examples/images/plot_aliased_1.png .. image:: auto_examples/images/plot_antialiased_1.png @@ -1077,11 +929,11 @@ Line properties - matplotlib color arg - .. image:: auto_examples/images/plot_color_1.png - * - linestyle (or ls) - - see `Line properties`_ + * - linestyle (o ls) + - ver `Line properties`_ - - * - linewidth (or lw) + * - linewidth (o lw) - float, the line width in points - .. image:: auto_examples/images/plot_linewidth_1.png @@ -1121,25 +973,23 @@ Line properties - size of the marker in points - .. image:: auto_examples/images/plot_ms_1.png - - -Line styles ------------ +Estilos de línea +---------------- .. image:: auto_examples/images/plot_linestyles_1.png -Markers -------- +Marcadores +---------- .. image:: auto_examples/images/plot_markers_1.png Colormaps --------- -All colormaps can be reversed by appending ``_r``. For instance, ``gray_r`` is -the reverse of ``gray``. +Todos los colormaps pueden invertirse añadiendo ``_r``. Por ejemplo, ``gray_r`` es +el inverso de ``gray``. -If you want to know more about colormaps, checks `Documenting the matplotlib +Si desea saber más acerca de colormaps, revise `Documenting the matplotlib colormaps `_. .. image:: auto_examples/images/plot_colormaps_1.png diff --git a/intro/numpy/advanced_operations.rst b/intro/numpy/advanced_operations.rst index 99d6bc5..34a435d 100644 --- a/intro/numpy/advanced_operations.rst +++ b/intro/numpy/advanced_operations.rst @@ -5,173 +5,183 @@ .. currentmodule:: numpy -Advanced operations -=================== +Operaciones avanzadas +===================== -.. contents:: Section contents +.. contents:: Contenido :local: :depth: 1 -Polynomials +Polinomios ----------- -Numpy also contains polynomials in different bases: +Numpy contiene polinomios en diferentes bases : -For example, :math:`3x^2 + 2x - 1` +Por ejemplo, :math:`3x^2 + 2x - 1` ->>> p = np.poly1d([3, 2, -1]) ->>> p(0) --1 ->>> p.roots -array([-1. , 0.33333333]) ->>> p.order -2 +.. code-block:: python ->>> x = np.linspace(0, 1, 20) ->>> y = np.cos(x) + 0.3*np.random.rand(20) ->>> p = np.poly1d(np.polyfit(x, y, 3)) + >>> p = np.poly1d([3, 2, -1]) + >>> p(0) + -1 + >>> p.roots + array([-1. , 0.33333333]) + >>> p.order + 2 ->>> t = np.linspace(0, 1, 200) ->>> plt.plot(x, y, 'o', t, p(t), '-') # doctest: +ELLIPSIS -[, ] +.. code-block:: python + + >>> x = np.linspace(0, 1, 20) + >>> y = np.cos(x) + 0.3*np.random.rand(20) + >>> p = np.poly1d(np.polyfit(x, y, 3)) + + >>> t = np.linspace(0, 1, 200) + >>> plt.plot(x, y, 'o', t, p(t), '-') # doctest: +ELLIPSIS + [, ] .. plot:: pyplots/numpy_intro_9.py -See http://docs.scipy.org/doc/numpy/reference/routines.polynomials.poly1d.html -for more. +Ver http://docs.scipy.org/doc/numpy/reference/routines.polynomials.poly1d.html +para más información. -More polynomials (with more bases) -................................... +Más polinomios (con más bases) +.............................. -Numpy also has a more sophisticated polynomial interface, which supports -e.g. the Chebyshev basis. +Numpy tiene una interfaz para polinomios más sofisticada , que soporta +por ejemplo bases de Chebyshev. :math:`3x^2 + 2x - 1` ->>> p = np.polynomial.Polynomial([-1, 2, 3]) # coefs in different order! ->>> p(0) --1.0 ->>> p.roots() -array([-1. , 0.33333333]) ->>> p.degree() # In general polynomials do not always expose 'order' -2 +.. code-block:: python + + >>> p = np.polynomial.Polynomial([-1, 2, 3]) # coeficientes en orden diferente! + >>> p(0) + -1.0 + >>> p.roots() + array([-1. , 0.33333333]) + >>> p.degree() # generalmente en polinomios no siempre muestra el 'orden' + 2 -Example using polynomials in Chebyshev basis, for polynomials in -range ``[-1, 1]``:: +Ejemplo de uso de polinomios en bases de Chebyshev, para polinomios en el rango ``[-1, 1]`` - >>> x = np.linspace(-1, 1, 2000) - >>> y = np.cos(x) + 0.3*np.random.rand(2000) - >>> p = np.polynomial.Chebyshev.fit(x, y, 90) +.. code-block:: python - >>> t = np.linspace(-1, 1, 200) - >>> plt.plot(x, y, 'r.') # doctest: +ELLIPSIS - [] - >>> plt.plot(t, p(t), 'k-', lw=3) # doctest: +ELLIPSIS - [] + >>> x = np.linspace(-1, 1, 2000) + >>> y = np.cos(x) + 0.3*np.random.rand(2000) + >>> p = np.polynomial.Chebyshev.fit(x, y, 90) + + >>> t = np.linspace(-1, 1, 200) + >>> plt.plot(x, y, 'r.') # doctest: +ELLIPSIS + [] + >>> plt.plot(t, p(t), 'k-', lw=3) # doctest: +ELLIPSIS + [] .. plot:: pyplots/numpy_intro_10.py -The Chebyshev polynomials have some advantages in interpolation. +Los polinomios de Chebyshev tienen algunas ventajas en interpolación. + +Cargando archivos de datos +-------------------------- -Loading data files -------------------- +Archivos de texto +................. -Text files -........... +Ejemplo: :download:`populations.txt <../../data/populations.txt>`: -Example: :download:`populations.txt <../../data/populations.txt>`:: +.. include:: ../../data/populations.txt + :end-line: 5 + :literal: - 1900 30e3 4e3 48300 - 1901 47.2e3 6.1e3 48200 - 1902 70.2e3 9.8e3 41500 - ... +.. code-block:: python -:: + >>> data = np.loadtxt('data/populations.txt') + >>> data # doctest: +ELLIPSIS + array([[ 1900., 30000., 4000., 48300.], + [ 1901., 47200., 6100., 48200.], + [ 1902., 70200., 9800., 41500.], + ... - >>> data = np.loadtxt('data/populations.txt') - >>> data # doctest: +ELLIPSIS - array([[ 1900., 30000., 4000., 48300.], - [ 1901., 47200., 6100., 48200.], - [ 1902., 70200., 9800., 41500.], - ... +.. code-block:: python - >>> np.savetxt('pop2.txt', data) - >>> data2 = np.loadtxt('pop2.txt') + >>> np.savetxt('pop2.txt', data) + >>> data2 = np.loadtxt('pop2.txt') -.. note:: If you have a complicated text file, what you can try are: +.. note:: Si usted tiene un archivo de texto complicado, puede probar con: - ``np.genfromtxt`` - - Using Python's I/O functions and e.g. regexps for parsing - (Python is quite well suited for this) + - Usar las funciones de E/S de Python, por ejemplo regexps para parsear (Python es bastante adecuado para esto) -.. topic:: Navigating the filesystem with *Ipython* +.. topic:: Recuerde: Navegando por el sistema de archivos con IPython .. sourcecode:: ipython - In [1]: pwd # show current directory - '/home/user/stuff/2011-numpy-tutorial' - In [2]: cd ex - '/home/user/stuff/2011-numpy-tutorial/ex' - In [3]: ls - populations.txt species.txt + In [1]: pwd # muestra el directorio actual + '/home/user/stuff/2011-numpy-tutorial' + In [2]: cd ex + '/home/user/stuff/2011-numpy-tutorial/ex' + In [3]: ls + populations.txt species.txt -Images -....... +Imágenes +........ -Using Matplotlib:: +Usando Matplotlib - >>> img = plt.imread('data/elephant.png') - >>> img.shape, img.dtype - ((200, 300, 3), dtype('float32')) - >>> plt.imshow(img) # doctest: +ELLIPSIS - - >>> plt.savefig('plot.png') +.. code-block:: python - >>> plt.imsave('red_elephant', img[:,:,0], cmap=plt.cm.gray) + >>> img = plt.imread('data/elephant.png') + >>> img.shape, img.dtype + ((200, 300, 3), dtype('float32')) + >>> plt.imshow(img) # doctest: +ELLIPSIS + + >>> plt.savefig('plot.png') -This saved only one channel (of RGB):: + >>> plt.imsave('red_elephant', img[:,:,0], cmap=plt.cm.gray) - >>> plt.imshow(plt.imread('red_elephant.png')) # doctest: +ELLIPSIS - +Esto guarda solo un canal (de RGB) -Other libraries:: +.. code-block:: python - >>> from scipy.misc import imsave - >>> imsave('tiny_elephant.png', img[::6,::6]) - >>> plt.imshow(plt.imread('tiny_elephant.png'), interpolation='nearest') # doctest: +ELLIPSIS - + >>> plt.imshow(plt.imread('red_elephant.png')) # doctest: +ELLIPSIS + + +Otras bibliotecas + +.. code-block:: python + + >>> from scipy.misc import imsave + >>> imsave('tiny_elephant.png', img[::6,::6]) + >>> plt.imshow(plt.imread('tiny_elephant.png'), interpolation='nearest') # doctest: +ELLIPSIS + .. plot:: pyplots/numpy_intro_3.py +Formato propio de Numpy +....................... -Numpy's own format -................... +Numpy tiene su propio formato binario, no es portátil pero con eficiente E/S -Numpy has its own binary format, not portable but with efficient I/O:: +.. code-block:: python - >>> data = np.ones((3, 3)) - >>> np.save('pop.npy', data) - >>> data3 = np.load('pop.npy') + >>> data = np.ones((3, 3)) + >>> np.save('pop.npy', data) + >>> data3 = np.load('pop.npy') -Well-known (& more obscure) file formats -......................................... +Formatos bien conocidos (y más obscuros) de archivo +................................................... * HDF5: `h5py `__, `PyTables `__ * NetCDF: ``scipy.io.netcdf_file``, `netcdf4-python `__, ... * Matlab: ``scipy.io.loadmat``, ``scipy.io.savemat`` * MatrixMarket: ``scipy.io.mmread``, ``scipy.io.mmread`` -... if somebody uses it, there's probably also a Python library for it. +... si alguien lo usa, es probable que haya una biblioteca de Python para ello. - -.. topic:: Exercise: Text data files +.. topic:: Ejercicio: Archivos de datos de texto :class: green - Write a Python script that loads data from :download:`populations.txt - <../../data/populations.txt>`:: and drop the last column and the first - 5 rows. Save the smaller dataset to ``pop2.txt``. - + Escribir un script en Python para cargar los datos de :download:`populations.txt <../../data/populations.txt>` y elimine la última columna y las primeras 5 filas. Guarde el pequeño conjunto de datos en ``pop2.txt``. .. loadtxt, savez, load, fromfile, tofile @@ -186,5 +196,7 @@ Well-known (& more obscure) file formats .. EXE: advanced: read the data in a PPM file +.. topic:: El interior de Numpy + Si está interesado en el funcionamiento interno de Numpy, hay una buena discusión en :ref:`advanced_numpy`. diff --git a/intro/numpy/array_object.rst b/intro/numpy/array_object.rst index 0152d0c..7f48a9a 100644 --- a/intro/numpy/array_object.rst +++ b/intro/numpy/array_object.rst @@ -1,112 +1,109 @@ -.. +.. >>> import numpy as np >>> np.random.seed(0) .. currentmodule:: numpy -The numpy array object -======================= +El objeto array numpy +===================== -.. contents:: Section contents +.. contents:: Contenido de la sección :local: :depth: 1 -What are Numpy and numpy arrays --------------------------------- +Que es Numpy y los array numpy +------------------------------ -**Python** has built-in: +:Objetos **Python**: - - containers: lists (costless insertion and append), dictionaries - (fast lookup) +- números objeto de alto nivel: enteros, de punto flotante - - high-level number objects: integers, floating point +- contenedores: listas (inserción y agregar elementos), diccionarios (búsqueda rápida) -**Numpy** is: +:**Numpy** dispone lo siguiente: - - extension package to Python for multi-dimensional arrays +- paquete de extensión Python para matrices multidimensionales - - closer to hardware (efficiency) +- cercano al hardware (eficiente) - - designed for scientific computation (convenience) +- diseñado para cálculo científico (conveniente) -:: - - >>> import numpy as np - >>> a = np.array([0, 1, 2, 3]) - >>> a - array([0, 1, 2, 3]) +.. code-block:: python -.. topic:: For example: + >>> import numpy as np + >>> a = np.array([0, 1, 2, 3]) + >>> a + array([0, 1, 2, 3]) - An array containing: +.. tip:: **Por ejemplo:** Una arreglo contiene: - * values of an experiment/simulation at discrete time steps + * valores de un experimento/simulación en intervalos de tiempo discreto - * signal recorded by a measurement device, e.g. sound wave + * señal grabada por un dispositivo de medición, por ejemplo, onda de sonido - * pixels of an image, grey-level or colour + * píxeles de una imagen en escala de grises o en color - * 3-D data measured at different X-Y-Z positions, e.g. MRI scan + * datos 3-D que miden diferentes posiciones XYZ, por ejemplo, imagen de resonancia magnética (MRI) - * ... + * ... -**Why it is useful:** Memory-efficient container that provides fast numerical -operations. +**Por qué es útil:** Los contenedores eficientes en memoria, proporcionan operaciones numéricas rápidas. .. sourcecode:: ipython - In [1]: l = range(1000) - - In [2]: %timeit [i**2 for i in l] - 1000 loops, best of 3: 403 us per loop - - In [3]: a = np.arange(1000) + In [1]: L = range(1000) - In [4]: %timeit a**2 - 100000 loops, best of 3: 12.7 us per loop + In [2]: %timeit [i**2 for i in L] + 1000 loops, best of 3: 73.8 us per loop + In [3]: a = np.arange(1000) -.. extension package to Python to support multidimensional arrays + In [4]: %timeit a**2 + 100000 loops, best of 3: 3.59 us per loop -.. diagram, import conventions +.. paquete de extensión Python con soporte de arreglos multidimensionales -.. scope of this tutorial: drill in features of array manipulation in - Python, and try to give some indication on how to get things done - in good style +.. diagramas, convenciones de importación -.. a fixed number of elements (cf. certain exceptions) -.. each element of same size and type -.. efficiency vs. Python lists +.. alcance de este tutorial: aprender a manipular arreglos en Python, y tratar de dar algunas indicaciones sobre la forma de hacer las cosas con un buen estilo -Reference documentation ------------------------ +.. un número fijo de elementos (por ejemplo, ciertas excepciones) +.. cada elemento del mismo tipo y tamaño +.. eficiencia vs listas Python -- On the web: http://docs.scipy.org/ +Documentación de referencia +--------------------------- -- Interactive help: +- En línea: http://docs.scipy.org/ - .. code-block:: python - - >>> help(np.array) # doctest: +ELLIPSIS - Help on built-in function array in module numpy.core.multiarray: - - array(...) - array(object, dtype=None, copy=True, order=None, subok=False, ... - ... +- Ayuda interactiva: .. sourcecode:: ipython In [5]: np.array? + Type: builtin_function_or_method String Form: Docstring: - array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0, ... + array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0) ... -- Looking for something: + .. tip:: + + .. code-block:: python + + >>> help(np.array) + Help on built-in function array in module numpy.core.multiarray: + + array(...) + array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0) + + ... + +- Por búsqueda: .. code-block:: python - >>> np.lookfor('create array') # doctest: +ELLIPSIS + >>> np.lookfor('create array') Search results for 'create array' --------------------------------- numpy.array @@ -124,71 +121,100 @@ Reference documentation np.convolve .. the import convention, reminder on python imports +.. la convención import, recuerdelo al importar en python -Creating arrays ---------------- +Convención para importar +------------------------ -**1-D**:: +La convención general para importar numpy es: - >>> a = np.array([0, 1, 2, 3]) - >>> a - array([0, 1, 2, 3]) - >>> a.ndim - 1 - >>> a.shape - (4,) - >>> len(a) - 4 +.. code-block:: python -**2-D, 3-D, ...**: + >>> import numpy as np -.. code-block:: python +El uso de este tipo de importación es recomendada. - >>> b = np.array([[0, 1, 2], [3, 4, 5]]) # 2 x 3 array - >>> b - array([[0, 1, 2], - [3, 4, 5]]) - >>> b.ndim - 2 - >>> b.shape - (2, 3) - >>> len(b) # returns the size of the first dimension - 2 - - >>> c = np.array([[[1], [2]], [[3], [4]]]) - >>> c - array([[[1], - [2]], - - [[3], - [4]]]) - >>> c.shape - (2, 2, 1) +Creando arreglos +---------------- + +* **1-D** -In practice, we rarely enter items one by one... + .. code-block:: python + + >>> a = np.array([0, 1, 2, 3]) + >>> a + array([0, 1, 2, 3]) + >>> a.ndim + 1 + >>> a.shape + (4,) + >>> len(a) + 4 -* Evenly spaced:: +* **2-D, 3-D, ...** + + .. code-block:: python + + >>> b = np.array([[0, 1, 2], [3, 4, 5]]) # arreglo 2 x 3 + >>> b + array([[0, 1, 2], + [3, 4, 5]]) + >>> b.ndim + 2 + >>> b.shape + (2, 3) + >>> len(b) # devuelve el tamaño de la primera dimension + 2 + + >>> c = np.array([[[1], [2]], [[3], [4]]]) + >>> c + array([[[1], + [2]], + + [[3], + [4]]]) + >>> c.shape + (2, 2, 1) + +.. topic:: **Ejercicio: Arreglos simples** + :class: green + + * Crear arreglos simples unidimensionales y bidimensionales. Hacer de nuevo los ejemplos de arriba y luego crear unos propios. + * Utilice las funciones ``len``, ``shape`` y ``ndim`` en algunos de esos arreglos y observe su salida. + +Funciones para crear arreglos +----------------------------- + +En la práctica, rara vez introducimos los items uno por uno ... + +* Uniformemente espaciados + + .. code-block:: python >>> import numpy as np - >>> a = np.arange(10) # 0 .. n-1 (!) + >>> a = np.arange(10) # 0 ... n-1 (!) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) - >>> b = np.arange(1, 9, 2) # start, end (exlusive), step + >>> b = np.arange(1, 9, 2) # inicio, final (excluido), paso >>> b array([1, 3, 5, 7]) - or by number of points:: +* o por número de puntos - >>> c = np.linspace(0, 1, 6) # start, end, num-points + .. code-block:: python + + >>> c = np.linspace(0, 1, 6) # inicio, final, número de puntos >>> c array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. ]) >>> d = np.linspace(0, 1, 5, endpoint=False) >>> d array([ 0. , 0.2, 0.4, 0.6, 0.8]) -* Common arrays:: +* Arreglos comunes + + .. code-block:: python - >>> a = np.ones((3, 3)) # reminder: (3, 3) is a tuple + >>> a = np.ones((3, 3)) # recuerde: (3, 3) es una tupla >>> a array([[ 1., 1., 1.], [ 1., 1., 1.], @@ -209,53 +235,56 @@ In practice, we rarely enter items one by one... [0, 0, 3, 0], [0, 0, 0, 4]]) -* `np.random`: random numbers (Mersenne Twister PRNG):: +* :mod:`np.random`: números seudoaleatorios (Mersenne Twister PRNG) + + .. code-block:: python - >>> a = np.random.rand(4) # uniform in [0, 1] + >>> a = np.random.rand(4) # uniformes in [0, 1] >>> a array([ 0.95799151, 0.14222247, 0.08777354, 0.51887998]) - >>> b = np.random.randn(4) # Gaussian + >>> b = np.random.randn(4) # Gaussianos >>> b array([ 0.37544699, -0.11425369, -0.47616538, 1.79664113]) - >>> np.random.seed(1234) # Setting the random seed + >>> np.random.seed(1234) # Establece la semilla aleatoria +.. topic:: **Ejercicio: Creación de arreglos** + :class: green + + Crear los siguientes arreglos (con los tipos de datos correctos) -.. topic:: **Exercise: Array creation** - :class: green + .. code-block:: python - Create the following arrays (with correct data types):: + [[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 2], + [1, 6, 1, 1]] - [[ 1 1 1 1] - [ 1 1 1 1] - [ 1 1 1 2] - [ 1 6 1 1]] + [[0., 0., 0., 0., 0.], + [2., 0., 0., 0., 0.], + [0., 3., 0., 0., 0.], + [0., 0., 4., 0., 0.], + [0., 0., 0., 5., 0.], + [0., 0., 0., 0., 6.]] - [[0. 0. 0. 0. 0.] - [2. 0. 0. 0. 0.] - [0. 3. 0. 0. 0.] - [0. 0. 4. 0. 0.] - [0. 0. 0. 5. 0.] - [0. 0. 0. 0. 6.]] + Para el curso: 3 casos de cada uno - Par on course: 3 statements for each + *Sugerencia*: A los elementos de un arreglo se acceden de igual forma que una lista, por ejemplo ``a[1]`` or ``a[1, 2]``. - *Hint*: Individual array elements can be accessed similarly to a list, - e.g. ``a[1]`` or ``a[1, 2]``. + *Sugerencia*: Examine el docstring para ``diag``. - *Hint*: Examine the docstring for ``diag``. +.. topic:: Ejercicio: Crear arreglos en mosaicos + :class: green -.. topic:: Exercise: Tiling for array creation - :class: green + Repasa la documentación de ``np.tile``, y utiliza esta función para construir la matriz - Skim through the documentation for ``np.tile``, and use this function - to construct the array:: + .. code-block:: python - [[4 3 4 3 4 3] - [2 1 2 1 2 1] - [4 3 4 3 4 3] - [2 1 2 1 2 1]] + [[4, 3, 4, 3, 4, 3], + [2, 1, 2, 1, 2, 1], + [4, 3, 4, 3, 4, 3], + [2, 1, 2, 1, 2, 1]] .. array() constructor @@ -267,252 +296,272 @@ In practice, we rarely enter items one by one... .. EXE: look what is in an empty() array .. EXE: construct 15 equispaced numbers in range [0, 10] -Basic data types ----------------- +Tipos de datos básicos +---------------------- + +Usted puede haber notado que, en algunos casos, los elementos del arreglo se muestran con un punto (por ejemplo, ``2.`` vs ``2``). Esto se debe a los tipos de datos utilizados -You may have noticed that, in some instances, array elements are displayed with -a trailing dot (e.g. ``2.`` vs ``2``). This is due to a difference in the -data-type used:: +.. code-block:: python - >>> a = np.array([1, 2, 3]) - >>> a.dtype - dtype('int64') + >>> a = np.array([1, 2, 3]) + >>> a.dtype + dtype('int64') - >>> b = np.array([1., 2., 3.]) - >>> b.dtype - dtype('float64') + >>> b = np.array([1., 2., 3.]) + >>> b.dtype + dtype('float64') -Different data-types allow us to store data more compactly in memory, but most -of the time we simply work with floating point numbers. Note that, in the -example above, NumPy auto-detects the data-type from the input. +.. tip:: Diferentes tipos de datos no permiten almacenar datos de forma más compacta en memoria, la mayoría de las veces simplemente trabaje con números de punto flotante. + Tenga en cuenta que, en el ejemplo anterior, NumPy detecta automáticamente el tipo de datos a partir de la entrada. ----------------------------- -You can explicitly specify which data-type you want:: +Puede especificar explícitamente qué tipo de datos desea - >>> c = np.array([1, 2, 3], dtype=float) - >>> c.dtype - dtype('float64') +.. code-block:: python + + >>> c = np.array([1, 2, 3], dtype=float) + >>> c.dtype + dtype('float64') + +El tipo de dato **por defecto** es de punto flotante -The **default** data type is floating point:: +.. tip:: + + .. code-block:: python - >>> a = np.ones((3, 3)) - >>> a.dtype - dtype('float64') + >>> a = np.ones((3, 3)) + >>> a.dtype + dtype('float64') -There are also other types: +También hay otros tipos: -:Complex: +:Complejos: - >>> d = np.array([1+2j, 3+4j, 5+6*1j]) - >>> d.dtype - dtype('complex128') + .. code-block:: python -:Bool: + >>> d = np.array([1+2j, 3+4j, 5+6*1j]) + >>> d.dtype + dtype('complex128') - >>> e = np.array([True, False, False, True]) - >>> e.dtype - dtype('bool') +:Booleanos: -:Strings: + .. code-block:: python - >>> f = np.array(['Bonjour', 'Hello', 'Hallo',]) - >>> f.dtype # <--- strings containing max. 7 letters - dtype('S7') + >>> e = np.array([True, False, False, True]) + >>> e.dtype + dtype('bool') -:Much more: +:Cadenas: - int32/int64... + .. code-block:: python + >>> f = np.array(['Bonjour', 'Hello', 'Hallo',]) + >>> f.dtype # <--- las cadenas en f contienen máximo 7 letras + dtype('S7') +:Muchos más: + + ``int32/int64...`` .. XXX: mention: astype -Basic visualization -------------------- +Visualización básica +-------------------- + +.. tip:: Ahora que tenemos nuestros primeros arreglos de datos, vamos a visualizarlos. -Now that we have our first data arrays, we are going to visualize them. +Inicie IPython en modo *pylab* -Start by launching `IPython` in `pylab` mode:: +.. sourcecode:: bash - $ ipython --pylab + $ ipython --pylab -**Matplotlib** is a 2D plotting package. We can import its functions as below:: +*Matplotlib* es un paquete de trazado 2D y 3D. Podemos importar sus funciones de la siguiente manera - >>> import matplotlib.pyplot as plt # the tidy way +.. code-block:: python -**1D plotting** + >>> import matplotlib.pyplot as plt # en forma ordenada ->>> x = np.linspace(0, 3, 20) ->>> y = np.linspace(0, 9, 20) ->>> plt.plot(x, y) # line plot # doctest: +ELLIPSIS -[] ->>> plt.plot(x, y, 'o') # dot plot # doctest: +ELLIPSIS -[] ->>> plt.show() # <-- shows the plot (not needed with Ipython) # doctest: +SKIP +* **Arreglos 1D** -.. plot:: pyplots/numpy_intro_1.py + .. code-block:: python -**2D arrays** (such as images) + >>> x = np.linspace(0, 3, 20) + >>> y = np.linspace(0, 9, 20) + >>> plt.plot(x, y) # gráfica con línea continua + [] + >>> plt.plot(x, y, 'o') # gráfica con línea punteada + [] + >>> plt.show() # <-- mostrar la gráfica (en Ipython no es necesario) ->>> image = np.random.rand(30, 30) ->>> plt.imshow(image, cmap=plt.cm.gray) # doctest: +ELLIPSIS - ->>> plt.colorbar() # doctest: +ELLIPSIS - ->>> plt.show() # doctest: +SKIP + .. plot:: pyplots/numpy_intro_1.py -.. plot:: pyplots/numpy_intro_2.py +* **Arreglos 2D** (como las imágenes) -.. seealso:: More in the :ref:`matplotlib chapter ` + .. code-block:: python + >>> image = np.random.rand(30, 30) + >>> plt.imshow(image, cmap=plt.cm.hot) + + >>> plt.colorbar() + + >>> plt.show() -**3D plotting** + .. plot:: pyplots/numpy_intro_2.py -For 3D visualization, we can use another package: **Mayavi**. A quick example: -start by **relaunching iPython** with these options: **ipython --pylab=wx** -(or **ipython -pylab -wthread** in IPython < 0.10). + .. seealso:: Más en :ref:`Capítulo Matplotlib ` -.. image:: surf.png - :align: right - :scale: 60 +* **Trazado 3D** -.. sourcecode:: ipython + Para la visualización 3D, podemos utilizar otro paquete: **Mayavi**. Un ejemplo rápido: **iniciar IPython** con estas opciones: **ipython -pylab=wx** (o **ipython -pylab -wthread** en IPython < 0.10). - In [58]: from mayavi import mlab - In [61]: mlab.surf(image) - Out[61]: - In [62]: mlab.axes() - Out[62]: + .. image:: images/surf.png + :align: right + :scale: 60 -The mayavi/mlab window that opens is interactive: by clicking on the left mouse -button you can rotate the image, zoom with the mouse wheel, etc. + .. sourcecode:: ipython -For more information on Mayavi : -http://github.enthought.com/mayavi/mayavi + In [58]: from mayavi import mlab + In [61]: mlab.surf(image) + Out[61]: + In [62]: mlab.axes() + Out[62]: -.. seealso:: More in the :ref:`Mayavi chapter ` + .. tip:: La ventana Mayavi/mlab que se abre es interactiva: haga clic en el botón izquierdo del ratón para rotar la imagen, hacer zoom con la rueda del ratón, etc. + Para más información sobre Mayavi : http://github.enthought.com/mayavi/mayavi -Indexing and slicing --------------------- + .. seealso:: Más en :ref:`Capítulo Mayavi ` -The items of an array can be accessed and assigned to the same way as -other Python sequences (e.g. lists) :: +Indexado y segmentado +--------------------- - >>> a = np.arange(10) - >>> a - array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) - >>> a[0], a[2], a[-1] - (0, 2, 9) +Los elementos de un arreglo se puede acceder y asignar de la misma forma que +otras secuencias de Python (por ejemplo, listas) -.. warning:: +.. code-block:: python - Indices begin at 0, like other Python sequences (and C/C++). - In contrast, in Fortran or Matlab, indices begin at 1. + >>> a = np.arange(10) + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> a[0], a[2], a[-1] + (0, 2, 9) -For multidimensional arrays, indexes are tuples of integers:: +.. warning:: Los indices comienzan en 0, al igual que otras secuencias de Python (y C/C++). En contraste, en Fortran o Matlab, los índices comienzan en 1. - >>> a = np.diag(np.arange(3)) - >>> a - array([[0, 0, 0], - [0, 1, 0], - [0, 0, 2]]) - >>> a[1, 1] - 1 - >>> a[2, 1] = 10 # third line, second column - >>> a - array([[ 0, 0, 0], - [ 0, 1, 0], - [ 0, 10, 2]]) - >>> a[1] - array([0, 1, 0]) +En arreglos multidimensionales, los índices son tuplas de números enteros -Note that: +.. code-block:: python -* In 2D, the first dimension corresponds to rows, the second to columns. -* for multidimensional ``a``, `a[0]` is interpreted by - taking all elements in the unspecified dimensions. + >>> a = np.diag(np.arange(3)) + >>> a + array([[0, 0, 0], + [0, 1, 0], + [0, 0, 2]]) + >>> a[1, 1] + 1 + >>> a[2, 1] = 10 # tercera fila, segunda columna + >>> a + array([[ 0, 0, 0], + [ 0, 1, 0], + [ 0, 10, 2]]) + >>> a[1] + array([0, 1, 0]) # segunda fila -**Slicing** Arrays, like other Python sequences can also be sliced:: +Note que: - >>> a = np.arange(10) - >>> a - array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) - >>> a[2:9:3] # [start:end:step] - array([2, 5, 8]) +* En 2D, la primera dimensión corresponde a las filas, la segunda a las columnas. +* Para un arreglo multidimensional ``a``, ``a[0]`` es interpretado teniendo todos los elementos en las dimensiones especificadas. -Note that the last index is not included! :: +**Segmentado** de arreglos, al igual que otras secuencias de Python también pueden ser segmentadas - >>> a[:4] - array([0, 1, 2, 3]) +.. code-block:: python -All three slice components are not required: by default, `start` is 0, -`end` is the last and `step` is 1:: + >>> a = np.arange(10) + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> a[2:9:3] # [inicio:final:paso] + array([2, 5, 8]) - >>> a[1:3] - array([1, 2]) - >>> a[::2] - array([0, 2, 4, 6, 8]) - >>> a[3:] - array([3, 4, 5, 6, 7, 8, 9]) +Tenga en cuenta que el último índice no es incluido! -A small illustrated summary of Numpy indexing and slicing... +.. code-block:: python -.. only:: latex + >>> a[:4] + array([0, 1, 2, 3]) - .. image:: numpy_indexing.png - :align: center +Los tres argumentos de segmentado no son necesarios: por defecto, `inicio` es 0, `final` es el último y `paso` es 1 -.. only:: html +.. code-block:: python - .. image:: numpy_indexing.png - :align: center - :width: 100% + >>> a[1:3] + array([1, 2]) + >>> a[::2] + array([0, 2, 4, 6, 8]) + >>> a[3:] + array([3, 4, 5, 6, 7, 8, 9]) -Copies and views ----------------- +Un pequeño resumen ilustrado de indexado y segmentado en Numpy ... -A slicing operation creates a **view** on the original array, which is -just a way of accessing array data. Thus the original array is not -copied in memory. +.. only:: latex -**When modifying the view, the original array is modified as well**:: + .. image:: images/numpy_indexing.png + :align: center - >>> a = np.arange(10) - >>> a - array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) - >>> b = a[::2]; b - array([0, 2, 4, 6, 8]) - >>> b[0] = 12 - >>> b - array([12, 2, 4, 6, 8]) - >>> a # (!) - array([12, 1, 2, 3, 4, 5, 6, 7, 8, 9]) +.. only:: html - >>> a = np.arange(10) - >>> b = a[::2].copy() # force a copy - >>> b[0] = 12 - >>> a - array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + .. image:: images/numpy_indexing.png + :align: center + :width: 65% -This behavior can be surprising at first sight... but it allows to save both -memory and time. +Copias y vistas +--------------- -.. warning:: **The transpose is a view** +Una operación de segmentado crea una **vista** del arreglo original, que es +sólo una forma de acceder a los datos de un arreglo. Por lo tanto el arreglo original no es copiado en memoria. - As a result, a matrix cannot be made symmetric in-place:: +**Al modificar una vista, la matriz original es modificado** - >>> a = np.ones((100, 100)) - >>> a += a.T - >>> a - array([[ 2., 2., 2., ..., 2., 2., 2.], - [ 2., 2., 2., ..., 2., 2., 2.], - [ 2., 2., 2., ..., 2., 2., 2.], - ..., - [ 3., 3., 3., ..., 2., 2., 2.], - [ 3., 3., 3., ..., 2., 2., 2.], - [ 3., 3., 3., ..., 2., 2., 2.]]) +.. code-block:: python + + >>> a = np.arange(10) + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + >>> b = a[::2] + array([0, 2, 4, 6, 8]) + >>> b + array([0, 2, 4, 6, 8]) + >>> b[0] = 12 + >>> b + array([12, 2, 4, 6, 8]) + >>> a # (!) + array([12, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + + >>> a = np.arange(10) + >>> b = a[::2].copy() # creando una copia + >>> b[0] = 12 + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) + +Este comportamiento puede resultar sorprendente a primera vista ... pues permite ahorrar memoria y tiempo. + +.. warning:: **La transpuesta es una vista** + + Como resultado, una matriz no puede simétrica sobre la marcha + + .. code-block:: python + + >>> a = np.ones((100, 100)) + >>> a += a.T + >>> a + array([[ 2., 2., 2., ..., 2., 2., 2.], + [ 2., 2., 2., ..., 2., 2., 2.], + [ 2., 2., 2., ..., 2., 2., 2.], + ..., + [ 3., 3., 3., ..., 2., 2., 2.], + [ 3., 3., 3., ..., 2., 2., 2.], + [ 3., 3., 3., ..., 2., 2., 2.]]) .. EXE: [1, 2, 3, 4, 5] -> [1, 2, 3] .. EXE: [1, 2, 3, 4, 5] -> [4, 5] @@ -525,146 +574,138 @@ memory and time. .. EXE: create an array [1, 0, 2, 0, 3, 0, 4] .. CHA: archimedean sieve -.. topic:: Worked example: Prime number sieve +.. topic:: Ejemplo práctico: Criba de números primos :class: green - .. image:: prime-sieve.png - - Compute prime numbers in 0--99, with a sieve + .. image:: images/prime-sieve.png - * Construct a shape (100,) boolean array ``is_prime``, - filled with True in the beginning:: + Calcular los números primos en 0--99, con una criba - >>> is_prime = np.ones((100,), dtype=bool) + * Construir un arreglo booleano ``es_primo`` con 100 elementos, en el principio todos sus elementos son True - * Cross out 0 and 1 which are not primes:: + .. code-block:: python - >>> is_prime[:2] = 0 + >>> es_primo = np.ones((100), dtype=bool) - * For each integer ``j`` starting from 2, cross out its higher multiples:: + * Descartar 0 y 1 porque no son primos - >>> N_max = int(np.sqrt(len(is_prime))) - >>> for j in range(2, N_max): - ... is_prime[2*j::j] = False + .. code-block:: python - * Skim through ``help(np.nonzero)``, and print the prime numbers + >>> es_primo[:2] = 0 # 0 es False, 1 es True - * Follow-up: + * Para cada número entero ``j`` a partir de 2, descartar sus múltiplos superiores - - Move the above code into a script file named ``prime_sieve.py`` - - - Run it to check it works - - - Convert the simple sieve to `the sieve of Eratosthenes - `__: + .. code-block:: python - 1. Skip `j` which are already known to not be primes + >>> numero_maximo = int(np.sqrt(len(es_primo))) + >>> for j in range(2, numero_maximo): + ... es_primo[2*j::j] = False - 2. The first number to cross out is :math:`j^2` + * Repase ``help(np.nonzero)``, e imprima los números primos -Adding Axes ------------ + * Pasos a seguir: -Indexing with the ``np.newaxis`` object allows us to add an axis to an array: + - Mueva el código anterior a un script llamado ``criba_primos.py`` ->>> z = np.array([1, 2, 3]) ->>> z -array([1, 2, 3]) + - Ejecutar para comprobar que funciona ->>> z[:, np.newaxis] -array([[1], - [2], - [3]]) + - Convierta esta criba simple una `Criba de Eratóstenes + `__: ->>> z[np.newaxis, :] -array([[1, 2, 3]]) + 1. Descarte los `j` que ya son conocidos por no ser primos + 2. El primer número para descartar es :math:`j^2` -Fancy indexing +Indexado fancy -------------- -Numpy arrays can be indexed with slices, but also with boolean or -integer arrays (**masks**). This method is called *fancy indexing*. It -creates **copies not views**. +.. tip:: Los arreglos numpy pueden indexarse ​​en segmentos, pero también con arreglos booleanos o arreglos enteros (**enmascarados**). Este método se llama *indexado fancy*. Crea **copias no vistas**. -Using boolean masks -................... +Usando enmascarado booleano +........................... ->>> np.random.seed(3) ->>> a = np.random.random_integers(0, 20, 15) ->>> a -array([10, 3, 8, 0, 19, 10, 11, 9, 10, 6, 0, 20, 12, 7, 14]) ->>> (a % 3 == 0) -array([False, True, False, True, False, False, False, True, False, - True, True, False, True, False, False], dtype=bool) ->>> mask = (a % 3 == 0) ->>> extract_from_a = a[mask] # or, a[a%3==0] ->>> extract_from_a # extract a sub-array with the mask -array([ 3, 0, 9, 6, 0, 12]) +.. code-block:: python -Indexing with a mask can be very useful to assign a new value to a sub-array:: + >>> np.random.seed(3) + >>> a = np.random.random_integers(0, 20, 15) + >>> a + array([10, 3, 8, 0, 19, 10, 11, 9, 10, 6, 0, 20, 12, 7, 14]) + >>> a % 3 == 0 + array([False, True, False, True, False, False, False, True, False, + True, True, False, True, False, False], dtype=bool) + >>> mascara = (a % 3 == 0) + >>> extraer_desde_a = a[mascara] # o tambien, extraer_desde_a = a[a%3==0] + >>> extraer_desde_a # extrae un subarreglo con máscara + array([ 3, 0, 9, 6, 0, 12]) - >>> a[a % 3 == 0] = -1 - >>> a - array([10, -1, 8, -1, 19, 10, 11, -1, 10, -1, -1, 20, -1, 7, 14]) +El indexado con máscara puede ser muy útil para asignar un nuevo valor a un subarreglo +.. code-block:: python -Indexing with an array of integers -.................................... + >>> a[a % 3 == 0] = -1 # o tambien, a[a%3==0] = -1 + >>> a + array([10, -1, 8, -1, 19, 10, 11, -1, 10, -1, -1, 20, -1, 7, 14]) ->>> a = np.arange(10) ->>> a -array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) +Indexado con una arreglo de enteros +................................... -Indexing can be done with an array of integers, where the same index is repeated -several time:: +.. code-block:: python - >>> a[[2, 3, 2, 4, 2]] # note: [2, 3, 2, 4, 2] is a Python list - array([2, 3, 2, 4, 2]) + >>> a = np.arange(10) + >>> a + array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) -New values can be assigned with this kind of indexing:: +El indexado se puede hacer con un arreglo de enteros, donde se repita el mismo índice varias veces - >>> a[[9, 7]] = -10 - >>> a - array([ 0, 1, 2, 3, 4, 5, 6, -10, 8, -10]) +.. code-block:: python -When a new array is created by indexing with an array of integers, the new array -has the same shape than the array of integers:: + >>> a[[2, 3, 2, 4, 2]] # nota: [2, 3, 2, 4, 2] es una lista Python + array([2, 3, 2, 4, 2]) + +Nuevos valores pueden ser asignados con este tipo de indexado + +.. code-block:: python - >>> a = np.arange(10) - >>> idx = np.array([[3, 4], [9, 7]]) - >>> a[idx] - array([[3, 4], - [9, 7]]) - >>> b = np.arange(10) + >>> a[[9, 7]] = -10 + >>> a + array([ 0, 1, 2, 3, 4, 5, 6, -10, 8, -10]) +.. tip:: Cuando una nuevo arreglo es creado a partir de un indexado de un arreglo de enteros, el nuevo arreglo tiene la misma forma que el arreglo de enteros + + .. code-block:: python + + >>> a = np.arange(10) + >>> indices = np.array([[3, 4], [9, 7]]) + >>> a[indices] + array([[3, 4], + [9, 7]]) + >>> b = np.arange(10) ____ -The image below illustrates various fancy indexing applications +La imagen a continuación muestra varias aplicaciones del indexado fancy .. only:: latex - .. image:: numpy_fancy_indexing.png - :align: center + .. image:: images/numpy_fancy_indexing.png + :align: center .. only:: html - .. image:: numpy_fancy_indexing.png - :align: center - :width: 100% + .. image:: images/numpy_fancy_indexing.png + :align: center + :width: 80% -We can even use fancy indexing and :ref:`broadcasting ` at -the same time:: - - >>> a = np.arange(12).reshape(3,4) - >>> a - array([[ 0, 1, 2, 3], - [ 4, 5, 6, 7], - [ 8, 9, 10, 11]]) - >>> i = np.array([[0, 1], [1, 2]]) - >>> a[i, 2] # same as a[i, 2*np.ones((2, 2), dtype=int)] - array([[ 2, 6], - [ 6, 10]]) +Incluso podemos utilizar el indexado fancy y :ref:`broadcasting ` al mismo tiempo +.. code-block:: python + >>> a = np.arange(12).reshape(3,4) + >>> a + array([[ 0, 1, 2, 3], + [ 4, 5, 6, 7], + [ 8, 9, 10, 11]]) + >>> i = np.array([[0, 1], [1, 2]]) + >>> a[i, 2] # lo mismo es a[i, 2*np.ones((2, 2), dtype=int)] + array([[ 2, 6], + [ 6, 10]]) diff --git a/intro/numpy/data b/intro/numpy/data new file mode 120000 index 0000000..b8fb52e --- /dev/null +++ b/intro/numpy/data @@ -0,0 +1 @@ +../../data/ \ No newline at end of file diff --git a/intro/numpy/elaborate_arrays.rst b/intro/numpy/elaborate_arrays.rst index 19a15ee..1d4869a 100644 --- a/intro/numpy/elaborate_arrays.rst +++ b/intro/numpy/elaborate_arrays.rst @@ -1,78 +1,85 @@ .. For doctests - + >>> import numpy as np >>> np.random.seed(0) >>> from matplotlib import pyplot as plt .. currentmodule:: numpy -More elaborate arrays -====================== +Arreglos más elaborados +======================= -.. contents:: Section contents +.. contents:: Contenido :local: :depth: 1 +Más tipos de datos +------------------ + +Conversión de tipos +................... -.. XXX: maybe some of this should go to the advanced chapter +El tipo "más grande" prevalece en las operaciones de tipo mixto -More data types ---------------- +.. code-block:: python -Casting -........ + >>> np.array([1, 2, 3]) + 1.5 + array([ 2.5, 3.5, 4.5]) -"Bigger" type wins in mixed-type operations:: +La asignación no cambia el tipo! - >>> np.array([1, 2, 3]) + 1.5 - array([ 2.5, 3.5, 4.5]) +.. code-block:: python -Assignment never changes the type! :: + >>> a = np.array([1, 2, 3]) + >>> a.dtype + dtype('int32') + >>> a[0] = 1.9 # <-- número de punto flotante truncado a número entero + >>> a + array([1, 2, 3]) - >>> a = np.array([1, 2, 3]) - >>> a.dtype - dtype('int64') - >>> a[0] = 1.9 # <-- float is truncated to integer - >>> a - array([1, 2, 3]) +Conversión forzada -Forced casts:: +.. code-block:: python - >>> a = np.array([1.7, 1.2, 1.6]) - >>> b = a.astype(int) # <-- truncates to integer - >>> b - array([1, 1, 1]) + >>> a = np.array([1.7, 1.2, 1.6]) + >>> b = a.astype(int) # <-- truncado a entero + >>> b + array([1, 1, 1]) -Rounding:: +Redondeo - >>> a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5]) - >>> b = np.around(a) - >>> b # still floating-point - array([ 1., 2., 2., 2., 4., 4.]) - >>> c = np.around(a).astype(int) - >>> c - array([ 1, 2, 2, 2, 4, 4]) +.. code-block:: python -Different data type sizes -.......................... + >>> a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5]) + >>> b = np.around(a) + >>> b # sigue siendo de punto flotante + array([ 1., 2., 2., 2., 4., 4.]) + >>> c = np.around(a).astype(int) + >>> c + array([1, 2, 2, 2, 4, 4]) -Integers (signed): +Tamaños de tipos de datos +......................... + +Enteros (con signo): =================== ============================================================== :class:`int8` 8 bits :class:`int16` 16 bits -:class:`int32` 32 bits (same as :class:`int` on 32-bit platform) -:class:`int64` 64 bits (same as :class:`int` on 64-bit platform) +:class:`int32` 32 bits (el mismo :class:`int` en platforma 32-bit) +:class:`int64` 64 bits (el mismo :class:`int` en platforma 64-bit) =================== ============================================================== ->>> np.array([1], dtype=int).dtype -dtype('int64') ->>> np.iinfo(np.int32).max, 2**31 - 1 -(2147483647, 2147483647) ->>> np.iinfo(np.int64).max, 2**63 - 1 -(9223372036854775807, 9223372036854775807L) +.. code-block:: python + + >>> np.array([1], dtype=int).dtype + dtype('int64') + >>> np.iinfo(np.int32).max, 2**31 - 1 + (2147483647, 2147483647) + >>> np.iinfo(np.int64).max, 2**63 - 1 + (9223372036854775807, 9223372036854775807L) -Unsigned integers: +Enteros sin signo: =================== ============================================================== :class:`uint8` 8 bits @@ -81,48 +88,52 @@ Unsigned integers: :class:`uint64` 64 bits =================== ============================================================== ->>> np.iinfo(np.uint32).max, 2**32 - 1 -(4294967295, 4294967295) ->>> np.iinfo(np.uint64).max, 2**64 - 1 -(18446744073709551615L, 18446744073709551615L) +.. code-block:: python -Floating-point numbers: + >>> np.iinfo(np.uint32).max, 2**32 - 1 + (4294967295, 4294967295) + >>> np.iinfo(np.uint64).max, 2**64 - 1 + (18446744073709551615L, 18446744073709551615L) + +Números de punto flotante: =================== ============================================================== :class:`float16` 16 bits :class:`float32` 32 bits -:class:`float64` 64 bits (same as :class:`float`) -:class:`float96` 96 bits, platform-dependent (same as :class:`np.longdouble`) -:class:`float128` 128 bits, platform-dependent (same as :class:`np.longdouble`) +:class:`float64` 64 bits (el mismo :class:`float`) +:class:`float96` 96 bits, dependiente de la plataforma (el mismo :class:`np.longdouble`) +:class:`float128` 128 bits, dependiente de la plataforma (el mismo :class:`np.longdouble`) =================== ============================================================== ->>> np.finfo(np.float32).eps -1.1920929e-07 ->>> np.finfo(np.float64).eps -2.2204460492503131e-16 +.. code-block:: python + + >>> np.finfo(np.float32).eps + 1.1920929e-07 + >>> np.finfo(np.float64).eps + 2.2204460492503131e-16 ->>> np.float32(1e-8) + np.float32(1) == 1 -True ->>> np.float64(1e-8) + np.float64(1) == 1 -False + >>> np.float32(1e-8) + np.float32(1) == 1 + True + >>> np.float64(1e-8) + np.float64(1) == 1 + False -Complex floating-point numbers: +Números complejos de punto flotante: =================== ============================================================== -:class:`complex64` two 32-bit floats -:class:`complex128` two 64-bit floats -:class:`complex192` two 96-bit floats, platform-dependent -:class:`complex256` two 128-bit floats, platform-dependent +:class:`complex64` dos números de punto flotante 32-bit +:class:`complex128` dos números de punto flotante 64-bit +:class:`complex192` dos números de punto flotante 96-bit, dependiente de la plataforma +:class:`complex256` dos números de punto flotante 128-bit, dependiente de la plataforma =================== ============================================================== -.. topic:: Smaller data types +.. topic:: Tipos de datos pequeños - If you don't know you need special data types, then you probably don't. + Si usted no sabe si necesita los tipos de datos especiales, es probable que no los conozca. - Comparison on using ``float32`` instead of ``float64``: + Comparación sobre el uso de ``float32`` en vez de ``float64``: - - Half the size in memory and on disk - - Half the memory bandwidth required (may be a bit faster in some operations) + - La mitad del tamaño en la memoria y en el disco + - La mitad del ancho de banda de memoria necesaria (puede ser un poco más rápido en algunas operaciones ) .. sourcecode:: ipython @@ -136,318 +147,114 @@ Complex floating-point numbers: In [4]: %timeit b*b 1000 loops, best of 3: 1.07 ms per loop - - But: bigger rounding errors --- sometimes in surprising places - (i.e., don't use them unless you really need them) - - -Structured data types ---------------------- - -==================================== == -``sensor_code`` (4-character string) -``position`` (float) -``value`` (float) -==================================== == - ->>> samples = np.zeros((6,), dtype=[('sensor_code', 'S4'), -... ('position', float), ('value', float)]) ->>> samples.ndim -1 ->>> samples.shape -(6,) ->>> samples.dtype.names -('sensor_code', 'position', 'value') - ->>> samples[:] = [('ALFA', 1, 0.37), ('BETA', 1, 0.11), ('TAU', 1, 0.13), -... ('ALFA', 1.5, 0.37), ('ALFA', 3, 0.11), ('TAU', 1.2, 0.13)] ->>> samples -array([('ALFA', 1.0, 0.37), ('BETA', 1.0, 0.11), ('TAU', 1.0, 0.13), - ('ALFA', 1.5, 0.37), ('ALFA', 3.0, 0.11), ('TAU', 1.2, 0.13)], - dtype=[('sensor_code', '|S4'), ('position', '>> samples['sensor_code'] - array(['ALFA', 'BETA', 'TAU', 'ALFA', 'ALFA', 'TAU'], - dtype='|S4') - >>> samples['value'] - array([ 0.37, 0.11, 0.13, 0.37, 0.11, 0.13]) - >>> samples[0] - ('ALFA', 1.0, 0.37) - - >>> samples[0]['sensor_code'] = 'TAU' - >>> samples[0] - ('TAU', 1.0, 0.37) - -Multiple fields at once:: - - >>> samples[['position', 'value']] - array([(1.0, 0.37), (1.0, 0.11), (1.0, 0.13), (1.5, 0.37), (3.0, 0.11), - (1.2, 0.13)], - dtype=[('position', '>> samples[samples['sensor_code'] == 'ALFA'] - array([('ALFA', 1.5, 0.37), ('ALFA', 3.0, 0.11)], - dtype=[('sensor_code', '|S4'), ('position', '`__ - and `here `__. +.. code-block:: python + >>> muestras = np.zeros((6,), dtype=[('codigo_sensor', 'S4'), + ... ('posicion', float), ('valor', float)]) + >>> muestras.ndim + 1 + >>> muestras.shape + (6,) + >>> muestras.dtype.names + ('codigo_sensor', 'posicion', 'valor') + >>> muestras[:] = [('ALFA', 1, 0.37), ('BETA', 1, 0.11), ('TAU', 1, 0.13), + ... ('ALFA', 1.5, 0.37), ('ALFA', 3, 0.11), ('TAU', 1.2, 0.13)] + >>> muestras + array([('ALFA', 1.0, 0.37), ('BETA', 1.0, 0.11), ('TAU', 1.0, 0.13), + ('ALFA', 1.5, 0.37), ('ALFA', 3.0, 0.11), ('TAU', 1.2, 0.13)], + dtype=[('codigo_sensor', 'S4'), ('posicion', '>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1]) - >>> x - masked_array(data = [1 -- 3 --], - mask = [False True False True], - fill_value = 999999) - + >>> muestras['codigo_sensor'] + array(['ALFA', 'BETA', 'TAU', 'ALFA', 'ALFA', 'TAU'], + dtype='|S4') + >>> muestras['valor'] + array([ 0.37, 0.11, 0.13, 0.37, 0.11, 0.13]) + >>> muestras[0] + ('ALFA', 1.0, 0.37) + >>> muestras[0]['codigo_sensor'] + >>> 'ALFA' + >>> muestras[0]['codigo_sensor'] = 'TAU' + >>> samples[0] + ('TAU', 1.0, 0.37) - >>> y = np.ma.array([1, 2, 3, 4], mask=[0, 1, 1, 1]) - >>> x + y - masked_array(data = [2 -- -- --], - mask = [False True True True], - fill_value = 999999) - +Campos múltiples a la vez -* Masking versions of common functions:: +.. code-block:: python - >>> np.ma.sqrt([1, -1, 2, -2]) - masked_array(data = [1.0 -- 1.41421356237 --], - mask = [False True False True], - fill_value = 1e+20) - + >>> muestras[['posicion', 'valor']] + array([(1.0, 0.37), (1.0, 0.11), (1.0, 0.13), (1.5, 0.37), (3.0, 0.11), + (1.2, 0.13)], + dtype=[('posicion', '` + >>> muestras[muestras['codigo_sensor'] == 'ALFA'] + array([('ALFA', 1.5, 0.37), ('ALFA', 3.0, 0.11)], + dtype=[('codigo_sensor', 'S4'), ('posicion', '`__ y `aquí `__. -.. _memory_layout: - -Under the hood: the memory layout of a numpy array +:class:`maskedarray`: tratando con datos que faltan --------------------------------------------------- -A numpy array is: - - block of memory + indexing scheme + data type descriptor - - - raw data - - how to locate an element - - how to interpret an element - -.. image:: threefundamental.png - -Block of memory -................ - ->>> x = np.array([1, 2, 3, 4], dtype=np.int32) ->>> x.data # doctest: +ELLIPSIS - ->>> str(x.data) -'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00' - -Memory address of the data:: - - >>> x.__array_interface__['data'][0] # doctest: +SKIP - 159755776 - -Reminder: two :class:`ndarrays ` may share the same memory:: - - >>> x = np.array([1,2,3,4]) - >>> y = x[:] - >>> x[0] = 9 - >>> y - array([9, 2, 3, 4]) - >>> y.base is x - True - -Memory does not need to be owned by an :class:`ndarray`:: - - >>> x = '\x01\x02\x03\x04' - >>> y = np.frombuffer(x, dtype=np.int8) - >>> y - array([1, 2, 3, 4], dtype=int8) - >>> y.data # doctest: +ELLIPSIS - - >>> y.base is x - True - - >>> y.flags - C_CONTIGUOUS : True - F_CONTIGUOUS : True - OWNDATA : False - WRITEABLE : False - ALIGNED : True - UPDATEIFCOPY : False - -The ``owndata`` and ``writeable`` flags indicate status of the memory -block. - - -Indexing scheme: strides -......................... - -**The question** - - >>> x = np.array([[1, 2, 3], - ... [4, 5, 6], - ... [7, 8, 9]], dtype=np.int8) - >>> str(x.data) - '\x01\x02\x03\x04\x05\x06\x07\x08\t' - - At which byte in ``x.data`` does the item ``x[1, 2]`` begin? - -**The answer** (in Numpy) - - - **strides**: the number of bytes to jump to find the next element - - 1 stride per dimension - - >>> x.strides - (3, 1) - >>> byte_offset = 3*1 + 1*2 # to find x[1, 2] - >>> x.data[byte_offset] - '\x06' - >>> x[1, 2] - 6 - - - simple, **flexible** - - -.. rubric:: C and Fortran order - ->>> x = np.array([[1, 2, 3], -... [4, 5, 6], -... [7, 8, 9]], dtype=np.int16, order='C') ->>> x.strides -(6, 2) ->>> str(x.data) -'\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00\x07\x00\x08\x00\t\x00' - -* Need to jump 6 bytes to find the next row -* Need to jump 2 bytes to find the next column - - ->>> y = np.array(x, order='F') ->>> y.strides -(2, 6) ->>> str(y.data) -'\x01\x00\x04\x00\x07\x00\x02\x00\x05\x00\x08\x00\x03\x00\x06\x00\t\x00' - -* Need to jump 2 bytes to find the next row -* Need to jump 6 bytes to find the next column - - -- Similarly to higher dimensions: - - - C: last dimensions vary fastest (= smaller strides) - - F: first dimensions vary fastest +* Para números de punto flotante se podría utilizar NaN , pero las máscaras funcionan para todos los tipos - .. math:: + .. code-block:: python - \mathrm{shape} &= (d_1, d_2, ..., d_n) - \\ - \mathrm{strides} &= (s_1, s_2, ..., s_n) - \\ - s_j^C &= d_{j+1} d_{j+2} ... d_{n} \times \mathrm{itemsize} - \\ - s_j^F &= d_{1} d_{2} ... d_{j-1} \times \mathrm{itemsize} + >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1]) + >>> x + masked_array(data = [1 -- 3 --], + mask = [False True False True], + fill_value = 999999) + -.. rubric:: Slicing + >>> y = np.ma.array([1, 2, 3, 4], mask=[0, 1, 1, 1]) + >>> x + y + masked_array(data = [2 -- -- --], + mask = [False True True True], + fill_value = 999999) + -- *Everything* can be represented by changing only ``shape``, ``strides``, - and possibly adjusting the ``data`` pointer! -- Never makes copies of the data +* Versión enmascarada de funciones comunes ->>> x = np.array([1, 2, 3, 4, 5, 6], dtype=np.int32) ->>> y = x[::-1] ->>> y -array([6, 5, 4, 3, 2, 1], dtype=int32) ->>> y.strides -(-4,) + .. code-block:: python ->>> y = x[2:] ->>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0] -8 - ->>> x = np.zeros((10, 10, 10), dtype=np.float) ->>> x.strides -(800, 80, 8) ->>> x[::2,::3,::4].strides -(1600, 240, 32) - -- Similarly, transposes never make copies (it just swaps strides) - ->>> x = np.zeros((10, 10, 10), dtype=np.float) ->>> x.strides -(800, 80, 8) ->>> x.T.strides -(8, 80, 800) - -.. rubric:: Reshaping - -But: not all reshaping operations can be represented by playing with -strides. - ->>> a = np.arange(6, dtype=np.int8).reshape(3, 2) ->>> b = a.T ->>> b.strides -(1, 2) - -So far, so good. However: - ->>> str(a.data) -'\x00\x01\x02\x03\x04\x05' ->>> b -array([[0, 2, 4], - [1, 3, 5]], dtype=int8) ->>> c = b.reshape(3*2) ->>> c -array([0, 2, 4, 1, 3, 5], dtype=int8) - -Here, there is no way to represent the array ``c`` given one stride -and the block of memory for ``a``. Therefore, the ``reshape`` -operation needs to make a copy here. - - -Summary -........ - -- Numpy array: block of memory + indexing scheme + data type description - -- Indexing: strides - - ``byte_position = np.sum(arr.strides * indices)`` - -- Various tricks can you do by playing with the strides (stuff for an - advanced tutorial it is) + >>> np.ma.sqrt([1, -1, 2, -2]) + masked_array(data = [1.0 -- 1.41421356237 --], + mask = [False True False True], + fill_value = 1e+20) + +.. note:: Hay otros útiles :ref:`array siblings ` _____ -While it is off topic in a chapter on numpy, let's take a moment to -recall good coding practice, which really do pay off in the long run: - -.. topic:: Good practices - - * Explicit variable names (no need of a comment to explain what is in - the variable) +Este tema esta fuera de los capítulos sobre Numpy, tomemos un momento para +recordar las buenas prácticas de codificación, lo que realmente vale la pena a largo plazo: - * Style: spaces after commas, around ``=``, etc. +.. topic:: Buenas prácticas - A certain number of rules for writing "beautiful" code (and, more - importantly, using the same conventions as everybody else!) are - given in the `Style Guide for Python Code - `_ and the `Docstring - Conventions `_ page (to - manage help strings). + * Nombres de variables explícitos (sin necesidad de un comentario que explique lo que está en la variable) - * Except some rare cases, variable names and comments in English. + * Estilo: espacio después de las comas, antes y despues de ``=``, etc. + Un cierto número de reglas para escribir código ``hermoso`` (y más importante, el uso de las mismas convenciones para todos los demás!) están en `Style Guide for Python Code `_ y `Docstring Conventions `_ (manejo de cadenas de ayuda). + * Excepto en algunos casos raros, los nombres de variables y comentarios en inglés. diff --git a/intro/numpy/exercises.rst b/intro/numpy/exercises.rst new file mode 100644 index 0000000..bc2ab19 --- /dev/null +++ b/intro/numpy/exercises.rst @@ -0,0 +1,257 @@ +Some exercises +============== + +Array manipulations +-------------------- + +1. Form the 2-D array (without typing it in explicitly):: + + [[1, 6, 11], + [2, 7, 12], + [3, 8, 13], + [4, 9, 14], + [5, 10, 15]] + + and generate a new array containing its 2nd and 4th rows. + +2. Divide each column of the array: + + .. sourcecode:: pycon + + >>> a = np.arange(25).reshape(5, 5) + + elementwise with the array ``b = np.array([1., 5, 10, 15, 20])``. + (Hint: ``np.newaxis``). + +3. Harder one: Generate a 10 x 3 array of random numbers (in range [0,1]). + For each row, pick the number closest to 0.5. + + - Use ``abs`` and ``argsort`` to find the column ``j`` closest for + each row. + + - Use fancy indexing to extract the numbers. (Hint: ``a[i,j]`` -- + the array ``i`` must contain the row numbers corresponding to stuff in + ``j``.) + + +Picture manipulation: Framing Lena +----------------------------------- + +Let's do some manipulations on numpy arrays by starting with the +famous image of Lena (http://www.cs.cmu.edu/~chuck/lennapg/). +``scipy`` provides a 2D array of this image with the ``scipy.lena`` +function:: + + + >>> from scipy import misc + >>> lena = misc.lena() + +**Note:** In older versions of scipy, you will find lena under +``scipy.lena()`` + +Here are a few images we will be able to obtain with our manipulations: +use different colormaps, crop the image, change some parts of the image. + +.. image:: images/lenas.png + :align: center + +* Let's use the imshow function of pylab to display the image. + + .. sourcecode:: ipython + + In [3]: import pylab as plt + In [4]: lena = misc.lena() + In [5]: plt.imshow(lena) + +* Lena is then displayed in false colors. A colormap must be + specified for her to be displayed in grey. + + .. sourcecode:: ipython + + In [6]: plt.imshow(lena, cmap=plt.cm.gray) + +* Create an array of the image with a narrower centering : for example, + remove 30 pixels from all the borders of the image. To check the result, + display this new array with ``imshow``. + + .. sourcecode:: ipython + + In [9]: crop_lena = lena[30:-30,30:-30] + +* We will now frame Lena's face with a black locket. For this, we + need to create a mask corresponding to the pixels we want to be + black. The mask is defined by this condition ``(y-256)**2 + + (x-256)**2`` + + .. sourcecode:: ipython + + In [15]: y, x = np.ogrid[0:512,0:512] # x and y indices of pixels + In [16]: y.shape, x.shape + Out[16]: ((512, 1), (1, 512)) + In [17]: centerx, centery = (256, 256) # center of the image + In [18]: mask = ((y - centery)**2 + (x - centerx)**2) > 230**2 # circle + + then we assign the value 0 to the pixels of the image corresponding + to the mask. The syntax is extremely simple and intuitive: + + .. sourcecode:: ipython + + In [19]: lena[mask] = 0 + In [20]: plt.imshow(lena) + Out[20]: + +* Follow-up: copy all instructions of this exercise in a script called + ``lena_locket.py`` then execute this script in IPython with ``%run + lena_locket.py``. + + Change the circle to an ellipsoid. + +Data statistics +---------------- + +The data in :download:`populations.txt <../../data/populations.txt>` +describes the populations of hares and lynxes (and carrots) in +northern Canada during 20 years: + +.. sourcecode:: pycon + + >>> data = np.loadtxt('data/populations.txt') + >>> year, hares, lynxes, carrots = data.T # trick: columns to variables + + >>> plt.axes([0.2, 0.1, 0.5, 0.8]) # doctest: +ELLIPSIS + + >>> plt.plot(year, hares, year, lynxes, year, carrots) # doctest: +ELLIPSIS + [, ...] + >>> plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5)) # doctest: +ELLIPSIS + + +.. plot:: pyplots/numpy_intro_7.py + +Computes and print, based on the data in ``populations.txt``... + +1. The mean and std of the populations of each species for the years + in the period. + +2. Which year each species had the largest population. + +3. Which species has the largest population for each year. + (Hint: ``argsort`` & fancy indexing of + ``np.array(['H', 'L', 'C'])``) + +4. Which years any of the populations is above 50000. + (Hint: comparisons and ``np.any``) + +5. The top 2 years for each species when they had the lowest + populations. (Hint: ``argsort``, fancy indexing) + +6. Compare (plot) the change in hare population (see + ``help(np.gradient)``) and the number of lynxes. Check correlation + (see ``help(np.corrcoef)``). + +... all without for-loops. + +Solution: :download:`Python source file ` + +Crude integral approximations +----------------------------- + +Write a function ``f(a, b, c)`` that returns :math:`a^b - c`. Form +a 24x12x6 array containing its values in parameter ranges ``[0,1] x +[0,1] x [0,1]``. + +Approximate the 3-d integral + +.. math:: \int_0^1\int_0^1\int_0^1(a^b-c)da\,db\,dc + +over this volume with the mean. The exact result is: :math:`\ln 2 - +\frac{1}{2}\approx0.1931\ldots` --- what is your relative error? + +(Hints: use elementwise operations and broadcasting. +You can make ``np.ogrid`` give a number of points in given range +with ``np.ogrid[0:1:20j]``.) + +**Reminder** Python functions:: + + def f(a, b, c): + return some_result + +Solution: :download:`Python source file ` + +Mandelbrot set +--------------- + +.. plot:: intro/numpy/solutions/2_4_mandelbrot.py + +Write a script that computes the Mandelbrot fractal. The Mandelbrot +iteration:: + + N_max = 50 + some_threshold = 50 + + c = x + 1j*y + + for j in xrange(N_max): + z = z**2 + c + +Point (x, y) belongs to the Mandelbrot set if :math:`|c|` < +``some_threshold``. + +Do this computation by: + +.. For doctests + >>> mask = np.ones((3, 3)) + +1. Construct a grid of c = x + 1j*y values in range [-2, 1] x [-1.5, 1.5] + +2. Do the iteration + +3. Form the 2-d boolean mask indicating which points are in the set + +4. Save the result to an image with: + + .. sourcecode:: pycon + + >>> import matplotlib.pyplot as plt + >>> plt.imshow(mask.T, extent=[-2, 1, -1.5, 1.5]) # doctest: +ELLIPSIS + + >>> plt.gray() + >>> plt.savefig('mandelbrot.png') + +Solution: :download:`Python source file ` + +Markov chain +------------- + +.. image:: images/markov-chain.png + +Markov chain transition matrix ``P``, and probability distribution on +the states ``p``:: + +1. ``0 <= P[i,j] <= 1``: probability to go from state ``i`` to state ``j`` + +2. Transition rule: :math:`p_{new} = P^T p_{old}` + +3. ``all(sum(P, axis=1) == 1)``, ``p.sum() == 1``: normalization + +Write a script that works with 5 states, and: + +- Constructs a random matrix, and normalizes each row so that it + is a transition matrix. + +- Starts from a random (normalized) probability distribution + ``p`` and takes 50 steps => ``p_50`` + +- Computes the stationary distribution: the eigenvector of ``P.T`` + with eigenvalue 1 (numerically: closest to 1) => ``p_stationary`` + +Remember to normalize the eigenvector --- I didn't... + +- Checks if ``p_50`` and ``p_stationary`` are equal to tolerance 1e-5 + +Toolbox: ``np.random.rand``, ``.dot()``, ``np.linalg.eig``, +reductions, ``abs()``, ``argmin``, comparisons, ``all``, +``np.linalg.norm``, etc. + +Solution: :download:`Python source file ` + + diff --git a/intro/numpy/cpu-cacheline.png b/intro/numpy/images/cpu-cacheline.png similarity index 100% rename from intro/numpy/cpu-cacheline.png rename to intro/numpy/images/cpu-cacheline.png diff --git a/intro/numpy/cpu-cacheline.svg b/intro/numpy/images/cpu-cacheline.svg similarity index 100% rename from intro/numpy/cpu-cacheline.svg rename to intro/numpy/images/cpu-cacheline.svg diff --git a/intro/numpy/lenas.png b/intro/numpy/images/lenas.png similarity index 100% rename from intro/numpy/lenas.png rename to intro/numpy/images/lenas.png diff --git a/intro/numpy/markov-chain.png b/intro/numpy/images/markov-chain.png similarity index 100% rename from intro/numpy/markov-chain.png rename to intro/numpy/images/markov-chain.png diff --git a/intro/numpy/markov-chain.svg b/intro/numpy/images/markov-chain.svg similarity index 100% rename from intro/numpy/markov-chain.svg rename to intro/numpy/images/markov-chain.svg diff --git a/intro/numpy/numpy_broadcasting.png b/intro/numpy/images/numpy_broadcasting.png similarity index 100% rename from intro/numpy/numpy_broadcasting.png rename to intro/numpy/images/numpy_broadcasting.png diff --git a/intro/numpy/numpy_fancy_indexing.png b/intro/numpy/images/numpy_fancy_indexing.png similarity index 100% rename from intro/numpy/numpy_fancy_indexing.png rename to intro/numpy/images/numpy_fancy_indexing.png diff --git a/intro/numpy/numpy_indexing.png b/intro/numpy/images/numpy_indexing.png similarity index 100% rename from intro/numpy/numpy_indexing.png rename to intro/numpy/images/numpy_indexing.png diff --git a/intro/numpy/numpy_indexing.svg b/intro/numpy/images/numpy_indexing.svg similarity index 100% rename from intro/numpy/numpy_indexing.svg rename to intro/numpy/images/numpy_indexing.svg diff --git a/intro/numpy/prime-sieve.png b/intro/numpy/images/prime-sieve.png similarity index 100% rename from intro/numpy/prime-sieve.png rename to intro/numpy/images/prime-sieve.png diff --git a/intro/numpy/prime-sieve.svg b/intro/numpy/images/prime-sieve.svg similarity index 100% rename from intro/numpy/prime-sieve.svg rename to intro/numpy/images/prime-sieve.svg diff --git a/intro/numpy/random_walk.png b/intro/numpy/images/random_walk.png similarity index 100% rename from intro/numpy/random_walk.png rename to intro/numpy/images/random_walk.png diff --git a/intro/numpy/random_walk_schema.png b/intro/numpy/images/random_walk_schema.png similarity index 100% rename from intro/numpy/random_walk_schema.png rename to intro/numpy/images/random_walk_schema.png diff --git a/intro/numpy/reductions.png b/intro/numpy/images/reductions.png similarity index 100% rename from intro/numpy/reductions.png rename to intro/numpy/images/reductions.png diff --git a/intro/numpy/reductions.svg b/intro/numpy/images/reductions.svg similarity index 100% rename from intro/numpy/reductions.svg rename to intro/numpy/images/reductions.svg diff --git a/intro/numpy/route66.png b/intro/numpy/images/route66.png similarity index 100% rename from intro/numpy/route66.png rename to intro/numpy/images/route66.png diff --git a/intro/numpy/surf.png b/intro/numpy/images/surf.png similarity index 100% rename from intro/numpy/surf.png rename to intro/numpy/images/surf.png diff --git a/intro/numpy/threefundamental.png b/intro/numpy/images/threefundamental.png similarity index 100% rename from intro/numpy/threefundamental.png rename to intro/numpy/images/threefundamental.png diff --git a/intro/numpy/index.rst b/intro/numpy/index.rst index 289fe7a..2bc0c6c 100644 --- a/intro/numpy/index.rst +++ b/intro/numpy/index.rst @@ -1,15 +1,14 @@ -*********************************************** -NumPy: creating and manipulating numerical data -*********************************************** +************************************************* +NumPy: creación y manipulación de datos numéricos +************************************************* -:authors: Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and Pauli Virtanen +:Autores: Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and Pauli Virtanen -.. .. contents:: Chapters contents +.. .. contents:: Contenido :local: :depth: 4 -This chapter gives an overview of Numpy, the core tool for performant -numerical computing with Python. +En este capítulo se ofrece una visión general de Numpy, la herramienta fundamental para cálculo numérico de alto rendimiento con Python. ____ @@ -20,5 +19,6 @@ ____ operations.rst elaborate_arrays.rst advanced_operations.rst + exercises.rst diff --git a/intro/numpy/operations.rst b/intro/numpy/operations.rst index 8b2a632..37c47f1 100644 --- a/intro/numpy/operations.rst +++ b/intro/numpy/operations.rst @@ -1,296 +1,355 @@ .. For doctests - + >>> import numpy as np >>> np.random.seed(0) .. currentmodule:: numpy -Numerical operations on arrays -================================= +Operaciones numéricas con arreglos +================================== -.. contents:: Section contents +.. contents:: Contenido :local: :depth: 1 +Operaciones elemento a elemento +------------------------------- + +Con escalares + +.. code-block:: python + + >>> a = np.array([1, 2, 3, 4]) + >>> a + 1 + array([2, 3, 4, 5]) + >>> 2**a + array([ 2, 4, 8, 16]) + +Toda las operaciones aritméticas son elemento a elemento -Elementwise operations ----------------------- +.. code-block:: python -With scalars: + >>> b = np.ones(4) + 1 + >>> a - b + array([-1., 0., 1., 2.]) + >>> a * b + array([ 2., 4., 6., 8.]) ->>> a = np.array([1, 2, 3, 4]) ->>> a + 1 -array([2, 3, 4, 5]) ->>> 2**a -array([ 2, 4, 8, 16]) + >>> j = np.arange(5) + >>> 2**(j + 1) - j + array([ 2, 3, 6, 13, 28]) -All arithmetic operates elementwise: +.. warning:: **Multiplicación de arreglos no es multiplicación matricial:** ->>> b = np.ones(4) + 1 ->>> a - b -array([-1., 0., 1., 2.]) ->>> a * b -array([ 2., 4., 6., 8.]) + .. code-block:: python ->>> j = np.arange(5) ->>> 2**(j + 1) - j -array([ 2, 3, 6, 13, 28]) + >>> c = np.ones((3, 3)) + >>> c * c # no es multiplicación matricial! + array([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) -.. warning:: **Array multiplication is not matrix multiplication:** +.. note:: **Multiplicación matricial:** - >>> c = np.ones((3, 3)) - >>> c * c # NOT matrix multiplication! - array([[ 1., 1., 1.], - [ 1., 1., 1.], - [ 1., 1., 1.]]) + .. code-block:: python -.. note:: **Matrix multiplication:** + >>> c.dot(c) # tambien, np.dot(c, c) + array([[ 3., 3., 3.], + [ 3., 3., 3.], + [ 3., 3., 3.]]) - >>> c.dot(c) - array([[ 3., 3., 3.], - [ 3., 3., 3.], - [ 3., 3., 3.]]) +Comparaciones -Comparisons:: +.. code-block:: python - >>> a = np.array([1, 2, 3, 4]) - >>> b = np.array([4, 2, 2, 4]) - >>> a == b - array([False, True, False, True], dtype=bool) - >>> a > b - array([False, False, True, False], dtype=bool) + >>> a = np.array([1, 2, 3, 4]) + >>> b = np.array([4, 2, 2, 4]) + >>> a == b + array([False, True, False, True], dtype=bool) + >>> a > b + array([False, False, True, False], dtype=bool) -Logical operations:: +Operaciones logicas - >>> a = np.array([1, 1, 0, 0], dtype=bool) - >>> b = np.array([1, 0, 1, 0], dtype=bool) - >>> np.logical_or(a, b) - array([ True, True, True, False], dtype=bool) - >>> np.logical_and(a, b) - array([ True, False, False, False], dtype=bool) +.. code-block:: python -Shape mismatches:: + >>> a = np.array([1, 1, 0, 0], dtype=bool) + >>> b = np.array([1, 0, 1, 0], dtype=bool) + >>> np.logical_or(a, b) + array([ True, True, True, False], dtype=bool) + >>> np.logical_and(a, b) + array([ True, False, False, False], dtype=bool) - >>> a = np.arange(4) - >>> a - array([0, 1, 2, 3]) - >>> a + np.array([1, 2]) # doctest: +SKIP - Traceback (most recent call last): - File "", line 1, in - ValueError: shape mismatch: objects cannot be broadcast to a single shape +Desajustes de forma -**'Broadcast'?** We'll return to that :ref:`later `. +.. code-block:: python -**Transposition**:: + >>> a = np.arange(4) + >>> a + np.array([1, 2]) + Traceback (most recent call last): + File "", line 1, in + ValueError: operands could not be broadcast together with shapes (4) (2) - >>> a = np.triu(np.ones((3, 3)), 1) # see help(np.triu) - >>> a - array([[ 0., 1., 1.], - [ 0., 0., 1.], - [ 0., 0., 0.]]) - >>> a.T - array([[ 0., 0., 0.], - [ 1., 0., 0.], - [ 1., 1., 0.]]) +**Broadcasting?** lo veremos :ref:`despues `. -.. note:: **Linear algebra** +Transposición - The sub-module :mod:`np.linalg` implements basic linear algebra, such as - solving linear systems, singular value decomposition, etc. However, it is - not guaranteed to be compiled using efficient routines, and thus we - recommend the use of :mod:`scipy.linalg`, as detailed in section - :ref:`scipy_linalg` +.. code-block:: python -.. topic:: Exercise - :class: green + >>> a = np.triu(np.ones((3, 3)), 1) # ver help(np.triu) + >>> a + array([[ 0., 1., 1.], + [ 0., 0., 1.], + [ 0., 0., 0.]]) + >>> a.T # tambien, a.transpose() + array([[ 0., 0., 0.], + [ 1., 0., 0.], + [ 1., 1., 0.]]) - Generate arrays `[2**0, 2**1, 2**2, 2**3, 2**4]` and - `a_j = 2^(3*j) - j` +.. note:: **Algebra linear** + El submódulo :mod:`numpy.linalg` implementa el álgebra lineal básico, como resolución de sistemas lineales, descomposición en valores singulares, etc. Sin embargo, esto no garantiza que sea compilado utilizando rutinas eficientes, y por lo tanto se recomienda el uso de :mod:`scipy.linalg`, como se detalla en la sección :ref:`scipy_linalg` -Basic reductions ----------------- +.. topic:: Ejercicio + :class: green + + Generar los arreglos ``[2**0, 2**1, 2**2, 2**3, 2**4]`` y ``a_j = 2^(3*j) - j`` + +Reducciones básicas +------------------- -Computing sums: +Cálculando sumas ->>> x = np.array([1, 2, 3, 4]) ->>> np.sum(x) -10 ->>> x.sum() -10 +.. code-block:: python -.. image:: reductions.png + >>> x = np.array([1, 2, 3, 4]) + >>> np.sum(x) + 10 + >>> x.sum() + 10 + +.. image:: images/reductions.png :align: right -Sum by rows and by columns:: +Suma por filas y por columnas - >>> x = np.array([[1, 1], [2, 2]]) - >>> x - array([[1, 1], - [2, 2]]) - >>> x.sum(axis=0) # columns (first dimension) - array([3, 3]) - >>> x[:, 0].sum(), x[:, 1].sum() - (3, 3) - >>> x.sum(axis=1) # rows (second dimension) - array([2, 4]) - >>> x[0, :].sum(), x[1, :].sum() - (2, 4) +.. code-block:: python -Same idea in higher dimensions:: + >>> x = np.array([[1, 1], [2, 2]]) + >>> x + array([[1, 1], + [2, 2]]) + >>> x.sum(axis=0) # columna (primera dimensión) + array([3, 3]) + >>> x[:, 0].sum(), x[:, 1].sum() + (3, 3) + >>> x.sum(axis=1) # fila (segunda dimensión) + array([2, 4]) + >>> x[0, :].sum(), x[1, :].sum() + (2, 4) - >>> x = np.random.rand(2, 2, 2) - >>> x.sum(axis=2)[0, 1] # doctest: +ELLIPSIS - 1.14764... - >>> x[0, 1, :].sum() # doctest: +ELLIPSIS - 1.14764... +.. tip:: El mismo procedimiento para arreglos multidimensionales -**Other reductions** --- works the same way (and take ``axis=``) + .. code-block:: python -- Statistics: + >>> x = np.random.rand(2, 2, 2) + >>> x.sum(axis=2)[0, 1] + 1.14764... + >>> x[0, 1, :].sum() + 1.14764... - >>> x = np.array([1, 2, 3, 1]) - >>> y = np.array([[1, 2, 3], [5, 6, 1]]) - >>> x.mean() - 1.75 - >>> np.median(x) - 1.5 - >>> np.median(y, axis=-1) # last axis - array([ 2., 5.]) +**Otras reducciones** --- funcionan de la misma manera (también ``axis=``) - >>> x.std() # full population standard dev. - 0.82915619758884995 +- Estadística -- Extrema: + .. code-block:: python - >>> x = np.array([1, 3, 2]) - >>> x.min() - 1 - >>> x.max() - 3 + >>> x = np.array([1, 2, 3, 1]) + >>> y = np.array([[1, 2, 3], [5, 6, 1]]) + >>> x.mean() + 1.75 + >>> np.median(x) + 1.5 + >>> np.median(y, axis=-1) # la ultima dimensión + array([ 2., 5.]) + >>> x.std() # desviación estándar de población (no muestra). + 0.82915619758884995 - >>> x.argmin() # index of minimum - 0 - >>> x.argmax() # index of maximum - 1 +- Valores extremos -- Logical operations: + .. code-block:: python - >>> np.all([True, True, False]) - False - >>> np.any([True, True, False]) - True + >>> x = np.array([1, 3, 2]) + >>> x.min() + 1 + >>> x.max() + 3 + >>> x.argmin() # índice del valor mínimo + 0 + >>> x.argmax() # índice del valor máximo + 1 - .. note:: +- Operaciones lógicas - Can be used for array comparisons: + .. code-block:: python - >>> a = np.zeros((100, 100)) - >>> np.any(a != 0) + >>> np.all([True, True, False]) False - >>> np.all(a == a) + >>> np.any([True, True, False]) True - >>> a = np.array([1, 2, 3, 2]) - >>> b = np.array([2, 2, 3, 2]) - >>> c = np.array([6, 4, 4, 5]) - >>> ((a <= b) & (b <= c)).all() - True + .. note:: Puede ser usado para comparar arreglos + + .. code-block:: python + + >>> a = np.zeros((100, 100)) + >>> np.any(a != 0) + False + >>> np.all(a == a) + True + >>> a = np.array([1, 2, 3, 2]) + >>> b = np.array([2, 2, 3, 2]) + >>> c = np.array([6, 4, 4, 5]) + >>> ((a <= b) & (b <= c)).all() + True + +- ... y muchos más (mejor para aprender sobre la marcha). + +.. topic:: Ejemplo: datos estadísticos + + Datos en :download:`populations.txt <../../data/populations.txt>` describe las poblaciones de liebres y linces (y zanahorias) en el norte de Canadá durante 20 años. + + Primero graficamos los datos + + .. code-block:: python + + >>> datos = np.loadtxt('data/populations.txt') + >>> year, liebres, linces, zanahorias = datos.T # truco: columnas a variables + >>> import matplotlib.pyplot as plt + >>> plt.axes([0.2, 0.1, 0.5, 0.8]) + + >>> plt.plot(year, liebres, year, linces, year, zanahorias) + [, ...] + >>> plt.legend(('Liebre', 'Lince', 'Zanahoria'), loc=(1.05, 0.5)) + + >>> plt.show() + + .. plot:: pyplots/numpy_intro_4.py -- ... and many more (best to learn as you go). + La media de cada población son -.. topic:: Example: data statistics + .. code-block:: python - Data in :download:`populations.txt <../../data/populations.txt>` - describes the populations of hares and lynxes (and carrots) in northern - Canada during 20 years. + >>> poblaciones = datos[:, 1:] + >>> poblaciones.mean(axis=0) + array([ 34080.95238095, 20166.66666667, 42400. ]) - We can first plot the data:: + Las desviaciones estándar son - >>> data = np.loadtxt('data/populations.txt') - >>> year, hares, lynxes, carrots = data.T # trick: columns to variables + .. code-block:: python - >>> from matplotlib import pyplot as plt - >>> plt.axes([0.2, 0.1, 0.5, 0.8]) # doctest: +ELLIPSIS - - >>> plt.plot(year, hares, year, lynxes, year, carrots) # doctest: +ELLIPSIS - [, ...] - >>> plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5)) # doctest: +ELLIPSIS - + >>> poblaciones.std(axis=0) + array([ 20897.90645809, 16254.59153691, 3322.50622558]) - .. plot:: pyplots/numpy_intro_4.py + Qué especie tiene la mayor población cada año? - The mean populations over time:: + .. code-block:: python - >>> populations = data[:, 1:] - >>> populations.mean(axis=0) - array([ 34080.95238095, 20166.66666667, 42400. ]) + >>> np.argmax(poblaciones, axis=1) + array([2, 2, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 1, 2, 2, 2, 2, 2]) - The sample standard deviations:: + Si no se comprende lo anterior imprimimos los índices: - >>> populations.std(axis=0) - array([ 20897.90645809, 16254.59153691, 3322.50622558]) + .. code-block:: python - Which species has the highest population each year? + >>> for fila, columna in enumerate(np.argmax(poblaciones, axis=1)): + ... print fila, columna + ... + 0 2 + 1 2 + 2 0 + 3 0 + 4 1 + 5 1 + 6 2 + 7 2 + 8 2 + 9 2 + 10 2 + 11 2 + 12 0 + 13 0 + 14 0 + 15 1 + 16 2 + 17 2 + 18 2 + 19 2 + 20 2 - >>> np.argmax(populations, axis=1) - array([2, 2, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 1, 2, 2, 2, 2, 2]) +.. topic:: Ejemplo: simulación de difusión usando el algoritmo random walk -.. topic:: Example: diffusion simulation using a random walk algorithm + .. image:: images/random_walk.png + :align: center - .. image:: random_walk.png - :align: center + Cuál es la distancia típica al origen en un recorrido al azar después de ``t`` saltos a la derecha o izquierda? - What is the typical distance from the origin of a random walker after - ``t`` left or right jumps? + .. only:: latex - .. only:: latex + .. image:: images/random_walk_schema.png + :align: center - .. image:: random_walk_schema.png - :align: center + .. only:: html - .. only:: html + .. image:: images/random_walk_schema.png + :align: center + :width: 100% - .. image:: random_walk_schema.png - :align: center - :width: 100% + .. code-block:: python - >>> n_stories = 1000 # number of walkers - >>> t_max = 200 # time during which we follow the walker + >>> numero_recorridos = 1000 # número de recorridos + >>> tiempo_maximo = 200 # tiempo de duración de cada recorrido - We randomly choose all the steps 1 or -1 of the walk:: + Elegimos al azar todos los pasos 1 o -1 del recorrido - >>> t = np.arange(t_max) - >>> steps = 2 * np.random.random_integers(0, 1, (n_stories, t_max)) - 1 - >>> np.unique(steps) # Verification: all steps are 1 or -1 - array([-1, 1]) + .. code-block:: python - We build the walks by summing steps along the time:: + >>> tiempo = np.arange(tiempo_maximo) + >>> pasos = 2 * np.random.random_integers(0, 1, (numero_recorridos, tiempo_maximo)) - 1 + >>> np.unique(pasos) # Verificación: todos los pasos son 1 o -1 + array([-1, 1]) - >>> positions = np.cumsum(steps, axis=1) # axis = 1: dimension of time - >>> sq_distance = positions**2 + Construimos los recorridos como la suma de los pasos a lo largo del tiempo - We get the mean in the axis of the stories:: + .. code-block:: python - >>> mean_sq_distance = np.mean(sq_distance, axis=0) + >>> posiciones = np.cumsum(pasos, axis=1) # eje = 1: dimensión tiempo + >>> distancias_al_cuadrado = posiciones**2 - Plot the results:: + Obtenemos la media en el eje de los recorridos - >>> plt.figure(figsize=(4, 3)) # doctest: +ELLIPSIS - - >>> plt.plot(t, np.sqrt(mean_sq_distance), 'g.', t, np.sqrt(t), 'y-') # doctest: +ELLIPSIS - [, ] - >>> plt.xlabel(r"$t$") # doctest: +ELLIPSIS - - >>> plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$") # doctest: +ELLIPSIS - - + .. code-block:: python - .. plot:: pyplots/numpy_intro_5.py + >>> media_distancias_al_cuadrado = np.mean(distancias_al_cuadrado, axis=0) -The RMS distance grows as the square root of the time! + graficamos el resultado + .. code-block:: python + + >>> plt.figure(figsize=(8, 6)) + + >>> plt.plot(tiempo, np.sqrt(media_distancias_al_cuadrado), 'g.', tiempo, np.sqrt(tiempo), 'y-') + [, ] + >>> plt.xlabel(r'$tiempo$') + + >>> plt.ylabel(r'$\sqrt{\Delta x^{2}}$') + + >>> plt.show() + + .. plot:: pyplots/numpy_intro_5.py + + La distancia RMS (raíz media cuadrática) crece como la raíz cuadrada del tiempo! .. arithmetic: sum/prod/mean/std @@ -311,82 +370,82 @@ The RMS distance grows as the square root of the time! Broadcasting ------------ -* Basic operations on ``numpy`` arrays (addition, etc.) are elementwise +* Operaciones básicas en arreglos ``numpy`` (suma, etc) son elemento a elemento. -* This works on arrays of the same size. +* Esto funciona con arreglos del mismo tamaño. - | **Nevertheless**, It's also possible to do operations on arrays of different - | sizes if *Numpy* can transform these arrays so that they all have - | the same size: this conversion is called **broadcasting**. + **No obstante!**, también es posible hacer operaciones con matrices de diferentes tamaños si *Numpy* puede transformar estos arreglos en arreglos del mismo tamaño: esta conversión se llama **broadcasting**. -The image below gives an example of broadcasting: +La siguiente imagen muestra un ejemplo de broadcasting: .. only:: latex - .. image:: numpy_broadcasting.png - :align: center + .. image:: images/numpy_broadcasting.png + :align: center .. only:: html - .. image:: numpy_broadcasting.png - :align: center - :width: 100% - -Let's verify:: - - >>> a = np.tile(np.arange(0, 40, 10), (3, 1)).T - >>> a - array([[ 0, 0, 0], - [10, 10, 10], - [20, 20, 20], - [30, 30, 30]]) - >>> b = np.array([0, 1, 2]) - >>> a + b - array([[ 0, 1, 2], - [10, 11, 12], - [20, 21, 22], - [30, 31, 32]]) - -An useful trick: - - >>> a = np.arange(0, 40, 10) - >>> a.shape - (4,) - >>> a = a[:, np.newaxis] # adds a new axis -> 2D array - >>> a.shape - (4, 1) - >>> a - array([[ 0], - [10], - [20], - [30]]) - >>> a + b - array([[ 0, 1, 2], - [10, 11, 12], - [20, 21, 22], - [30, 31, 32]]) - -We have already used broadcasting without knowing it!:: - - >>> a = np.ones((4, 5)) - >>> a[0] = 2 # we assign an array of dimension 0 to an array of dimension 1 - >>> a - array([[ 2., 2., 2., 2., 2.], - [ 1., 1., 1., 1., 1.], - [ 1., 1., 1., 1., 1.], - [ 1., 1., 1., 1., 1.]]) - -Broadcasting seems a bit magical, but it is actually quite natural to use it -when we want to solve a problem whose output data is an array with more -dimensions than input data. - -.. topic:: Example - - Let's construct an array of distances (in miles) between cities of - Route 66: Chicago, Springfield, Saint-Louis, Tulsa, Oklahoma City, - Amarillo, Santa Fe, Albuquerque, Flagstaff and Los Angeles. - - :: + .. image:: images/numpy_broadcasting.png + :align: center + :width: 100% + +Vamos a verificarlo + +.. code-block:: python + + >>> a = np.tile(np.arange(0, 40, 10), (3, 1)).T + >>> a + array([[ 0, 0, 0], + [10, 10, 10], + [20, 20, 20], + [30, 30, 30]]) + >>> b = np.array([0, 1, 2]) + >>> a + b + array([[ 0, 1, 2], + [10, 11, 12], + [20, 21, 22], + [30, 31, 32]]) + +Un truco útil + +.. code-block:: python + + >>> a = np.arange(0, 40, 10) + >>> a.shape + (4,) + >>> a = a[:, np.newaxis] # adds a new axis -> 2D array + >>> a.shape + (4, 1) + >>> a + array([[ 0], + [10], + [20], + [30]]) + >>> a + b + array([[ 0, 1, 2], + [10, 11, 12], + [20, 21, 22], + [30, 31, 32]]) + +Ya hemos usado broadcasting sin saberlo! + +.. code-block:: python + + >>> a = np.ones((4, 5)) + >>> a[0] = 2 # we assign an array of dimension 0 to an array of dimension 1 + >>> a + array([[ 2., 2., 2., 2., 2.], + [ 1., 1., 1., 1., 1.], + [ 1., 1., 1., 1., 1.], + [ 1., 1., 1., 1., 1.]]) + +.. tip:: El broadcasting parece un poco mágico, pero en realidad es bastante natural usarlo cuando queremos resolver un problema cuya salida de datos es una matriz con más dimensiones que los datos de entrada. + +.. topic:: Ejemplo + + Vamos a construir un arreglo de distancias (en millas) entre las ciudades de la Ruta 66: Chicago, Springfield, Saint-Louis, Tulsa, Oklahoma City, Amarillo, Santa Fe, Albuquerque, Flagstaff y Los Angeles. + + .. code-block:: python >>> mileposts = np.array([0, 198, 303, 736, 871, 1175, 1475, 1544, ... 1913, 2448]) @@ -404,66 +463,69 @@ dimensions than input data. [2448, 2250, 2145, 1712, 1577, 1273, 973, 904, 535, 0]]) - .. image:: route66.png - :align: center - :scale: 60 + .. image:: images/route66.png + :align: center + :scale: 60 + +Una gran cantidad de problemas basados ​​en mallas o redes también puede utilizar broadcasting. Por ejemplo, si queremos calcular la distancia de el origen de los puntos en una cuadrícula de 10x10, se puede hacer -A lot of grid-based or network-based problems can also use -broadcasting. For instance, if we want to compute the distance from -the origin of points on a 10x10 grid, we can do:: +.. code-block:: python - >>> x, y = np.arange(5), np.arange(5) - >>> distance = np.sqrt(x ** 2 + y[:, np.newaxis] ** 2) - >>> distance - array([[ 0. , 1. , 2. , 3. , 4. ], - [ 1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], - [ 2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], - [ 3. , 3.16227766, 3.60555128, 4.24264069, 5. ], - [ 4. , 4.12310563, 4.47213595, 5. , 5.65685425]]) + >>> x, y = np.arange(5), np.arange(5) + >>> distance = np.sqrt(x ** 2 + y[:, np.newaxis] ** 2) + >>> distance + array([[ 0. , 1. , 2. , 3. , 4. ], + [ 1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], + [ 2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], + [ 3. , 3.16227766, 3.60555128, 4.24264069, 5. ], + [ 4. , 4.12310563, 4.47213595, 5. , 5.65685425]]) - Or in color:: +O en colores - >>> plt.pcolor(distance) # doctest: +ELLIPSIS - - >>> plt.colorbar() # doctest: +ELLIPSIS - - >>> plt.axis('equal') - (0.0, 200.0, 0.0, 16.0) +.. code-block:: python + + >>> plt.pcolor(distance) # doctest: +ELLIPSIS + + >>> plt.colorbar() # doctest: +ELLIPSIS + + >>> plt.axis('equal') + (0.0, 200.0, 0.0, 16.0) .. plot:: pyplots/numpy_intro_6.py +**Observación**: la función ``numpy.ogrid`` permite crear directamente vectores x +e y del ejemplo anterior, con dos "dimensiones significativas" + +.. code-block:: python -**Remark** : the ``numpy.ogrid`` function allows to directly create vectors x -and y of the previous example, with two "significant dimensions":: - - >>> x, y = np.ogrid[0:5, 0:5] - >>> x, y - (array([[0], - [1], - [2], - [3], - [4]]), array([[0, 1, 2, 3, 4]])) - >>> x.shape, y.shape - ((5, 1), (1, 5)) - >>> distance = np.sqrt(x ** 2 + y ** 2) - -So, ``np.ogrid`` is very useful as soon as we have to handle computations on a -grid. On the other hand, ``np.mgrid`` directly provides matrices full of -indices for cases where we can't (or don't want to) benefit from broadcasting:: - - >>> x, y = np.mgrid[0:4, 0:4] - >>> x - array([[0, 0, 0, 0], - [1, 1, 1, 1], - [2, 2, 2, 2], - [3, 3, 3, 3]]) - >>> y - array([[0, 1, 2, 3], - [0, 1, 2, 3], - [0, 1, 2, 3], - [0, 1, 2, 3]]) - -However, in practice, this is rarely needed! + >>> x, y = np.ogrid[0:5, 0:5] + >>> x, y + (array([[0], + [1], + [2], + [3], + [4]]), array([[0, 1, 2, 3, 4]])) + >>> x.shape, y.shape + ((5, 1), (1, 5)) + >>> distance = np.sqrt(x ** 2 + y ** 2) + +.. tip:: Por tanto, ``np.ogrid`` es muy útil para manejar cálculos sobre una malla. Por otro lado, ``np.mgrid`` proporciona directamente matrices llenas de índices para los casos en que no pueda (o no desee hacer) beneficiarse del broadcasting + + .. code-block:: python + + >>> x, y = np.mgrid[0:4, 0:4] + >>> x + array([[0, 0, 0, 0], + [1, 1, 1, 1], + [2, 2, 2, 2], + [3, 3, 3, 3]]) + >>> y + array([[0, 1, 2, 3], + [0, 1, 2, 3], + [0, 1, 2, 3], + [0, 1, 2, 3]]) + + Sin embargo, en la práctica, esto casi nunca se necesita! .. rules @@ -477,121 +539,144 @@ However, in practice, this is rarely needed! .. CHA: constructing grids -- meshgrid using only newaxis -Array shape manipulation ------------------------- +Manipulando las dimensiones de un arreglo +----------------------------------------- + +Aplanado +........ -Flattening -........... +.. code-block:: python ->>> a = np.array([[1, 2, 3], [4, 5, 6]]) ->>> a.ravel() -array([1, 2, 3, 4, 5, 6]) ->>> a.T -array([[1, 4], + >>> a = np.array([[1, 2, 3], [4, 5, 6]]) + >>> a.ravel() + array([1, 2, 3, 4, 5, 6]) + >>> a.T + array([[1, 4], [2, 5], [3, 6]]) ->>> a.T.ravel() -array([1, 4, 2, 5, 3, 6]) + >>> a.T.ravel() + array([1, 4, 2, 5, 3, 6]) -Higher dimensions: last dimensions ravel out "first". +Dimensiones superiores: las últimos dimensiones son las "primeras". Reshaping ......... -The inverse operation to flattening:: +La operación inversa a aplanar + +.. code-block:: python + + >>> a.shape + (2, 3) + >>> b = a.ravel() + >>> b.reshape((2, 3)) + array([[1, 2, 3], + [4, 5, 6]]) + +O, + +.. code-block:: python + + >>> a.reshape((2, -1)) # unspecified (-1) value is inferred - >>> a.shape - (2, 3) - >>> b = a.ravel() - >>> b.reshape((2, 3)) - array([[1, 2, 3], - [4, 5, 6]]) +.. warning:: ``ndarray.reshape`` **puede** devolver una vista (cf ``help(np.reshape)``)), o copia -Creating an array with a different shape, from another array:: +.. tip:: - >>> a = np.arange(36) - >>> b = a.reshape((6, 6)) - >>> b - array([[ 0, 1, 2, 3, 4, 5], - [ 6, 7, 8, 9, 10, 11], - [12, 13, 14, 15, 16, 17], - [18, 19, 20, 21, 22, 23], - [24, 25, 26, 27, 28, 29], - [30, 31, 32, 33, 34, 35]]) + .. code-block:: python -Or, :: + >>> b[0, 0] = 99 + >>> a + array([99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, + 34, 35]) - >>> b = a.reshape((6, -1)) # unspecified (-1) value is inferred + Cuidado: reshape también pueden devolver una copia! -Views and copies -................ + .. code-block:: python -``ndarray.reshape`` **may** return a view (cf ``help(np.reshape)``)), -not a copy: + >>> a = np.zeros((3, 2)) + >>> b = a.T.reshape(3*2) + >>> b[0] = 9 + >>> a + array([[ 0., 0.], + [ 0., 0.], + [ 0., 0.]]) ->>> b[0, 0] = 99 ->>> a -array([99, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, - 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, - 34, 35]) + Para entender, consulte la sección sobre :ref: `el diseño de memoria de un arreglo ` más abajo. -Beware: reshape may also return a copy! +Agregando una dimensión +....................... ->>> a = np.zeros((3, 2)) ->>> b = a.T.reshape(3*2) ->>> b[0] = 9 ->>> a -array([[ 0., 0.], - [ 0., 0.], - [ 0., 0.]]) +Indexando con el objeto ``np.newaxis`` nos permite agregar un eje a un arreglo -To understand, see the section on :ref:`the memory layout of an array ` below. +.. code-block:: python -Dimension shuffling -.................... + >>> z = np.array([1, 2, 3]) + >>> z + array([1, 2, 3]) ->>> a = np.arange(4*3*2).reshape(4, 3, 2) ->>> a.shape -(4, 3, 2) ->>> a[0, 2, 1] -5 ->>> b = a.transpose(1, 2, 0) ->>> b.shape -(3, 2, 4) ->>> b[2, 1, 0] -5 + >>> z[:, np.newaxis] + array([[1], + [2], + [3]]) -Also creates a view:: + >>> z[np.newaxis, :] + array([[1, 2, 3]]) - >>> b[2, 1, 0] = -1 - >>> a[0, 2, 1] - -1 +Cambiando dimensiones +..................... + +.. code-block:: python + + >>> a = np.arange(4*3*2).reshape(4, 3, 2) + >>> a.shape + (4, 3, 2) + >>> a[0, 2, 1] + 5 + >>> b = a.transpose(1, 2, 0) + >>> b.shape + (3, 2, 4) + >>> b[2, 1, 0] + 5 + +También crea una vista + +.. code-block:: python + + >>> b[2, 1, 0] = -1 + >>> a[0, 2, 1] + -1 Resizing -......... +........ + +El tamaño de un arreglo se puede cambiar con ``ndarray.resize`` -Size of an array can be changed with ``ndarray.resize``:: +.. code-block:: python - >>> a = np.arange(4) - >>> a.resize((8,)) - >>> a - array([0, 1, 2, 3, 0, 0, 0, 0]) + >>> a = np.arange(4) + >>> a.resize((8,)) + >>> a + array([0, 1, 2, 3, 0, 0, 0, 0]) -However, it must not be referred to somewhere else:: +Sin embargo, no debe ser referenciado a otro objeto: - >>> b = a - >>> a.resize((4,)) # doctest: +SKIP - ... - ValueError: cannot resize an array references or is referenced - by another array in this way. Use the resize function +.. code-block:: python -Some examples of real-world use cases -...................................... + >>> b = a + >>> a.resize((4,)) # doctest: +SKIP + Traceback (most recent call last): + File "", line 1, in + ValueError: cannot resize an array that has been referenced or is + referencing another array in this way. Use the resize function -.. topic:: Case 2.a: Calling (legacy) Fortran code +Algunos ejemplos del mundo real +............................... - Shape-preserving functions with elementwise non-Python - routines. For instance, Fortran +.. topic:: Caso 2.a: Llamando código (legado) Fortran + + Funciones y rutinas no Python. Por ejemplo, Fortran .. sourcecode:: fortran @@ -603,34 +688,34 @@ Some examples of real-world use cases b = a + 1 end subroutine some_function - We can use f2py to wrap this fortran code in Python: + Podemos utilizar f2py para envolver código Fortran en Python: ``f2py -c -m fortran_module 2_a_fortran_module.f90`` .. sourcecode:: python - import numpy as np - import fortran_module + import numpy as np + import fortran_module - def some_function(input): - """ - Call a Fortran routine, and preserve input shape - """ - input = np.asarray(input) - # fortran_module.some_function() takes 1-D arrays! - output = fortran_module.some_function(input.ravel()) - return output.reshape(input.shape) + def some_function(input): + """ + Call a Fortran routine, and preserve input shape + """ + input = np.asarray(input) + # fortran_module.some_function() takes 1-D arrays! + output = fortran_module.some_function(input.ravel()) + return output.reshape(input.shape) - print some_function(np.array([1, 2, 3])) - print some_function(np.array([[1, 2], [3, 4]])) + print some_function(np.array([1, 2, 3])) + print some_function(np.array([[1, 2], [3, 4]])) - # -> - # [ 2. 3. 4.] - # [[ 2. 3.] - # [ 4. 5.]] + # -> + # [ 2. 3. 4.] + # [[ 2. 3.] + # [ 4. 5.]] -.. topic:: Case 2.b: Block matrices and vectors (and tensors) +.. topic:: Caso 2.b: Bloques de matrices y vectores (y tensores) - Vector space: quantum level :math:`\otimes` spin + Vector espacio: nivel cuántico :math:`\otimes` spin .. math:: @@ -651,16 +736,17 @@ Some examples of real-world use cases \psi_{2\uparrow} \\ \psi_{2\downarrow} \end{pmatrix} - In short: for **block matrices and vectors**, it can be useful - to preserve the **block structure**. + En resumen: para **bloques de matrices y vectores**, puede ser útil preservar la **estructura de bloque**. + + En Numpy - In Numpy:: + .. code-block:: python - >>> psi = np.zeros((2, 2)) # dimensions: level, spin - >>> psi[0, 1] # <-- psi_{1,downarrow} - 0.0 + >>> psi = np.zeros((2, 2)) # dimensions: level, spin + >>> psi[0, 1] # <-- psi_{1,downarrow} + 0.0 - Linear operators on such block vectors have similar block structure: + Los operadores lineales en tales bloques de vectores tienen una estructura de bloques similar: .. math:: @@ -682,23 +768,25 @@ Some examples of real-world use cases \qquad \ldots - >>> H = np.zeros((2, 2, 2, 2)) # dimensions: level1, level2, spin1, spin2 - >>> h_11 = H[0,0,:,:] - >>> V = H[0,1] + .. code-block:: python - Doing the matrix product: get rid of the block structure, do the - 4x4 matrix product, then put it back + >>> H = np.zeros((2, 2, 2, 2)) # dimensions: level1, level2, spin1, spin2 + >>> h_11 = H[0,0,:,:] + >>> V = H[0,1] + + Para hacer el producto matricial: nos deshacemos de la estructura de bloques, hacemos el producto de la matriz 4x4, a continuación de nuevo .. math:: \check{H}\check{\psi} - >>> def mdot(operator, psi): - ... return operator.transpose(0, 2, 1, 3).reshape(4, 4).dot( - ... psi.reshape(4)).reshape(2, 2) + .. code-block:: python + + >>> def mdot(operator, psi): + ... return operator.transpose(0, 2, 1, 3).reshape(4, 4).dot( + ... psi.reshape(4)).reshape(2, 2) - I.e., reorder dimensions first to ``level1, spin1, level2, spin2`` - and then reshape => correct matrix product. + Es decir, cambiamos el orden de las dimensiones primero a ``level1, spin1, level2, spin2`` y luego reshape => producto matriz correcto. .. seealso: ``help(np.tensordot)`` @@ -717,46 +805,53 @@ Some examples of real-world use cases .. EXE: shuffling dimensions when writing a general vectorized function .. CHA: the mathematical 'vec' operation -Sorting data ------------- +Ordenando datos +--------------- + +Ordenando a lo largo de un eje + +.. code-block:: python -Sorting along an axis:: + >>> a = np.array([[4, 3, 5], [1, 2, 1]]) + >>> b = np.sort(a, axis=1) + >>> b + array([[3, 4, 5], + [1, 1, 2]]) - >>> a = np.array([[4, 3, 5], [1, 2, 1]]) - >>> b = np.sort(a, axis=1) - >>> b - array([[3, 4, 5], - [1, 1, 2]]) +.. note:: Ordena filas y columnas por separado! -.. note:: Sorts each row separately! +Ordenar y reemplazar -In-place sort:: +.. code-block:: python - >>> a.sort(axis=1) - >>> a - array([[3, 4, 5], - [1, 1, 2]]) + >>> a.sort(axis=1) + >>> a + array([[3, 4, 5], + [1, 1, 2]]) -Sorting with fancy indexing:: +Ordenar con indexado fancy - >>> a = np.array([4, 3, 1, 2]) - >>> j = np.argsort(a) - >>> j - array([2, 3, 1, 0]) - >>> a[j] - array([1, 2, 3, 4]) +.. code-block:: python -Finding minima and maxima:: + >>> a = np.array([4, 3, 1, 2]) + >>> j = np.argsort(a) + >>> j + array([2, 3, 1, 0]) + >>> a[j] + array([1, 2, 3, 4]) - >>> a = np.array([4, 3, 1, 2]) - >>> j_max = np.argmax(a) - >>> j_min = np.argmin(a) - >>> j_max, j_min - (0, 2) +Buscando los valores mínimos y máximos +.. code-block:: python + + >>> a = np.array([4, 3, 1, 2]) + >>> j_max = np.argmax(a) + >>> j_min = np.argmin(a) + >>> j_max, j_min + (0, 2) .. XXX: need a frame for summaries - + * Arithmetic etc. are elementwise operations * Basic linear algebra, ``.dot()`` * Reductions: ``sum(axis=1)``, ``std()``, ``all()``, ``any()`` @@ -765,273 +860,31 @@ Finding minima and maxima:: * Fancy indexing: ``a[a > 3]``, ``a[[2, 3]]`` * Sorting data: ``.sort()``, ``np.sort``, ``np.argsort``, ``np.argmax`` -Some exercises ----------------- - -.. topic:: Worked example: Framing Lena - :class: green - - Let's do some manipulations on numpy arrays by starting with the - famous image of Lena (http://www.cs.cmu.edu/~chuck/lennapg/). - ``scipy`` provides a 2D array of this image with the ``scipy.lena`` - function:: - - >>> from scipy import misc - >>> lena = misc.lena() - - **Note:** In older versions of scipy, you will find lena under - `scipy.lena()` - - Here are a few images we will be able to obtain with our manipulations: - use different colormaps, crop the image, change some parts of the image. - - .. image:: lenas.png - :align: center - - * Let's use the imshow function of pylab to display the image. - - .. sourcecode:: ipython - - In [3]: import pylab as plt - In [4]: lena = misc.lena() - In [5]: plt.imshow(lena) - - * Lena is then displayed in false colors. A colormap must be - specified for her to be displayed in grey. - - .. sourcecode:: ipython - - In [6]: plt.imshow(lena, cmap=plt.cm.gray) - - * Create an array of the image with a narrower centering : for example, - remove 30 pixels from all the borders of the image. To check the result, - display this new array with ``imshow``. - - .. sourcecode:: ipython - - In [9]: crop_lena = lena[30:-30,30:-30] - - * We will now frame Lena's face with a black locket. For this, we - need to create a mask corresponding to the pixels we want to be - black. The mask is defined by this condition ``(y-256)**2 + - (x-256)**2`` - - .. sourcecode:: ipython - - In [15]: y, x = np.ogrid[0:512,0:512] # x and y indices of pixels - In [16]: y.shape, x.shape - Out[16]: ((512, 1), (1, 512)) - In [17]: centerx, centery = (256, 256) # center of the image - In [18]: mask = ((y - centery)**2 + (x - centerx)**2) > 230**2 # circle - - then we assign the value 0 to the pixels of the image corresponding - to the mask. The syntax is extremely simple and intuitive: - - .. sourcecode:: ipython - - In [19]: lena[mask] = 0 - In [20]: plt.imshow(lena) - Out[20]: - - * Follow-up: copy all instructions of this exercise in a script called - ``lena_locket.py`` then execute this script in IPython with ``%run - lena_locket.py``. - - Change the circle to an ellipsoid. - -.. topic:: Exercise: Array manipulations - :class: green - - 1. Form the 2-D array (without typing it in explicitly):: - - 1 6 11 - 2 7 12 - 3 8 13 - 4 9 14 - 5 10 15 - - and generate a new array containing its 2nd and 4th rows. - - 2. Divide each column of the array:: - - >>> a = np.arange(25).reshape(5, 5) - - elementwise with the array ``b = np.array([1., 5, 10, 15, 20])``. - (Hint: ``np.newaxis``). - - 3. Harder one: Generate a 10 x 3 array of random numbers (in range [0,1]). - For each row, pick the number closest to 0.5. - - - Use ``abs`` and ``argsort`` to find the column ``j`` closest for - each row. - - - Use fancy indexing to extract the numbers. (Hint: ``a[i,j]`` -- - the array ``i`` must contain the row numbers corresponding to stuff in - ``j``.) - -.. topic:: Exercise: Data statistics +.. topic:: **Ejercicio: Ordenado** :class: green - The data in :download:`populations.txt <../../data/populations.txt>`:: - describes the populations of hares and lynxes (and carrots) in - northern Canada during 20 years:: - - >>> data = np.loadtxt('data/populations.txt') - >>> year, hares, lynxes, carrots = data.T # trick: columns to variables - - >>> plt.axes([0.2, 0.1, 0.5, 0.8]) # doctest: +ELLIPSIS - - >>> plt.plot(year, hares, year, lynxes, year, carrots) # doctest: +ELLIPSIS - [, ...] - >>> plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5)) # doctest: +ELLIPSIS - - - .. plot:: pyplots/numpy_intro_7.py - - Computes and print, based on the data in ``populations.txt``... - - 1. The mean and std of the populations of each species for the years - in the period. - - 2. Which year each species had the largest population. - - 3. Which species has the largest population for each year. - (Hint: ``argsort`` & fancy indexing of - ``np.array(['H', 'L', 'C'])``) - - 4. Which years any of the populations is above 50000. - (Hint: comparisons and ``np.any``) - - 5. The top 2 years for each species when they had the lowest - populations. (Hint: ``argsort``, fancy indexing) - - 6. Compare (plot) the change in hare population (see - ``help(np.gradient)``) and the number of lynxes. Check correlation - (see ``help(np.corrcoef)``). - - ... all without for-loops. - -.. topic:: Exercise: Crude integral approximations - :class: green - - Write a function ``f(a, b, c)`` that returns :math:`a^b - c`. Form - a 24x12x6 array containing its values in parameter ranges ``[0,1] x - [0,1] x [0,1]``. - - Approximate the 3-d integral - - .. math:: \int_0^1\int_0^1\int_0^1(a^b-c)da\,db\,dc - - over this volume with the mean. The exact result is: :math:`\ln 2 - - \frac{1}{2}\approx0.1931\ldots` --- what is your relative error? - - (Hints: use elementwise operations and broadcasting. - You can make ``np.ogrid`` give a number of points in given range - with ``np.ogrid[0:1:20j]``.) - - **Reminder** Python functions:: - - def f(a, b, c): - return some_result - -.. topic:: Exercise: Mandelbrot set - :class: green - - .. plot:: intro/numpy/solutions/2_4_mandelbrot.py - - Write a script that computes the Mandelbrot fractal. The Mandelbrot - iteration:: - - N_max = 50 - some_threshold = 50 - - c = x + 1j*y - - for j in xrange(N_max): - z = z**2 + c - - Point (x, y) belongs to the Mandelbrot set if :math:`|c|` < - ``some_threshold``. - - Do this computation by: - - .. For doctests - >>> mask = np.ones((3, 3)) - - 1. Construct a grid of c = x + 1j*y values in range [-2, 1] x [-1.5, 1.5] - - 2. Do the iteration - - 3. Form the 2-d boolean mask indicating which points are in the set - - 4. Save the result to an image with:: - - >>> import matplotlib.pyplot as plt - >>> plt.imshow(mask.T, extent=[-2, 1, -1.5, 1.5]) # doctest: +ELLIPSIS - - >>> plt.gray() - >>> plt.savefig('mandelbrot.png') - - -.. topic:: Exercise: Markov chain - :class: green - - .. image:: markov-chain.png - - Markov chain transition matrix ``P``, and probability distribution on - the states ``p``:: - - 1. ``0 <= P[i,j] <= 1``: probability to go from state ``i`` to state ``j`` - - 2. Transition rule: :math:`p_{new} = P^T p_{old}` - - 3. ``all(sum(P, axis=1) == 1)``, ``p.sum() == 1``: normalization - - Write a script that works with 5 states, and: - - - Constructs a random matrix, and normalizes each row so that it - is a transition matrix. - - - Starts from a random (normalized) probability distribution - ``p`` and takes 50 steps => ``p_50`` - - - Computes the stationary distribution: the eigenvector of ``P.T`` - with eigenvalue 1 (numerically: closest to 1) => ``p_stationary`` - - Remember to normalize the eigenvector --- I didn't... - - - Checks if ``p_50`` and ``p_stationary`` are equal to tolerance 1e-5 - - Toolbox: ``np.random.rand``, ``.dot()``, ``np.linalg.eig``, - reductions, ``abs()``, ``argmin``, comparisons, ``all``, - ``np.linalg.norm``, etc. - - -Summary --------- + * Pruebe creando una copia y sin crear una copia. + * Trate de crear arreglos con diferentes dtypes y ordenarlos. + * Utilice ``all`` o ``array_equal`` para comprobar los resultados. + * Pruebe ``np.random.shuffle`` una manera de crear entradas para ordenar más rápido. + * Combine ``ravel``, ``sort`` y ``reshape``. + * Revise la palabra clave ``axis`` para ``sort`` y reescriba el ejercicio anterior. -**What do you need to know to get started?** +Resumen +------- -* Know how to create arrays : ``array``, ``arange``, ``ones``, - ``zeros``. +**Qué es lo necesita saber para empezar?** -* Know the shape of the array with ``array.shape``, then use slicing - to obtain different views of the array: ``array[::2]``, - etc. Adjust the shape of the array using ``reshape`` or flatten it - with ``ravel``. +* Saber cómo crear arreglos: ``array``, ``arange``, ``ones``, ``zeros``. -* Obtain a subset of the elements of an array and/or modify their values - with masks:: +* Obtener la dimensión de un arreglo con ``array.shape``, usar el segmentado para obtener diferentes vistas de un arreglo: ``array [:: 2]``, etc. Cambiar la dimensión de la matriz mediante ``reshape`` o aplanarla con ``ravel``. - >>> a[a < 0] = 0 +* Obtener un subconjunto de los elementos de un arreglo y/o modificar sus valores con máscaras -* Know miscellaneous operations on arrays, such as finding the mean or max - (``array.max()``, ``array.mean()``). No need to retain everything, but - have the reflex to search in the documentation (online docs, - ``help()``, ``lookfor()``)!! +.. code-block:: python -* For advanced use: master the indexing with arrays of integers, as well as - broadcasting. Know more Numpy functions to handle various array - operations. + >>> a[a < 0] = 0 +* Conocer las operaciones misceláneas con arreglos, como la búsqueda de la media o el valor máximo (``array.mean()``, ``array.max()``). No hay necesidad de saberlo todo, solo busque en la documentación (documentación en línea, ``help()``, ``lookfor()``)!! +* Para uso avanzado: dominar el indexado con arreglos de enteros, así como broadcasting. Conocer más funciones para manejar varias operaciones con arreglos Numpy. diff --git a/intro/numpy/solutions/mandelbrot.png b/intro/numpy/solutions/mandelbrot.png new file mode 100644 index 0000000..1f24529 Binary files /dev/null and b/intro/numpy/solutions/mandelbrot.png differ diff --git a/intro/scipy.rst b/intro/scipy.rst index c190087..645dbf0 100644 --- a/intro/scipy.rst +++ b/intro/scipy.rst @@ -1,814 +1,766 @@ -Scipy : high-level scientific computing -========================================= +Scipy: computación científica de alto nivel +=========================================== -:authors: Adrien Chauve, Andre Espaze, Emmanuelle Gouillart, +:Autores: Adrien Chauve, Andre Espaze, Emmanuelle Gouillart, Gaël Varoquaux, Ralf Gommers -.. +.. >>> import numpy as np >>> np.random.seed(0) .. topic:: Scipy - The ``scipy`` package contains various toolboxes dedicated to common - issues in scientific computing. Its different submodules correspond - to different applications, such as interpolation, integration, - optimization, image processing, statistics, special functions, etc. + El paquete ``scipy`` contiene varias cajas de herramientas dedicadas a problemas comunes problemas en computación científica. Sus diferentes submódulos corresponden a diferentes aplicaciones, tales como interpolación, integración, optimización, procesamiento de imágenes, estadística, funciones especiales, etc. - ``scipy`` can be compared to other standard scientific-computing - libraries, such as the GSL (GNU Scientific Library for C and C++), - or Matlab's toolboxes. ``scipy`` is the core package for scientific - routines in Python; it is meant to operate efficiently on ``numpy`` - arrays, so that numpy and scipy work hand in hand. + ``scipy`` se puede comparar con otras bibliotecas estándar de computación científica, como GSL (GNU Scientific Library para C y C++), o cajas de herramientas de Matlab. ``scipy`` es el paquete núcleo para rutinas científicas en Python; operando de manera eficiente los arreglos ``numpy``, por tanto numpy y scipy trabajan mano a mano. - Before implementing a routine, it is worth checking if the desired - data processing is not already implemented in Scipy. As - non-professional programmers, scientists often tend to **re-invent the - wheel**, which leads to buggy, non-optimal, difficult-to-share and - unmaintainable code. By contrast, ``Scipy``'s routines are optimized - and tested, and should therefore be used when possible. + Antes de implementar una rutina, hay que comprobar si no está implementado en Scipy. Como programadores no profesionales, los científicos a menudo tienden a **reinventar la rueda**, lo que conduce a errores en el código, código no optimizado, código difícil de compartir e imposible de mantener. Por el contrario, las rutinas que contiene ``Scipy`` están optimizadas y probadas, por lo tanto se debe utilizar siempre que sea posible. - -.. contents:: Chapters contents +.. contents:: Contenido :local: - :depth: 4 - - -.. warning:: + :depth: 1 - This tutorial is far from an introduction to numerical computing. - As enumerating the different submodules and functions in scipy would - be very boring, we concentrate instead on a few examples to give a - general idea of how to use ``scipy`` for scientific computing. +.. warning:: Este tutorial está lejos de ser una introducción a métodos numéricos. Enumerar los diferentes submódulos y funciones en scipy seria muy aburrido, en cambio nos concentramos en algunos ejemplos para dar una idea general de cómo utilizar ``scipy`` para computación científica. -`scipy` is composed of task-specific sub-modules: +:mod:`scipy` contiene sub-módulos para tareas específicas: =========================== =============================================== :mod:`scipy.cluster` Vector quantization / Kmeans -:mod:`scipy.constants` Physical and mathematical constants -:mod:`scipy.fftpack` Fourier transform -:mod:`scipy.integrate` Integration routines -:mod:`scipy.interpolate` Interpolation -:mod:`scipy.io` Data input and output -:mod:`scipy.linalg` Linear algebra routines +:mod:`scipy.constants` Constantes físicas y matemáticas +:mod:`scipy.fftpack` Transformadas de Fourier +:mod:`scipy.integrate` Rutinas para integración +:mod:`scipy.interpolate` Interpolación +:mod:`scipy.io` Entrada y salida +:mod:`scipy.linalg` Rutinas para algebra lineal :mod:`scipy.ndimage` n-dimensional image package :mod:`scipy.odr` Orthogonal distance regression -:mod:`scipy.optimize` Optimization -:mod:`scipy.signal` Signal processing -:mod:`scipy.sparse` Sparse matrices -:mod:`scipy.spatial` Spatial data structures and algorithms -:mod:`scipy.special` Any special mathematical functions -:mod:`scipy.stats` Statistics +:mod:`scipy.optimize` Optimización +:mod:`scipy.signal` Procesamiento de señales +:mod:`scipy.sparse` Matrices dispersas +:mod:`scipy.spatial` estructuras de datos espaciales y algoritmos +:mod:`scipy.special` Funciones matemáticas especiales +:mod:`scipy.stats` Estadística =========================== =============================================== -They all depend on :mod:`numpy`, but are mostly independent of each other. The -standard way of importing Numpy and these Scipy modules is:: +Todos ellos dependen de :mod:`numpy`, en su mayoría son independientes el uno del otro. La forma estándar de importar Numpy y módulos Scipy es - >>> import numpy as np - >>> from scipy import stats # same for other sub-modules - -The main ``scipy`` namespace mostly contains functions that are really -numpy functions (try ``scipy.cos is np.cos``). Those are exposed for historical -reasons only; there's usually no reason to use ``import scipy`` in your code. +.. code-block:: python + >>> import numpy as np + >>> from scipy import stats # lo mismo para otros submódulos -File input/output: :mod:`scipy.io` ----------------------------------- +El espacio de nombres principal ``scipy`` que contiene la mayoría de las funciones son en realidad funciones numpy (pruebe ``scipy.cos is np.cos``). Están expuestos por razones solamente históricas, por lo general no hay ninguna razón para utilizar ``import scipy`` en su código. -* Loading and saving matlab files:: +Entrada/salida de archivos: :mod:`scipy.io` +------------------------------------------- - >>> from scipy import io as spio - >>> a = np.ones((3, 3)) - >>> spio.savemat('file.mat', {'a': a}) # savemat expects a dictionary - >>> data = spio.loadmat('file.mat', struct_as_record=True) - >>> data['a'] - array([[ 1., 1., 1.], - [ 1., 1., 1.], - [ 1., 1., 1.]]) +* Cargar y guardar archivos de matlab -* Reading images:: + .. code-block:: python - >>> from scipy import misc - >>> misc.imread('fname.png') - >>> # Matplotlib also has a similar function - >>> import matplotlib.pyplot as plt - >>> plt.imread('fname.png') + >>> from scipy import io as spio + >>> a = np.ones((3, 3)) + >>> spio.savemat('file.mat', {'a': a}) # savemat espera un diccionario + >>> data = spio.loadmat('file.mat', struct_as_record=True) + >>> data['a'] + array([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) -See also: +* Lectura de imágenes - * Load text files: :func:`numpy.loadtxt`/:func:`numpy.savetxt` + .. code-block:: python - * Clever loading of text/csv files: - :func:`numpy.genfromtxt`/:func:`numpy.recfromcsv` + >>> from scipy import misc + >>> misc.imread('fname.png') + >>> # Matplotlib tiene una función similar + >>> import matplotlib.pyplot as plt + >>> plt.imread('fname.png') - * Fast and efficient, but numpy-specific, binary format: - :func:`numpy.save`/:func:`numpy.load` +Ver también: +* Cargar archivos de texto: :func:`numpy.loadtxt`/:func:`numpy.savetxt` +* Cargar archivos de texto/csv de forma hábil: :func:`numpy.genfromtxt`/:func:`numpy.recfromcsv` -Special functions: :mod:`scipy.special` ---------------------------------------- +* Rápido y eficiente, formato propio de numpy en archivo binario: :func:`numpy.save`/:func:`numpy.load` -Special functions are transcendental functions. The docstring of the -:mod:`scipy.special` module is well-written, so we won't list all -functions here. Frequently used ones are: +Funciones especiales: :mod:`scipy.special` +------------------------------------------ - * Bessel function, such as :func:`scipy.special.jn` (nth integer order Bessel - function) +Las funciones especiales son funciones trascendentales. La cadena de documentación del módulo :mod:`scipy.special` está bien escrita, así que no vamos a enumerar todas las +funciones aquí. Los frecuentemente utilizadas son: - * Elliptic function (:func:`scipy.special.ellipj` for the Jacobian elliptic - function, ...) +* Función de Bessel, tales como :func:`scipy.special.jn` (función de Bessel de enésimo orden) - * Gamma function: :func:`scipy.special.gamma`, also note - :func:`scipy.special.gammaln` which - will give the log of Gamma to a higher numerical precision. +* Función elíptica (:func:`scipy.special.ellipj` para la función elíptica jacobiana, ...) - * Erf, the area under a Gaussian curve: :func:`scipy.special.erf` +* Función Gamma: :func:`scipy.special.gamma`, también tenga en cuenta :func:`scipy.special.gammaln` dará el registro de Gamma con una mayor precisión numérica. +* Erf, la función error o el área bajo la curva de Gauss: :func:`scipy.special.erf` .. _scipy_linalg: -Linear algebra operations: :mod:`scipy.linalg` ------------------------------------------------ +Operaciones de álgebra lineal: :mod:`scipy.linalg` +-------------------------------------------------- + +El módulo :mod:`scipy.linalg` ofrece operaciones estándar para álgebra lineal, basándose en una aplicación eficiente subyacente (BLAS, LAPACK). + +* El función :func:`scipy.linalg.det` calcula el determinante de una matriz cuadrada + + .. code-block:: python + + >>> from scipy import linalg + >>> arr = np.array([[1, 2], + ... [3, 4]]) + >>> linalg.det(arr) + -2.0 + >>> arr = np.array([[3, 2], + ... [6, 4]]) + >>> linalg.det(arr) + 0.0 + >>> linalg.det(np.ones((3, 4))) + Traceback (most recent call last): + ... + ValueError: expected square matrix + +* La función :func:`scipy.linalg.inv` calcula la inversa de una matriz cuadrada + + .. code-block:: python + + >>> arr = np.array([[1, 2], + ... [3, 4]]) + >>> iarr = linalg.inv(arr) + >>> iarr + array([[-2. , 1. ], + [ 1.5, -0.5]]) + >>> np.allclose(np.dot(arr, iarr), np.eye(2)) + True + + Finalmente calcular la inversa de una matriz singular (su determinante es cero) generará un error ``LinAlgError`` + + .. code-block:: python + + >>> arr = np.array([[3, 2], + ... [6, 4]]) + >>> linalg.inv(arr) + Traceback (most recent call last): + ... + LinAlgError: singular matrix + +* Operaciones más avanzadas están disponibles, por ejemplo descomposición en valores singulares (SVD) + + .. code-block:: python + + >>> arr = np.arange(9).reshape((3, 3)) + np.diag([1, 0, 1]) + >>> uarr, spec, vharr = linalg.svd(arr) + + Los valores propios son + + .. code-block:: python -The :mod:`scipy.linalg` module provides standard linear algebra -operations, relying on an underlying efficient implementation (BLAS, -LAPACK). - -* The :func:`scipy.linalg.det` function computes the determinant of a - square matrix:: - - >>> from scipy import linalg - >>> arr = np.array([[1, 2], - ... [3, 4]]) - >>> linalg.det(arr) - -2.0 - >>> arr = np.array([[3, 2], - ... [6, 4]]) - >>> linalg.det(arr) - 0.0 - >>> linalg.det(np.ones((3, 4))) - Traceback (most recent call last): - ... - ValueError: expected square matrix - -* The :func:`scipy.linalg.inv` function computes the inverse of a square - matrix:: - - >>> arr = np.array([[1, 2], - ... [3, 4]]) - >>> iarr = linalg.inv(arr) - >>> iarr - array([[-2. , 1. ], - [ 1.5, -0.5]]) - >>> np.allclose(np.dot(arr, iarr), np.eye(2)) - True - - Finally computing the inverse of a singular matrix (its determinant is zero) - will raise ``LinAlgError``:: - - >>> arr = np.array([[3, 2], - ... [6, 4]]) - >>> linalg.inv(arr) - Traceback (most recent call last): - ... - LinAlgError: singular matrix - -* More advanced operations are available, for example singular-value - decomposition (SVD):: - - >>> arr = np.arange(9).reshape((3, 3)) + np.diag([1, 0, 1]) - >>> uarr, spec, vharr = linalg.svd(arr) - - The resulting array spectrum is:: - - >>> spec # doctest: +ELLIPSIS - array([ 14.88982544, 0.45294236, 0.29654967]) - - The original matrix can be re-composed by matrix multiplication of the outputs of - ``svd`` with ``np.dot``:: - - >>> sarr = np.diag(spec) - >>> svd_mat = uarr.dot(sarr).dot(vharr) - >>> np.allclose(svd_mat, arr) - True - - SVD is commonly used in statistics and signal processing. Many other - standard decompositions (QR, LU, Cholesky, Schur), as well as solvers - for linear systems, are available in :mod:`scipy.linalg`. - - -Fast Fourier transforms: :mod:`scipy.fftpack` ----------------------------------------------- - -The :mod:`scipy.fftpack` module allows to compute fast Fourier transforms. -As an illustration, a (noisy) input signal may look like:: - - >>> time_step = 0.02 - >>> period = 5. - >>> time_vec = np.arange(0, 20, time_step) - >>> sig = np.sin(2 * np.pi / period * time_vec) + \ - ... 0.5 * np.random.randn(time_vec.size) - -The observer doesn't know the signal frequency, only -the sampling time step of the signal ``sig``. The signal -is supposed to come from a real function so the Fourier transform -will be symmetric. -The :func:`scipy.fftpack.fftfreq` function will generate the sampling frequencies and -:func:`scipy.fftpack.fft` will compute the fast Fourier transform:: - - >>> from scipy import fftpack - >>> sample_freq = fftpack.fftfreq(sig.size, d=time_step) - >>> sig_fft = fftpack.fft(sig) - -Because the resulting power is symmetric, only the positive part of the -spectrum needs to be used for finding the frequency:: - - >>> pidxs = np.where(sample_freq > 0) - >>> freqs = sample_freq[pidxs] - >>> power = np.abs(sig_fft)[pidxs] + >>> spec # doctest: +ELLIPSIS + array([ 14.88982544, 0.45294236, 0.29654967]) + + La matriz original puede ser obtenida mediante multiplicación matricial de los resultados de ``svd`` con ``np.dot`` + + .. code-block:: python + + >>> sarr = np.diag(spec) + >>> svd_mat = uarr.dot(sarr).dot(vharr) + >>> np.allclose(svd_mat, arr) + True + + SVD se utiliza comúnmente en estadística y procesamiento de señales. Otros métodos de descomposiciones estándar están disponibles (QR, LU, Cholesky, Schur), támbien solucionadores de sistemas lineales, están disponibles en :mod:`scipy.linalg`. + +Transformada rápida de Fourier: :mod:`scipy.fftpack` +---------------------------------------------------- + +El módulo :mod:`scipy.fftpack` permite calcular la transformada rápida de Fourier. A modo de ejemplo, una señal de entrada (con ruido) puede verse + +.. code-block:: python + + >>> time_step = 0.02 + >>> period = 5. + >>> time_vec = np.arange(0, 20, time_step) + >>> sig = np.sin(2 * np.pi / period * time_vec) + \ + ... 0.5 * np.random.randn(time_vec.size) + +El observador no conoce la frecuencia de la señal, sólo el paso de tiempo de muestreo de la señal ``sig``. La señal se supone que procede de una función real para la cual la transformada de Fourier será simétrica. +La función :func:`scipy.fftpack.fftfreq` genera las frecuencias de muestreo y :func:`scipy.fftpack.fft` calcula la transformada rápida de Fourier + +.. code-block:: python + + >>> from scipy import fftpack + >>> sample_freq = fftpack.fftfreq(sig.size, d=time_step) + >>> sig_fft = fftpack.fft(sig) + +Debido a que la potencia resultante es simétrica, sólo la parte positiva del espectro es utilizada para encontrar la frecuencia + +.. code-block:: python + + >>> pidxs = np.where(sample_freq > 0) + >>> freqs = sample_freq[pidxs] + >>> power = np.abs(sig_fft)[pidxs] .. plot:: pyplots/fftpack_frequency.py - :scale: 70 + :scale: 70 + +La frecuencia de la señal se puede encontrar + +.. code-block:: python + + >>> freq = freqs[power.argmax()] + >>> np.allclose(freq, 1./period) # check that correct freq is found + True -The signal frequency can be found by:: +Ahora, el ruido de alta frecuencia será eliminado de la señal transformada de Fourier - >>> freq = freqs[power.argmax()] - >>> np.allclose(freq, 1./period) # check that correct freq is found - True +.. code-block:: python -Now the high-frequency noise will be removed from the Fourier transformed -signal:: + >>> sig_fft[np.abs(sample_freq) > freq] = 0 - >>> sig_fft[np.abs(sample_freq) > freq] = 0 +La señal filtrada resultante puede ser calculado con la función :func:`scipy.fftpack.ifft` -The resulting filtered signal can be computed by the -:func:`scipy.fftpack.ifft` function:: +.. code-block:: python - >>> main_sig = fftpack.ifft(sig_fft) + >>> main_sig = fftpack.ifft(sig_fft) -The result can be viewed with:: +El resultado se puede ver con - >>> plt.figure() - >>> plt.plot(time_vec, sig) - >>> plt.plot(time_vec, main_sig, linewidth=3) - >>> plt.xlabel('Time [s]') - >>> plt.ylabel('Amplitude') +.. code-block:: python + + >>> import pylab as plt + >>> plt.figure() + >>> plt.plot(time_vec, sig) + >>> plt.plot(time_vec, main_sig, linewidth=3) + >>> plt.xlabel('Time [s]') + >>> plt.ylabel('Amplitude') .. plot:: pyplots/fftpack_signals.py :scale: 70 .. topic:: `numpy.fft` - Numpy also has an implementation of FFT (:mod:`numpy.fft`). However, - in general the scipy one - should be preferred, as it uses more efficient underlying implementations. + Numpy también tiene una implementación de FFT (:mod:`numpy.fft`). Sin embargo, en general es preferible usar :mod:`scipy.fftpack`, ya que utiliza implementaciones subyacentes más eficientes. -.. topic:: Worked example: Crude periodicity finding +.. topic:: Ejemplo práctico: Encontrar periodicidad cruda - .. plot:: intro/solutions/periodicity_finder.py + .. plot:: intro/solutions/periodicity_finder.py -.. topic:: Worked example: Gaussian image blur +.. topic:: Ejemplo práctico: Gaussian image blur - Convolution: + Convolución: - .. math:: + .. math:: - f_1(t) = \int dt'\, K(t-t') f_0(t') + f_1(t) = \int dt'\, K(t-t') f_0(t') - .. math:: + .. math:: - \tilde{f}_1(\omega) = \tilde{K}(\omega) \tilde{f}_0(\omega) + \tilde{f}_1(\omega) = \tilde{K}(\omega) \tilde{f}_0(\omega) - .. plot:: intro/solutions/image_blur.py + .. plot:: intro/solutions/image_blur.py -.. topic:: Exercise: Denoise moon landing image +.. topic:: Ejercicio: Imagen de alunizaje con ruido :class: green .. image:: ../data/moonlanding.png :scale: 70 - 1. Examine the provided image moonlanding.png, which is heavily - contaminated with periodic noise. In this exercise, we aim to clean up - the noise using the Fast Fourier Transform. - - 2. Load the image using `plt.imread`. + 1. Examine la imagen moonlanding.png proporcionada, que está en gran medida + contaminada con ruido periódico. En este ejercicio, nuestro objetivo es limpiar + el ruido utilizando la transformada rápida de Fourier. - 3. Find and use the 2-D FFT function in :mod:`scipy.fftpack`, and plot the - spectrum (Fourier transform of) the image. Do you have any trouble - visualising the spectrum? If so, why? + 2. Cargar la imagen usando :func:`pylab.imread`. - 4. The spectrum consists of high and low frequency components. The noise is - contained in the high-frequency part of the spectrum, so set some of - those components to zero (use array slicing). + 3. Encontrar y utilizar la función FFT 2-D en :mod:`scipy.fftpack`, y graficar el + espectro de la imagen (de la transformada de Fourier). Tiene algún problema + en visualizar el espectro? Si es así, porqué? - 5. Apply the inverse Fourier transform to see the resulting image. + 4. El espectro consta de componentes de alta y baja frecuencia. El ruido está contenida en la parte de alta frecuencia del espectro, por lo que se debe establecer algunos de sus componentes a cero (use segmentado de arreglos o slicing). + 5. Aplicar la transformada inversa de Fourier para ver la imagen resultante. -Optimization and fit: :mod:`scipy.optimize` +Optimización y ajuste: :mod:`scipy.optimize` ------------------------------------------- -Optimization is the problem of finding a numerical solution to a -minimization or equality. +Optimización es el problema de encontrar una solución numérica a un +minimización o igualdad. + +El módulo :mod:`scipy.optimize` proporciona algoritmos útiles para la minimización de funciones (escalares o multidimensionales), ajuste de curvas y búsqueda de raices. -The :mod:`scipy.optimize` module provides useful algorithms for function -minimization (scalar or multi-dimensional), curve fitting and root -finding. :: +.. code-block:: python - >>> from scipy import optimize + >>> from scipy import optimize +**Encontrar los mínimos de una función escalar** -**Finding the minimum of a scalar function** +Vamos a definir la siguiente función: -Let's define the following function: :: +.. code-block:: python - >>> def f(x): - ... return x**2 + 10*np.sin(x) + >>> def f(x): + ... return x**2 + 10*np.sin(x) -and plot it: +y la graficamos: -.. doctest:: +.. code-block:: python - >>> x = np.arange(-10, 10, 0.1) - >>> plt.plot(x, f(x)) # doctest:+SKIP - >>> plt.show() # doctest:+SKIP + >>> x = np.arange(-10, 10, 0.1) + >>> plt.plot(x, f(x)) # doctest:+SKIP + >>> plt.show() # doctest:+SKIP .. plot:: pyplots/scipy_optimize_example1.py -This function has a global minimum around -1.3 and a local minimum around 3.8. +Esta función tiene un mínimo global en torno a -1.3 y un mínimo local en torno a 3.8. + +La forma general y eficiente para encontrar el mínimo de esta función es llevar a cabo un descenso de gradiente partiendo de un punto inicial dado. El algoritmo BFGS es una buena manera de hacer esto + +.. code-block:: python + + >>> optimize.fmin_bfgs(f, 0) + Optimization terminated successfully. + Current function value: -7.945823 + Iterations: 5 + Function evaluations: 24 + Gradient evaluations: 8 + array([-1.30644003]) -The general and efficient way to find a minimum for this function is to -conduct a gradient descent starting from a given initial point. The BFGS -algorithm is a good way of doing this:: +Un posible problema con este enfoque es, si la función tiene mínimos locales +el algoritmo puede encontrar estos mínimos locales en lugar de los mínimos globales de pendiendo del punto inicial: - >>> optimize.fmin_bfgs(f, 0) - Optimization terminated successfully. - Current function value: -7.945823 - Iterations: 5 - Function evaluations: 24 - Gradient evaluations: 8 - array([-1.30644003]) +.. code-block:: python -A possible issue with this approach is that, if the function has local minima -the algorithm may find these local minima instead of the -global minimum depending on the initial point: :: + >>> optimize.fmin_bfgs(f, 3, disp=0) + array([ 3.83746663]) - >>> optimize.fmin_bfgs(f, 3, disp=0) - array([ 3.83746663]) +Si no conocemos el intérvalo del mínimo global para elegir el punto inicial, tenemos que recurrir a una más costoso optimización global. Para encontrar el mínimo global, el algoritmo más simple es el algoritmo de fuerza bruta, en la que el +la función se evalúa en cada punto de una cuadrícula: -If we don't know the neighborhood of the global minimum to choose the initial -point, we need to resort to costlier global optimization. To find the global -minimum, the simplest algorithm is the brute force algorithm, in which the -function is evaluated on each point of a given grid: :: +.. code-block:: python - >>> grid = (-10, 10, 0.1) - >>> xmin_global = optimize.brute(f, (grid,)) - >>> xmin_global - array([-1.30641113]) + >>> grid = (-10, 10, 0.1) + >>> xmin_global = optimize.brute(f, (grid,)) + >>> xmin_global + array([-1.30641113]) -For larger grid sizes, :func:`scipy.optimize.brute` becomes quite slow. -:func:`scipy.optimize.anneal` -provides an alternative, using simulated annealing. More efficient algorithms -for different classes of global optimization problems exist, but this is out of -the scope of ``scipy``. Some useful packages for global optimization are -OpenOpt_, IPOPT_, PyGMO_ and PyEvolve_. +Para tamaños de cuadrícula más grandes, :func:`scipy.optimize.brute` se vuelve muy lento. :func:`scipy.optimize.anneal` ofrece una alternativa, utilizando recocido simulado. Existen algoritmos más eficientes para diferentes tipos de problemas de optimización global, pero están fuera del alcance de ``scipy``. Algunos paquetes útiles para optimización global son OpenOpt_, IPOPT_, PyGMO_ y PyEvolve_. .. _OpenOpt: http://openopt.org/Welcome .. _IPOPT: https://github.com/xuy/pyipopt .. _PyGMO: http://pagmo.sourceforge.net/pygmo/index.html .. _PyEvolve: http://pyevolve.sourceforge.net/ -To find the local minimum, let's constraint the variable to the interval -``(0, 10)`` using :func:`scipy.optimize.fminbound`: :: +Para encontrar el mínimo local, vamos a restringir la variable en el intervalo +``(0, 10)`` usando :func:`scipy.optimize.fminbound`: - >>> xmin_local = optimize.fminbound(f, 0, 10) # doctest: +ELLIPSIS - >>> xmin_local - 3.8374671... +.. code-block:: python -.. note:: - - Finding minima of function is discussed in more details in the - advanced chapter: :ref:`mathematical_optimization`. + >>> xmin_local = optimize.fminbound(f, 0, 10) # doctest: +ELLIPSIS + >>> xmin_local + 3.8374671... -**Finding the roots of a scalar function** +.. note:: Encontrar los mínimos de una función se discute con más detalles en el capítulo avanzado: :ref:`mathematical_optimization`. -To find a root, i.e. a point where ``f(x) = 0``, of the function ``f`` above -we can use for example :func:`scipy.optimize.fsolve`: :: +**Encontrar las raíces de una función escalar** - >>> root = optimize.fsolve(f, 1) # our initial guess is 1 - >>> root - array([ 0.]) +Para encontrar una raíz, o el punto donde ``f(x) = 0``, de la función ``f`` de arriba +podemos utilizar por ejemplo :func:`scipy.optimize.fsolve`: -Note that only one root is found. Inspecting the plot of ``f`` reveals that -there is a second root around -2.5. We find the exact value of it by adjusting -our initial guess: :: +.. code-block:: python - >>> root2 = optimize.fsolve(f, -2.5) - >>> root2 - array([-2.47948183]) + >>> root = optimize.fsolve(f, 1) # our initial guess is 1 + >>> root + array([ 0.]) -**Curve fitting** +Tenga en cuenta que sólo una raíz puede ser encontrada. Una inspeción a la gráfica de ``f`` revela que hay una segunda raíz alrededor de -2.5. Encontramos el valor exacto de la misma mediante un ajuste a la estimación inicial: -Suppose we have data sampled from ``f`` with some noise: :: +.. code-block:: python - >>> xdata = np.linspace(-10, 10, num=20) - >>> ydata = f(xdata) + np.random.randn(xdata.size) - -Now if we know the functional form of the function from which the samples were -drawn (``x^2 + sin(x)`` in this case) but not the amplitudes of the terms, we -can find those by least squares curve fitting. First we have to define the -function to fit:: + >>> root2 = optimize.fsolve(f, -2.5) + >>> root2 + array([-2.47948183]) - >>> def f2(x, a, b): - ... return a*x**2 + b*np.sin(x) +**Ajuste de curvas** -Then we can use :func:`scipy.optimize.curve_fit` to find ``a`` and ``b``: :: +Supongamos que tenemos datos de una muestra de ``f`` con un poco de ruido: - >>> guess = [2, 2] - >>> params, params_covariance = optimize.curve_fit(f2, xdata, ydata, guess) - >>> params - array([ 0.99925147, 9.76065551]) +.. code-block:: python -Now we have found the minima and roots of ``f`` and used curve fitting on it, -we put all those resuls together in a single plot: + >>> xdata = np.linspace(-10, 10, num=20) + >>> ydata = f(xdata) + np.random.randn(xdata.size) -.. plot:: pyplots/scipy_optimize_example2.py +Ahora bien, si se conoce la forma funcional de la función de la cual las muestras fueron dibujadas (``x^2 + sin(x)`` en este caso), pero no la amplitud de los términos, puede ser encontrados mediante una ajuste por mínimos cuadrados. Primero tenemos que definir la funcionar a ajustar + +.. code-block:: python + + >>> def f2(x, a, b): + ... return a*x**2 + b*np.sin(x) + +Entonces podemos usar :func:`scipy.optimize.curve_fit` para encontrar ``a`` y ``b``: + +.. code-block:: python + + >>> guess = [2, 2] + >>> params, params_covariance = optimize.curve_fit(f2, xdata, ydata, guess) + >>> params + array([ 0.99925147, 9.76065551]) -.. note:: - - In Scipy >= 0.11 unified interfaces to all minimization and root - finding algorithms are available: :func:`scipy.optimize.minimize`, - :func:`scipy.optimize.minimize_scalar` and - :func:`scipy.optimize.root`. They allow comparing various algorithms - easily through the ``method`` keyword. +Ahora hemos encontrado los mínimos y las raíces de ``f`` y usando un ajuste de la curva, ponemos todos los resultados juntos en un gráfico: -You can find algorithms with the same functionalities for multi-dimensional -problems in :mod:`scipy.optimize`. +.. plot:: pyplots/scipy_optimize_example2.py + +.. note:: En scipy >= 0.11 se unificaron las interfaces para todos los algoritmos de minimización y búsqueda de raices están disponibles en :func:`scipy.optimize.minimize`, :func:`scipy.optimize.minimize_scalar` y :func:`scipy.optimize.root`. Se permite comparar fácilmente diferentes algoritmos a través de la palabra clave ``method``. + Usted puede encontrar algoritmos con las mismas funcionalidades para problemas multi-dimensional en :mod:`scipy.optimize`. -.. topic:: Exercise: Curve fitting of temperature data +.. topic:: Ejercicio: Ajuste de datos de temperatura :class: green - The temperature extremes in Alaska for each month, starting in January, are - given by (in degrees Celcius):: + Las temperaturas extremas en Alaska para cada mes, a partir de enero (en grados centígrados) + + .. code-block:: python - max: 17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18 - min: -62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58 + max: 17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18 + min: -62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58 - 1. Plot these temperature extremes. - 2. Define a function that can describe min and max temperatures. - Hint: this function has to have a period of 1 year. - Hint: include a time offset. - 3. Fit this function to the data with :func:`scipy.optimize.curve_fit`. - 4. Plot the result. Is the fit reasonable? If not, why? - 5. Is the time offset for min and max temperatures the same within the fit - accuracy? + 1. Grafique las temperaturas extremas. -.. topic:: Exercise: 2-D minimization + 2. Definir una función que puede describir las temperaturas min y máx. + Sugerencia: esta función tiene un periodo de 1 año. + Sugerencia: incluir un tiempo compensado. + 3. Ajuste esta función a los datos con :func:`scipy.optimize.curve_fit`. + 4. Graficar el resultado. El ajuste es razonable? Si no, por qué? + 5. Si el tiempo no es compensado el ajuste de las temperaturas mínima y máxima tiene la misma exactitud? + +.. topic:: Ejercicio: Minimización 2-D :class: green - .. plot:: pyplots/scipy_optimize_sixhump.py + .. plot:: pyplots/scipy_optimize_sixhump.py - The six-hump camelback function - - .. math:: f(x, y) = (4 - 2.1x^2 + \frac{x^4}{3})x^2 + xy + (4y^2 - 4)y^2 + La función six-hump camelback - has multiple global and local minima. Find the global minima of this - function. + .. math:: f(x, y) = (4 - 2.1x^2 + \frac{x^4}{3})x^2 + xy + (4y^2 - 4)y^2 - Hints: + tiene múltiples mınimos globales y locales. Encuentre los mínimos globales de esta función. - - Variables can be restricted to ``-2 < x < 2`` and ``-1 < y < 1``. - - Use :func:`numpy.meshgrid` and `plt.imshow` to find visually the - regions. - - Use :func:`scipy.optimize.fmin_bfgs` or another multi-dimensional - minimizer. + Sugerencia: - How many global minima are there, and what is the function value at those - points? What happens for an initial guess of ``(x, y) = (0, 0)``? + - Puede restringir las variables a ``-2 < x < 2`` y ``-1 < y < 1``. + - Use :func:`numpy.meshgrid` y :func:`pylab.imshow` para encontrar visualmente las regiones. + - Use :func:`scipy.optimize.fmin_bfgs` o otro minimizador multidimensional. -See the summary exercise on :ref:`summary_exercise_optimize` for another, more -advanced example. + Cuántos mínimos globales hay, y cuál es el valor de la función en esos puntos? Qué sucede con una estimación inicial de ``(x, y) = (0, 0)``? + Ver el sumario de ejercicios en :ref:`summary_exercise_optimize` para ejemplos más avanzados. -Statistics and random numbers: :mod:`scipy.stats` -------------------------------------------------- +Estadística y números aleatorios: :mod:`scipy.stats` +---------------------------------------------------- + +El módulo :mod:`scipy.stats` contiene herramientas estadísticas y probabilísticas +descripciones de procesos aleatorios. Generadores de números aleatorios para diferentes +procesos aleatorios se puede encontrar en :mod:`numpy.random` . -The module :mod:`scipy.stats` contains statistical tools and probabilistic -descriptions of random processes. Random number generators for various -random process can be found in :mod:`numpy.random`. +Histograma y la función de densidad de probabilidad +................................................... -Histogram and probability density function -............................................... +Mediante observaciones de un proceso aleatorio, su histograma es un estimador del proceso aleatorio PDF (probability density function): -Given observations of a random process, their histogram is an estimator of -the random process's PDF (probability density function): :: +.. code-block:: python - >>> a = np.random.normal(size=1000) - >>> bins = np.arange(-4, 5) - >>> bins - array([-4, -3, -2, -1, 0, 1, 2, 3, 4]) - >>> histogram = np.histogram(a, bins=bins, normed=True)[0] - >>> bins = 0.5*(bins[1:] + bins[:-1]) - >>> bins - array([-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5]) - >>> from scipy import stats - >>> b = stats.norm.pdf(bins) # norm is a distribution + >>> a = np.random.normal(size=1000) + >>> bins = np.arange(-4, 5) + >>> bins + array([-4, -3, -2, -1, 0, 1, 2, 3, 4]) + >>> histogram = np.histogram(a, bins=bins, normed=True)[0] + >>> bins = 0.5*(bins[1:] + bins[:-1]) + >>> bins + array([-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5]) + >>> from scipy import stats + >>> b = stats.norm.pdf(bins) # norm is a distribution .. sourcecode:: ipython - In [1]: pl.plot(bins, histogram) - In [2]: pl.plot(bins, b) + In [1]: pl.plot(bins, histogram) + In [2]: pl.plot(bins, b) .. plot:: pyplots/normal_distribution.py - :scale: 70 + :scale: 70 -If we know that the random process belongs to a given family of random -processes, such as normal processes, we can do a maximum-likelihood fit -of the observations to estimate the parameters of the underlying -distribution. Here we fit a normal process to the observed data:: +Si sabemos que el proceso aleatorio pertenece a una determinada familia de procesos aleatorios, tales como procesos normales, podemos hacer un ajuste de máxima credibilidad de las observaciones para estimar los parámetros de la distribución subyacente. Aquí ajustamos a un proceso normal los datos observados - >>> loc, std = stats.norm.fit(a) - >>> loc # doctest: +ELLIPSIS - -0.045256707490... - >>> std # doctest: +ELLIPSIS - 0.9870331586690... +.. code-block:: python -.. topic:: Exercise: Probability distributions - :class: green + >>> loc, std = stats.norm.fit(a) + >>> loc # doctest: +ELLIPSIS + -0.045256707490... + >>> std # doctest: +ELLIPSIS + 0.9870331586690... - Generate 1000 random variates from a gamma distribution with a shape - parameter of 1, then plot a histogram from those samples. Can you plot the - pdf on top (it should match)? +.. topic:: Ejercicio: Distribuciones de probabilidad + :class: green - Extra: the distributions have a number of useful methods. Explore them by - reading the docstring or by using IPython tab completion. Can you find the - shape parameter of 1 back by using the ``fit`` method on your random - variates? + Generar 1000 variables aleatorias desde una distribución gamma con un parámetro de forma igual a 1, despues graficar el histograma de las muestras. Puede graficar la pdf de arriba (debe coincidir)? + Adicional: las distribuciones tienen una serie de métodos útiles. Explore la documentación o mediante la implementación del tabulador IPython. Puede encontrar el parámetro de forma de 1 vuelta usando el método ``fit`` para variables aleatorias? Percentiles -............. +........... + +La mediana es el valor situado al medio de las observaciones por debajo y arriba + +.. code-block:: python + + >>> np.median(a) # doctest: +ELLIPSIS + -0.058028034... -The median is the value with half of the observations below, and half -above:: +También se conoce como el percentil 50, porque el 50 % de las observaciones están por debajo - >>> np.median(a) # doctest: +ELLIPSIS - -0.058028034... +.. code-block:: python -It is also called the percentile 50, because 50% of the observation are -below it:: + >>> stats.scoreatpercentile(a, 50) # doctest: +ELLIPSIS + -0.0580280347... - >>> stats.scoreatpercentile(a, 50) # doctest: +ELLIPSIS - -0.0580280347... +Del mismo modo, podemos calcular el percentil 90 -Similarly, we can calculate the percentile 90:: +.. code-block:: python - >>> stats.scoreatpercentile(a, 90) # doctest: +ELLIPSIS - 1.231593551... + >>> stats.scoreatpercentile(a, 90) # doctest: +ELLIPSIS + 1.231593551... -The percentile is an estimator of the CDF: cumulative distribution -function. +El percentil es un estimador de una CDF: función de distribución acumulada (cumulative distribution function). -Statistical tests -................... +Pruebas estadísticas +.................... -A statistical test is a decision indicator. For instance, if we have two -sets of observations, that we assume are generated from Gaussian -processes, we can use a -`T-test `__ to decide -whether the two sets of observations are significantly different:: +Una prueba estadística es un indicador de decisión. Por ejemplo, si tenemos dos +series de observaciones, que suponemos se generan a partir de una distribución normal, podemos utilizar la `Prueba t de Student `__ para decidir si los dos conjuntos de observaciones son significativamente diferentes - >>> a = np.random.normal(0, 1, size=100) - >>> b = np.random.normal(1, 1, size=10) - >>> stats.ttest_ind(a, b) # doctest: +ELLIPSIS - (-3.75832707..., 0.00027786...) +.. code-block:: python -The resulting output is composed of: + >>> a = np.random.normal(0, 1, size=100) + >>> b = np.random.normal(1, 1, size=10) + >>> stats.ttest_ind(a, b) # doctest: +ELLIPSIS + (-3.75832707..., 0.00027786...) - * The T statistic value: it is a number the sign of which is - proportional to the difference between the two random processes and - the magnitude is related to the significance of this difference. +La salida resultante se compone de: - * the *p value*: the probability of both processes being identical. If it - is close to 1, the two process are almost certainly identical. - The closer it is to zero, the more likely it is that the processes - have different means. +* El valor estadístico T: es un número cuyo signo es proporcional a la diferencia entre los dos procesos aleatorios y la magnitud está relacionada a cuanto diferen. +* El *valor p*: la probabilidad de que ambos procesos sean idénticos. Si es cercano a 1, los dos procesos son casi con toda seguridad idénticos. Cuanto más cercano sea a cero, lo más probable es que los procesos tengan diferentes medias. -Interpolation: :mod:`scipy.interpolate` ----------------------------------------- +Interpolación: :mod:`scipy.interpolate` +--------------------------------------- -The :mod:`scipy.interpolate` is useful for fitting a function from experimental -data and thus evaluating points where no measure exists. The module is based -on the `FITPACK Fortran subroutines`_ from the netlib_ project. +El módulo :mod:`scipy.interpolate` es útil para ajustar una función a partir de datos experimental y evaluar los puntos que se requieren. El módulo se basa en `FITPACK Fortran subroutines`_ del proyecto netlib_. .. _`FITPACK Fortran subroutines` : http://www.netlib.org/dierckx/index.html .. _netlib : http://www.netlib.org -By imagining experimental data close to a sine function:: +Suponiendo que los datos experimentales son cercanos a una función seno + +.. code-block:: python + + >>> measured_time = np.linspace(0, 1, 10) + >>> noise = (np.random.random(10)*2 - 1) * 1e-1 + >>> measures = np.sin(2 * np.pi * measured_time) + noise - >>> measured_time = np.linspace(0, 1, 10) - >>> noise = (np.random.random(10)*2 - 1) * 1e-1 - >>> measures = np.sin(2 * np.pi * measured_time) + noise +La clase :class:`scipy.interpolate.interp1d` puede construir una función de interpolación lineal -The :class:`scipy.interpolate.interp1d` class can build a linear -interpolation function:: +.. code-block:: python - >>> from scipy.interpolate import interp1d - >>> linear_interp = interp1d(measured_time, measures) + >>> from scipy.interpolate import interp1d + >>> linear_interp = interp1d(measured_time, measures) -Then the :obj:`scipy.interpolate.linear_interp` instance needs to be -evaluated at the time of interest:: +La instancia :obj:`scipy.interpolate.linear_interp` puede evaluarlo para un tiempo requerido - >>> computed_time = np.linspace(0, 1, 50) - >>> linear_results = linear_interp(computed_time) +.. code-block:: python -A cubic interpolation can also be selected by providing the ``kind`` optional -keyword argument:: + >>> computed_time = np.linspace(0, 1, 50) + >>> linear_results = linear_interp(computed_time) - >>> cubic_interp = interp1d(measured_time, measures, kind='cubic') - >>> cubic_results = cubic_interp(computed_time) +La interpolación cúbica puede seleccionarse al proporcionar al argumento opcional la palabra clave ``kind`` -The results are now gathered on the following Matplotlib figure: +.. code-block:: python + + >>> cubic_interp = interp1d(measured_time, measures, kind='cubic') + >>> cubic_results = cubic_interp(computed_time) + +Los resultados se muestran en la siguiente figura creada con Matplotlib: .. plot:: pyplots/scipy_interpolation.py -:class:`scipy.interpolate.interp2d` is similar to -:class:`scipy.interpolate.interp1d`, but for 2-D arrays. Note that for -the `interp` family, the computed time must stay within the measured -time range. See the summary exercise on -:ref:`summary_exercise_stat_interp` for a more advance spline -interpolation example. +:class:`scipy.interpolate.interp2d` es similar a :class:`scipy.interpolate.interp1d`, pero para arreglos 2-D. Tenga en cuenta que para los valores `interp`, el tiempo calculado debe permanecer dentro del intervalo de tiempo medido. Ver el sumario de ejercicios :ref:`summary_exercise_stat_interp` para un ejemplo más avanzado de interpolación con splines. +Integración numérica: :mod:`scipy.integrate` +-------------------------------------------- -Numerical integration: :mod:`scipy.integrate` ------------------------------------------------- +La rutina de integración más genérica es :func:`scipy.integrate.quad` -The most generic integration routine is :func:`scipy.integrate.quad`:: +.. code-block:: python - >>> from scipy.integrate import quad - >>> res, err = quad(np.sin, 0, np.pi/2) - >>> np.allclose(res, 1) - True - >>> np.allclose(err, 1 - res) - True + >>> from scipy.integrate import quad + >>> res, err = quad(np.sin, 0, np.pi/2) + >>> np.allclose(res, 1) + True + >>> np.allclose(err, 1 - res) + True -Others integration schemes are available with ``fixed_quad``, +Otros esquemas de integración están disponibles como ``fixed_quad``, ``quadrature``, ``romberg``. -:mod:`scipy.integrate` also features routines for integrating Ordinary -Differential Equations (ODE). In particular, :func:`scipy.integrate.odeint` -is a general-purpose integrator using LSODA (Livermore Solver for -Ordinary Differential equations with Automatic method switching -for stiff and non-stiff problems), see the `ODEPACK Fortran library`_ -for more details. +:mod:`scipy.integrate` también cuenta con rutinas para integrar Ecuaciones Diferenciales Ordinarias (ODE). En particular, :func:`scipy.integrate.odeint` es un integrador de propósito general utilizando LSODA (Solucionador Livermore para Ecuaciones Diferenciales ordinarias con método Automático de conmutación +para problemas rígidos y no rígidos), consulte `ODEPACK Fortran library`_ para más detalles. .. _`ODEPACK Fortran library` : http://people.sc.fsu.edu/~jburkardt/f77_src/odepack/odepack.html -``odeint`` solves first-order ODE systems of the form:: +``odeint`` resuelve sistemas de ecuaciones diferenciales ordinarias de primer orden de la forma -``dy/dt = rhs(y1, y2, .., t0,...)`` +.. code-block:: python -As an introduction, let us solve the ODE ``dy/dt = -2y`` between ``t = -0..4``, with the initial condition ``y(t=0) = 1``. First the function -computing the derivative of the position needs to be defined:: + dy/dt = rhs(y1, y2, .., t0,...) - >>> def calc_derivative(ypos, time, counter_arr): - ... counter_arr += 1 - ... return -2 * ypos - ... +A modo de introducción, vamos a resolver la ecuación diferencial ordinaria ``dy/dt = -2y`` para ``t = 0 .. 4`` , con la condición inicial ``y(t=0) = 1``. Primero se debe calcular la derivada de la función en una posición definida -An extra argument ``counter_arr`` has been added to illustrate that the -function may be called several times for a single time step, until solver -convergence. The counter array is defined as:: +.. code-block:: python - >>> counter = np.zeros((1,), dtype=np.uint16) + >>> def calc_derivative(ypos, time, counter_arr): + ... counter_arr += 1 + ... return -2 * ypos + ... -The trajectory will now be computed:: +El argumento adicional ``counter_arr`` se ha añadido para mostrar que la +función puede ser llamada varias veces para un solo paso de tiempo, hasta que el solucionador llege a converger. La matriz de contadores se define como - >>> from scipy.integrate import odeint - >>> time_vec = np.linspace(0, 4, 40) - >>> yvec, info = odeint(calc_derivative, 1, time_vec, - ... args=(counter,), full_output=True) +.. code-block:: python -Thus the derivative function has been called more than 40 times -(which was the number of time steps):: + >>> counter = np.zeros((1,), dtype=np.uint16) - >>> counter - array([129], dtype=uint16) +A continuación se calcula la trayectoria -and the cumulative number of iterations for each of the 10 first time steps -can be obtained by:: +.. code-block:: python - >>> info['nfe'][:10] - array([31, 35, 43, 49, 53, 57, 59, 63, 65, 69], dtype=int32) + >>> from scipy.integrate import odeint + >>> time_vec = np.linspace(0, 4, 40) + >>> yvec, info = odeint(calc_derivative, 1, time_vec, + ... args=(counter,), full_output=True) -Note that the solver requires more iterations for the first time step. -The solution ``yvec`` for the trajectory can now be plotted: +La función derivada ha sido llamada más de 40 veces (el número de pasos de tiempo) - .. plot:: pyplots/odeint_introduction.py - :scale: 70 +.. code-block:: python -Another example with :func:`scipy.integrate.odeint` will be a damped -spring-mass oscillator -(2nd order oscillator). The position of a mass attached to a spring obeys -the 2nd order ODE ``y'' + 2 eps wo y' + wo^2 y = 0`` with ``wo^2 = k/m`` -with ``k`` the spring constant, ``m`` the mass and ``eps=c/(2 m wo)`` -with ``c`` the damping coefficient. -For this example, we choose the parameters as:: + >>> counter + array([129], dtype=uint16) - >>> mass = 0.5 # kg - >>> kspring = 4 # N/m - >>> cviscous = 0.4 # N s/m +y el número acumulado de iteraciones para cada uno de los primeros 10 pasos de tiempo +puede obtenerse con -so the system will be underdamped, because:: +.. code-block:: python - >>> eps = cviscous / (2 * mass * np.sqrt(kspring/mass)) - >>> eps < 1 - True + >>> info['nfe'][:10] + array([31, 35, 43, 49, 53, 57, 59, 63, 65, 69], dtype=int32) -For the :func:`scipy.integrate.odeint` solver the 2nd order equation needs to be transformed in a -system of two first-order equations for the vector ``Y=(y, y')``. It will -be convenient to define ``nu = 2 eps * wo = c / m`` and ``om = wo^2 = k/m``:: +Tenga en cuenta que el solucionador requiere más iteraciones para la primera etapa de tiempo. La solución de la trayectoria ``yvec`` puede ahora ser graficada: - >>> nu_coef = cviscous / mass - >>> om_coef = kspring / mass +.. plot:: pyplots/odeint_introduction.py + :scale: 70 -Thus the function will calculate the velocity and acceleration by:: +Otro ejemplo con :func:`scipy.integrate.odeint` será un oscilador amortiguado masa-resorte (oscilador de segundo orden). La posición de la masa unida a un resorte obedece +la ecuación diferencial de segundo orden ``y'' + 2 eps wo y' + wo^2 y = 0`` con ``wo^2 = k/m`` siendo ``k`` la constante del resorte , ``m`` la masa y ``eps = c/(2 m wo)`` siendo ``c`` el coeficiente de amortiguamiento. Para este ejemplo, elegimos los parámetros - >>> def calc_deri(yvec, time, nuc, omc): - ... return (yvec[1], -nuc * yvec[1] - omc * yvec[0]) - ... - >>> time_vec = np.linspace(0, 10, 100) - >>> yarr = odeint(calc_deri, (1, 0), time_vec, args=(nu_coef, om_coef)) +.. code-block:: python -The final position and velocity are shown on the following Matplotlib figure: + >>> mass = 0.5 # kg + >>> kspring = 4 # N/m + >>> cviscous = 0.4 # N s/m + +por lo que el sistema es subamortiguado, porque + +.. code-block:: python + + >>> eps = cviscous / (2 * mass * np.sqrt(kspring/mass)) + >>> eps < 1 + True + +Para usar el solucionador :func:`scipy.integrate.odeint` la ecuación de segundo orden debe ser transformado en un sistema de dos ecuaciones de primer orden mediante el vector ``Y = (y, y')``. Serás conveniente definir ``nu = 2 eps * wo = c / m`` y ``om = wo^2 = k/m`` + +.. code-block:: python + + >>> nu_coef = cviscous / mass + >>> om_coef = kspring / mass + +La función que calculará la velocidad y la aceleración será + +.. code-block:: python + + >>> def calc_deri(yvec, time, nuc, omc): + ... return (yvec[1], -nuc * yvec[1] - omc * yvec[0]) + ... + >>> time_vec = np.linspace(0, 10, 100) + >>> yarr = odeint(calc_deri, (1, 0), time_vec, args=(nu_coef, om_coef)) + +La posición final y la velocidad se muestran en la siguiente figura creada con Matplotlib: .. plot:: pyplots/odeint_damped_spring_mass.py - :scale: 70 + :scale: 70 -There is no Partial Differential Equations (PDE) solver in Scipy. -Some Python packages for solving PDE's are available, such as fipy_ or SfePy_. +Scipy no tiene solucionadores de ecuaciones diferenciales parciales (PDE). Algunos paquetes Python para la resolver PDE están disponibles, tales como fipy_ o SfePy_. .. _fipy: http://www.ctcms.nist.gov/fipy/ .. _SfePy: http://code.google.com/p/sfepy/ +Procesamiento de señales: :mod:`scipy.signal` +--------------------------------------------- -Signal processing: :mod:`scipy.signal` ---------------------------------------- +.. code-block:: python -:: + >>> from scipy import signal - >>> from scipy import signal +* :func:`scipy.signal.detrend`: eliminar la tendencia lineal de la señal -* :func:`scipy.signal.detrend`: remove linear trend from signal:: + .. code-block:: python - t = np.linspace(0, 5, 100) - x = t + np.random.normal(size=100) + t = np.linspace(0, 5, 100) + x = t + np.random.normal(size=100) - pl.plot(t, x, linewidth=3) - pl.plot(t, signal.detrend(x), linewidth=3) + pl.plot(t, x, linewidth=3) + pl.plot(t, signal.detrend(x), linewidth=3) .. plot:: pyplots/demo_detrend.py - :scale: 70 + :scale: 70 + +* :func:`scipy.signal.resample`: remuestrea una señal a `n` puntos usando FFT. -* :func:`scipy.signal.resample`: resample a signal to `n` points using FFT. :: + .. code-block:: python - t = np.linspace(0, 5, 100) - x = np.sin(t) - - pl.plot(t, x, linewidth=3) - pl.plot(t[::2], signal.resample(x, 50), 'ko') + t = np.linspace(0, 5, 100) + x = np.sin(t) + + pl.plot(t, x, linewidth=3) + pl.plot(t[::2], signal.resample(x, 50), 'ko') .. plot:: pyplots/demo_resample.py - :scale: 70 + :scale: 70 .. only:: latex - Notice how on the side of the window the resampling is less accurate - and has a rippling effect. + Note como en el lado de la ventana del remuestreo es menos precisa y tiene un efecto de ondulación. -* Signal has many window function: :func:`scipy.signal.hamming`, +* :mod:`scipy.signal` tiene muchas funciones como: :func:`scipy.signal.hamming`, :func:`scipy.signal.bartlett`, :func:`scipy.signal.blackman`... -* Signal has filtering (median filter :func:`scipy.signal.medfilt`, - Wiener :func:`scipy.signal.wiener`), but we will - discuss this in the image paragraph. +* :mod:`scipy.signal` tiene filtros (median filter :func:`scipy.signal.medfilt`, + Wiener :func:`scipy.signal.wiener`), discutiremos esto en la sección de imagen. - -Image processing: :mod:`scipy.ndimage` ------------------------------------------- +Procesamiento de imágenes: :mod:`scipy.ndimage` +----------------------------------------------- .. include:: image_processing/image_processing.rst +Sumario de ejercicios para computación científica +------------------------------------------------- -Summary exercises on scientific computing ------------------------------------------ - -The summary exercises use mainly Numpy, Scipy and Matplotlib. They provide some -real-life examples of scientific computing with Python. Now that the basics of -working with Numpy and Scipy have been introduced, the interested user is -invited to try these exercises. +El sumario de ejercicios utiliza principalmente Numpy, Scipy y Matplotlib. Se proporcionan algunos ejemplos de la vida real en computación científica con Python. Los fundamentos para trabajar con Numpy y Scipy fueron introducidos, se invita a el usuario interesado probar los ejercicios. .. only:: latex @@ -819,10 +771,14 @@ invited to try these exercises. summary-exercises/optimize-fit.rst summary-exercises/image-processing.rst summary-exercises/answers_image_processing.rst + summary-exercises/routing_reservoir.rst + summary-exercises/routing_river_channel.rst + summary-exercises/answers_routing_river_channel.rst + summary-exercises/fit_flow_rate.rst .. only:: html - Exercises: + **Ejercicios:** .. toctree:: :maxdepth: 1 @@ -830,10 +786,14 @@ invited to try these exercises. summary-exercises/stats-interpolate.rst summary-exercises/optimize-fit.rst summary-exercises/image-processing.rst + summary-exercises/routing_reservoir.rst + summary-exercises/routing_river_channel.rst + summary-exercises/fit_flow_rate.rst - Proposed solutions: + **Soluciones propuestas:** .. toctree:: :maxdepth: 1 summary-exercises/answers_image_processing.rst + summary-exercises/answers_routing_river_channel.rst diff --git a/intro/solutions.rst b/intro/solutions.rst index d32c35e..a0a0b14 100644 --- a/intro/solutions.rst +++ b/intro/solutions.rst @@ -6,7 +6,7 @@ .. _pi_wallis: La solución Pi Wallis ----------------------- +--------------------- Calcula los decimales de Pi usando la fórmula de Wallis: @@ -15,7 +15,7 @@ Calcula los decimales de Pi usando la fórmula de Wallis: .. _quick_sort: La solución Quicksort ----------------------- +--------------------- Implementa el algoritmo quicksort tal como viene definido en la wikipedia: diff --git a/intro/solutions/pi_wallis.py b/intro/solutions/pi_wallis.py index 6ab8d1a..5ddee98 100644 --- a/intro/solutions/pi_wallis.py +++ b/intro/solutions/pi_wallis.py @@ -8,7 +8,7 @@ my_pi = 1. for i in range(1, 100000): - my_pi *= 4*i**2/(4*i**2 - 1.) + my_pi *= 4 * i ** 2 / (4 * i ** 2 - 1.) my_pi *= 2 @@ -16,22 +16,24 @@ print my_pi print abs(pi - my_pi) -################################################################################ +############################################################################### num = 1 den = 1 for i in range(1, 100000): - tmp = 4*i*i + tmp = 4 * i * i num *= tmp - den *= tmp-1 + den *= tmp - 1 -better_pi = 2*(num/den) +better_pi = 2 * (num / den) print pi print better_pi print abs(pi - better_pi) print abs(my_pi - better_pi) -################################################################################ +############################################################################### # Solution in a single line using more adcanved constructs (reduce, lambda, # list comprehensions -print 2 * reduce(lambda x,y: x*y, [float((4*(i**2)))/((4*(i**2))-1) for i in range(1,100000)]) +print 2 * reduce(lambda x, y: x * y, + [float((4 * (i ** 2))) / ((4 * (i ** 2)) - 1) + for i in range(1, 100000)]) diff --git a/intro/summary-exercises/auto_examples/images/plot_cumulative_wind_speed_prediction_1.png b/intro/summary-exercises/auto_examples/images/plot_cumulative_wind_speed_prediction_1.png new file mode 100644 index 0000000..f9422ea Binary files /dev/null and b/intro/summary-exercises/auto_examples/images/plot_cumulative_wind_speed_prediction_1.png differ diff --git a/intro/summary-exercises/auto_examples/images/plot_gumbell_wind_speed_prediction_1.png b/intro/summary-exercises/auto_examples/images/plot_gumbell_wind_speed_prediction_1.png new file mode 100644 index 0000000..b004b64 Binary files /dev/null and b/intro/summary-exercises/auto_examples/images/plot_gumbell_wind_speed_prediction_1.png differ diff --git a/intro/summary-exercises/auto_examples/images/plot_sprog_annual_maxima_1.png b/intro/summary-exercises/auto_examples/images/plot_sprog_annual_maxima_1.png new file mode 100644 index 0000000..7ffbdcf Binary files /dev/null and b/intro/summary-exercises/auto_examples/images/plot_sprog_annual_maxima_1.png differ diff --git a/intro/summary-exercises/auto_examples/images/thumb/plot_cumulative_wind_speed_prediction.png b/intro/summary-exercises/auto_examples/images/thumb/plot_cumulative_wind_speed_prediction.png new file mode 100644 index 0000000..9d22a93 Binary files /dev/null and b/intro/summary-exercises/auto_examples/images/thumb/plot_cumulative_wind_speed_prediction.png differ diff --git a/intro/summary-exercises/auto_examples/images/thumb/plot_gumbell_wind_speed_prediction.png b/intro/summary-exercises/auto_examples/images/thumb/plot_gumbell_wind_speed_prediction.png new file mode 100644 index 0000000..87e4be6 Binary files /dev/null and b/intro/summary-exercises/auto_examples/images/thumb/plot_gumbell_wind_speed_prediction.png differ diff --git a/intro/summary-exercises/auto_examples/images/thumb/plot_sprog_annual_maxima.png b/intro/summary-exercises/auto_examples/images/thumb/plot_sprog_annual_maxima.png new file mode 100644 index 0000000..c106f94 Binary files /dev/null and b/intro/summary-exercises/auto_examples/images/thumb/plot_sprog_annual_maxima.png differ diff --git a/intro/summary-exercises/auto_examples/index.rst b/intro/summary-exercises/auto_examples/index.rst new file mode 100644 index 0000000..67646b6 --- /dev/null +++ b/intro/summary-exercises/auto_examples/index.rst @@ -0,0 +1,46 @@ + +.. raw:: html + + + +Examples +======== + +.. _examples-index: +.. figure:: ./images/thumb/plot_cumulative_wind_speed_prediction.png + :target: ./plot_cumulative_wind_speed_prediction.html + + :ref:`example_plot_cumulative_wind_speed_prediction.py` + +.. figure:: ./images/thumb/plot_gumbell_wind_speed_prediction.png + :target: ./plot_gumbell_wind_speed_prediction.html + + :ref:`example_plot_gumbell_wind_speed_prediction.py` + +.. figure:: ./images/thumb/plot_sprog_annual_maxima.png + :target: ./plot_sprog_annual_maxima.html + + :ref:`example_plot_sprog_annual_maxima.py` + + +.. raw:: html + +
    + \ No newline at end of file diff --git a/intro/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.py b/intro/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.py new file mode 100644 index 0000000..a76a27b --- /dev/null +++ b/intro/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.py @@ -0,0 +1,28 @@ +"""Generate the image cumulative-wind-speed-prediction.png +for the interpolate section of scipy.rst. +""" + +import numpy as np +from scipy.interpolate import UnivariateSpline +import pylab as pl + +max_speeds = np.load('max-speeds.npy') +years_nb = max_speeds.shape[0] + +cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1) +sorted_max_speeds = np.sort(max_speeds) +speed_spline = UnivariateSpline(cprob, sorted_max_speeds) +nprob = np.linspace(0, 1, 1e2) +fitted_max_speeds = speed_spline(nprob) + +fifty_prob = 1. - 0.02 +fifty_wind = speed_spline(fifty_prob) + +pl.figure() +pl.plot(sorted_max_speeds, cprob, 'o') +pl.plot(fitted_max_speeds, nprob, 'g--') +pl.plot([fifty_wind], [fifty_prob], 'o', ms=8., mfc='y', mec='y') +pl.text(30, 0.05, '$V_{50} = %.2f \, m/s$' % fifty_wind) +pl.plot([fifty_wind, fifty_wind], [pl.axis()[2], fifty_prob], 'k--') +pl.xlabel('Annual wind speed maxima [$m/s$]') +pl.ylabel('Cumulative probability') diff --git a/intro/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.rst b/intro/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.rst new file mode 100644 index 0000000..931fe36 --- /dev/null +++ b/intro/summary-exercises/auto_examples/plot_cumulative_wind_speed_prediction.rst @@ -0,0 +1,18 @@ + + +.. _example_plot_cumulative_wind_speed_prediction.py: + +Generate the image cumulative-wind-speed-prediction.png +for the interpolate section of scipy.rst. + + + +.. image:: images/plot_cumulative_wind_speed_prediction_1.png + :align: center + + +**Python source code:** :download:`plot_cumulative_wind_speed_prediction.py ` + +.. literalinclude:: plot_cumulative_wind_speed_prediction.py + :lines: 4- + \ No newline at end of file diff --git a/intro/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.py b/intro/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.py new file mode 100644 index 0000000..447c967 --- /dev/null +++ b/intro/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.py @@ -0,0 +1,33 @@ +"""Generate the exercise results on the Gumbell distribution +""" +import numpy as np +from scipy.interpolate import UnivariateSpline +import pylab as pl + + +def gumbell_dist(arr): + return -np.log(-np.log(arr)) + +years_nb = 21 +wspeeds = np.load('sprog-windspeeds.npy') +max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) +sorted_max_speeds = np.sort(max_speeds) + +cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1) +gprob = gumbell_dist(cprob) +speed_spline = UnivariateSpline(gprob, sorted_max_speeds, k=1) +nprob = gumbell_dist(np.linspace(1e-3, 1-1e-3, 1e2)) +fitted_max_speeds = speed_spline(nprob) + +fifty_prob = gumbell_dist(49./50.) +fifty_wind = speed_spline(fifty_prob) + +pl.figure() +pl.plot(sorted_max_speeds, gprob, 'o') +pl.plot(fitted_max_speeds, nprob, 'g--') +pl.plot([fifty_wind], [fifty_prob], 'o', ms=8., mfc='y', mec='y') +pl.plot([fifty_wind, fifty_wind], [pl.axis()[2], fifty_prob], 'k--') +pl.text(35, -1, r'$V_{50} = %.2f \, m/s$' % fifty_wind) +pl.xlabel('Annual wind speed maxima [$m/s$]') +pl.ylabel('Gumbell cumulative probability') +pl.show() diff --git a/intro/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.rst b/intro/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.rst new file mode 100644 index 0000000..74698d1 --- /dev/null +++ b/intro/summary-exercises/auto_examples/plot_gumbell_wind_speed_prediction.rst @@ -0,0 +1,17 @@ + + +.. _example_plot_gumbell_wind_speed_prediction.py: + +Generate the exercise results on the Gumbell distribution + + + +.. image:: images/plot_gumbell_wind_speed_prediction_1.png + :align: center + + +**Python source code:** :download:`plot_gumbell_wind_speed_prediction.py ` + +.. literalinclude:: plot_gumbell_wind_speed_prediction.py + :lines: 3- + \ No newline at end of file diff --git a/intro/summary-exercises/auto_examples/plot_sprog_annual_maxima.py b/intro/summary-exercises/auto_examples/plot_sprog_annual_maxima.py new file mode 100644 index 0000000..d885375 --- /dev/null +++ b/intro/summary-exercises/auto_examples/plot_sprog_annual_maxima.py @@ -0,0 +1,30 @@ + +"""Generate the exercise results on the Gumbell distribution +""" +import numpy as np +from scipy.interpolate import UnivariateSpline +import pylab as pl + + +def gumbell_dist(arr): + return -np.log(-np.log(arr)) + +years_nb = 21 +wspeeds = np.load('sprog-windspeeds.npy') +max_speeds = np.array([arr.max() for arr in np.array_split(wspeeds, years_nb)]) +sorted_max_speeds = np.sort(max_speeds) + +cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1) +gprob = gumbell_dist(cprob) +speed_spline = UnivariateSpline(gprob, sorted_max_speeds, k=1) +nprob = gumbell_dist(np.linspace(1e-3, 1-1e-3, 1e2)) +fitted_max_speeds = speed_spline(nprob) + +fifty_prob = gumbell_dist(49./50.) +fifty_wind = speed_spline(fifty_prob) + +pl.figure() +pl.bar(np.arange(years_nb) + 1, max_speeds) +pl.axis('tight') +pl.xlabel('Year') +pl.ylabel('Annual wind speed maxima [$m/s$]') diff --git a/intro/summary-exercises/auto_examples/plot_sprog_annual_maxima.rst b/intro/summary-exercises/auto_examples/plot_sprog_annual_maxima.rst new file mode 100644 index 0000000..8485025 --- /dev/null +++ b/intro/summary-exercises/auto_examples/plot_sprog_annual_maxima.rst @@ -0,0 +1,17 @@ + + +.. _example_plot_sprog_annual_maxima.py: + +Generate the exercise results on the Gumbell distribution + + + +.. image:: images/plot_sprog_annual_maxima_1.png + :align: center + + +**Python source code:** :download:`plot_sprog_annual_maxima.py ` + +.. literalinclude:: plot_sprog_annual_maxima.py + :lines: 4- + \ No newline at end of file diff --git a/intro/summary-exercises/image-processing.rst b/intro/summary-exercises/image-processing.rst index f5a0c7e..e5c6fc5 100644 --- a/intro/summary-exercises/image-processing.rst +++ b/intro/summary-exercises/image-processing.rst @@ -1,6 +1,6 @@ .. _summary_exercise_image_processing: -Aplicación de proceso de imagen: contando burbujas y granos no fundidos +Image processing application: counting bubbles and unmolten grains ------------------------------------------------------------------ .. image:: ../image_processing/MV_HFV_012.jpg @@ -9,46 +9,45 @@ Aplicación de proceso de imagen: contando burbujas y granos no fundidos .. only:: latex -Definición del problema +Statement of the problem .......................... -1. Abre la imagen file MV_HFV_012.jpg y muéstrala en pantalla. Navega -a través de los argumentos del `docstring` de ``imshow`` para mostrar -la imagen con la orientación correctato display the image (origen en la -esquina inferior izquierda y no en la esquina superior izquierda como -en un array estándar). +1. Open the image file MV_HFV_012.jpg and display it. Browse through the +keyword arguments in the docstring of ``imshow`` to display the image +with the "right" orientation (origin in the bottom left corner, and not +the upper left corner as for standard arrays). -Esta imagen `Scanning Element Microscopy` representa una muestra de cristal -(matriz gris clara) con algunas burbujass (en negro) y granos de arena sin fundir (gris oscuro). -Deseamos determinar la fración de la muestra cubierta por cada una de estas tres -fases y estimar el tamaño típico de los granos de arena, de las burbujas, sus -tamaños, etc. +This Scanning Element Microscopy image shows a glass sample (light gray +matrix) with some bubbles (on black) and unmolten sand grains (dark +gray). We wish to determine the fraction of the sample covered by these +three phases, and to estimate the typical size of sand grains and +bubbles, their sizes, etc. -2. Recorta la imagen para eliminar el panel inferior con la información de la medida. +2. Crop the image to remove the lower panel with measure information. -3. Filtra ligeramente la imagen con un filtro de mediana para refinar su histograma. -Comprueba como cambia el histograma. +3. Slightly filter the image with a median filter in order to refine its +histogram. Check how the histogram changes. -4. Usando el histograma de la imagen filtrada determina umbrales que permitan definir -máscaras para los píxeles de arena, los píxeles de cristal y los píxeles de burbuja. -Otra opción (deberes para casa): escribe una función que determine automáticamente -los umbrales a partir de la mínima del histograma. +4. Using the histogram of the filtered image, determine thresholds that +allow to define masks for sand pixels, glass pixels and bubble pixels. +Other option (homework): write a function that determines automatically +the thresholds from the minima of the histogram. -5. Muestra en pantalla una imagen en la cual las tres fases (cristal, burbuja, arena) se -muestre con tres colores diferentes. +5. Display an image in which the three phases are colored with three +different colors. -6. Usa morfología matemática para limpiar las diferentes fases. +6. Use mathematical morphology to clean the different phases. -7. Creo etiquetas de atributos para todas las burbujas y los granos de arena - y elimina granos de arena que sean menores a 10 píxeles. Para hacer esto -último puedes usar ``ndimage.sum`` o ``np.bincount`` para calcular el tamaño de los granos. +7. Attribute labels to all bubbles and sand grains, and remove from the +sand mask grains that are smaller than 10 pixels. To do so, use +``ndimage.sum`` or ``np.bincount`` to compute the grain sizes. -8. Calcula el tamaño medio de las burbujas. +8. Compute the mean size of bubbles. .. only:: latex .. _image-answers: -Solución propuesta -.................... +Proposed solution +................. diff --git a/intro/summary-exercises/stats-interpolate.rst b/intro/summary-exercises/stats-interpolate.rst index 0afe028..b2e360d 100644 --- a/intro/summary-exercises/stats-interpolate.rst +++ b/intro/summary-exercises/stats-interpolate.rst @@ -79,8 +79,7 @@ of probabilities:: >>> nprob = np.linspace(0, 1, 1e2) >>> fitted_max_speeds = quantile_func(nprob) - -2% + 2% In the current model, the maximum wind speed occurring every 50 years is defined as the upper 2% quantile. As a result, the cumulative probability diff --git a/misc/yeahconsole b/misc/yeahconsole old mode 100755 new mode 100644 diff --git a/packages/3d_plotting/auto_examples/animate_data.py b/packages/3d_plotting/auto_examples/animate_data.py new file mode 100644 index 0000000..501614f --- /dev/null +++ b/packages/3d_plotting/auto_examples/animate_data.py @@ -0,0 +1,17 @@ +""" +A small demo of data animation +""" +import numpy as np +from mayavi import mlab + +# Create some simple data +x , y , z = np.ogrid[-5:5:100j ,-5:5:100j, -5:5:100j] +scalars = np.sin(x * y * z) / (x * y * z) + +iso = mlab.contour3d(scalars, transparent=True, contours=[0.5]) +for i in range(1, 20): + scalars = np.sin(i * x * y * z) /(x * y * z) + iso.mlab_source.scalars = scalars + +# Start the event loop, if needed +mlab.show() diff --git a/packages/3d_plotting/auto_examples/animate_data.rst b/packages/3d_plotting/auto_examples/animate_data.rst new file mode 100644 index 0000000..64c6165 --- /dev/null +++ b/packages/3d_plotting/auto_examples/animate_data.rst @@ -0,0 +1,13 @@ + + +.. _example_animate_data.py: + + +A small demo of data animation + + +**Python source code:** :download:`animate_data.py ` + +.. literalinclude:: animate_data.py + :lines: 4- + \ No newline at end of file diff --git a/packages/3d_plotting/auto_examples/coil_application.py b/packages/3d_plotting/auto_examples/coil_application.py new file mode 100644 index 0000000..7502c02 --- /dev/null +++ b/packages/3d_plotting/auto_examples/coil_application.py @@ -0,0 +1,272 @@ +""" +================= +Coil Application +================= + +An application to visualize the field create by a list of +coils. + +This code is fairly complex, but it is actuallty a very rich application, +and a full-blown example of what you might want to do +""" + +import numpy as np +from scipy import linalg, special +from traits.api import HasTraits, Array, CFloat, Str, List, \ + Instance, on_trait_change +from traits.ui.api import Item, View, HGroup, ListEditor, \ + HSplit, VSplit, spring +from mayavi.core.ui.api import EngineView, MlabSceneModel, \ + SceneEditor + +############################################################################## +# A current loop + +class Loop(HasTraits): + """ A current loop. + """ + direction = Array(float, value=(0, 0, 1), cols=3, + shape=(3,), desc='directing vector of the loop', + enter_set=True, auto_set=False) + + # CFloat tries to convert automatically to floats + radius = CFloat(0.1, desc='radius of the loop', + enter_set=True, auto_set=False) + + position = Array(float, value=(0, 0, 0), cols=3, + shape=(3,), desc='position of the center of the loop', + enter_set=True, auto_set=False) + + plot = None + + name = Str + + view = View(HGroup(Item('name', style='readonly', show_label=False), + spring, 'radius'), + 'position', 'direction', '_') + + # For a Borg-like pattern + __shared_state = {'number':0} + + def __init__(self, **traits): + HasTraits.__init__(self, **traits) + self.__shared_state['number'] += 1 + self.name = 'Coil %i' % self.__shared_state['number'] + + def base_vectors(self): + """ Returns 3 orthognal base vectors, the first one colinear to + the axis of the loop. + """ + # normalize n + n = self.direction / (self.direction**2).sum(axis=-1) + + # choose two vectors perpendicular to n + # choice is arbitrary since the coil is symetric about n + if np.abs(n[0])==1 : + l = np.r_[n[2], 0, -n[0]] + else: + l = np.r_[0, n[2], -n[1]] + + l /= (l**2).sum(axis=-1) + m = np.cross(n, l) + return n, l, m + + @on_trait_change('direction,radius,position') + def redraw(self): + if hasattr(self, 'app'): + self.mk_B_field() + if self.app.scene._renderer is not None: + self.display() + self.app.visualize_field() + + def display(self, half=False): + """ + Display the coil in the 3D view. + If half is True, display only one half of the coil. + """ + n, l, m = self.base_vectors() + theta = np.linspace(0, (2-half)*np.pi, 30) + theta = theta[..., np.newaxis] + coil = self.radius*(np.sin(theta)*l + np.cos(theta)*m) + coil += self.position + coil_x, coil_y, coil_z = coil.T + if self.plot is None: + self.plot = self.app.scene.mlab.plot3d(coil_x, coil_y, coil_z, + tube_radius=0.007, color=(0, 0, 1), + name=self.name ) + else: + self.plot.mlab_source.set(x=coil_x, y=coil_y, z=coil_z) + + def mk_B_field(self): + """ + returns the magnetic field for the current loop calculated + from eqns (1) and (2) in Phys Rev A Vol. 35, N 4, pp. 1535-1546; 1987. + + return: + B is a vector for the B field at point r in inverse units of + (mu I) / (2 pi d) + for I in amps and d in meters and mu = 4 pi * 10^-7 we get Tesla + """ + ### Translate the coordinates in the coil's frame + n, l, m = self.base_vectors() + R = self.radius + r0 = self.position + r = np.c_[np.ravel(self.app.X), np.ravel(self.app.Y), + np.ravel(self.app.Z)] + + # transformation matrix coil frame to lab frame + trans = np.vstack((l, m, n)) + + r -= r0 #point location from center of coil + r = np.dot(r, linalg.inv(trans) ) #transform vector to coil frame + + #### calculate field + + # express the coordinates in polar form + x = r[:, 0] + y = r[:, 1] + z = r[:, 2] + rho = np.sqrt(x**2 + y**2) + theta = np.arctan(x/y) + + E = special.ellipe((4 * R * rho)/( (R + rho)**2 + z**2)) + K = special.ellipk((4 * R * rho)/( (R + rho)**2 + z**2)) + Bz = 1/np.sqrt((R + rho)**2 + z**2) * ( + K + + E * (R**2 - rho**2 - z**2)/((R - rho)**2 + z**2) + ) + Brho = z/(rho*np.sqrt((R + rho)**2 + z**2)) * ( + -K + + E * (R**2 + rho**2 + z**2)/((R - rho)**2 + z**2) + ) + # On the axis of the coil we get a divided by zero here. This returns a + # NaN, where the field is actually zero : + Brho[np.isnan(Brho)] = 0 + + B = np.c_[np.cos(theta)*Brho, np.sin(theta)*Brho, Bz ] + + # Rotate the field back in the lab's frame + B = np.dot(B, trans) + + Bx, By, Bz = B.T + Bx = np.reshape(Bx, self.app.X.shape) + By = np.reshape(By, self.app.X.shape) + Bz = np.reshape(Bz, self.app.X.shape) + + Bnorm = np.sqrt(Bx**2 + By**2 + Bz**2) + + # We need to threshold ourselves, rather than with VTK, to be able + # to use an ImageData + Bmax = 10 * np.median(Bnorm) + + Bx[Bnorm > Bmax] = np.NAN + By[Bnorm > Bmax] = np.NAN + Bz[Bnorm > Bmax] = np.NAN + Bnorm[Bnorm > Bmax] = np.NAN + + self.Bx = Bx + self.By = By + self.Bz = Bz + self.Bnorm = Bnorm + + +############################################################################## +# The application + +class Application(HasTraits): + + scene = Instance(MlabSceneModel, (), editor=SceneEditor()) + + # The mayavi engine view. + engine_view = Instance(EngineView) + + # We use a traits List to be able to add coils to it + coils = List(Loop, + value=( Loop(position=(0, 0, -0.05), ), + Loop(position=(0, 0, 0.05), ), ), + editor=ListEditor(use_notebook=True, deletable=False, + style='custom'), + ) + + # The grid of points on which we want to evaluate the field + X, Y, Z = np.mgrid[-0.15:0.15:20j, -0.15:0.15:20j, -0.15:0.15:20j] + + # Avoid rounding issues: + f = 1e4 # this gives the precision we are interested by : + X = np.round(X * f) / f + Y = np.round(Y * f) / f + Z = np.round(Z * f) / f + + Bx = Array(value=np.zeros_like(X)) + By = Array(value=np.zeros_like(X)) + Bz = Array(value=np.zeros_like(X)) + Bnorm = Array(value=np.zeros_like(X)) + + field = None + + def __init__(self, **traits): + HasTraits.__init__(self, **traits) + self.engine_view = EngineView(engine=self.scene.engine) + + @on_trait_change('scene.activated') + def init_view(self): + # This gets fired when the viewer of the scene is created + self.scene.scene_editor.background = (0, 0, 0) + for coil in self.coils: + coil.app = self + coil.display() + coil.mk_B_field() + + self.visualize_field() + + def visualize_field(self): + self.Bx = np.zeros_like(self.X) + self.By = np.zeros_like(self.X) + self.Bz = np.zeros_like(self.X) + self.Bnorm = np.zeros_like(self.X) + for coil in self.coils: + if hasattr(coil, 'Bx'): + self.Bx += coil.Bx + self.By += coil.By + self.Bz += coil.Bz + self.Bnorm += coil.Bnorm + + if self.field is None: + self.field = self.scene.mlab.pipeline.vector_field( + self.X, self.Y, self.Z, self.Bx, self.By, self.Bz, + scalars = self.Bnorm, + name='B field') + vectors = self.scene.mlab.pipeline.vectors(self.field, + mode='arrow', resolution=10, + mask_points=6, colormap='YlOrRd', + scale_factor=2*np.abs(self.X[0,0,0] + -self.X[1,1,1]) ) + vectors.module_manager.vector_lut_manager.reverse_lut = True + vectors.glyph.mask_points.random_mode = False + self.scene.mlab.axes() + self.scp = self.scene.mlab.pipeline.scalar_cut_plane(self.field, + colormap='hot') + else: + self.field.mlab_source.set(x=self.X, y=self.Y, z=self.Z, + u=self.Bx, v=self.By, w=self.Bz, + scalars=self.Bnorm) + + view = View(HSplit( + VSplit(Item(name='engine_view', + style='custom', + resizable=True), + Item('coils', springy=True), + show_labels=False), + 'scene', + show_labels=False), + resizable=True, + title='Coils...', + height=0.8, + width=0.8, + ) + +############################################################################## +if __name__ == '__main__': + app = Application() + app.configure_traits() + diff --git a/packages/3d_plotting/auto_examples/coil_application.rst b/packages/3d_plotting/auto_examples/coil_application.rst new file mode 100644 index 0000000..03e7736 --- /dev/null +++ b/packages/3d_plotting/auto_examples/coil_application.rst @@ -0,0 +1,21 @@ + + +.. _example_coil_application.py: + + +================= +Coil Application +================= + +An application to visualize the field create by a list of +coils. + +This code is fairly complex, but it is actuallty a very rich application, +and a full-blown example of what you might want to do + + +**Python source code:** :download:`coil_application.py ` + +.. literalinclude:: coil_application.py + :lines: 12- + \ No newline at end of file diff --git a/packages/3d_plotting/auto_examples/compute_field.py b/packages/3d_plotting/auto_examples/compute_field.py new file mode 100644 index 0000000..1c6f62f --- /dev/null +++ b/packages/3d_plotting/auto_examples/compute_field.py @@ -0,0 +1,135 @@ +""" +A script that computes the magnetic field generated by a pair of Helmoltz +coils. +""" + +import numpy as np +from scipy import special, linalg + +############################################################################## +# Function to caculate the field of a loop + +def base_vectors(n): + """ Returns 3 orthognal base vectors, the first one colinear to n. + """ + # normalize n + n = n / np.sqrt(np.square(n).sum(axis=-1)) + + # choose two vectors perpendicular to n + # choice is arbitrary since the coil is symetric about n + if abs(n[0]) == 1 : + l = np.r_[n[2], 0, -n[0]] + else: + l = np.r_[0, n[2], -n[1]] + + l = l / np.sqrt(np.square(l).sum(axis=-1)) + m = np.cross(n, l) + return n, l, m + + +def B_field(r, n, r0, R): + """ + returns the magnetic field from an arbitrary current loop calculated from + eqns (1) and (2) in Phys Rev A Vol. 35, N 4, pp. 1535-1546; 1987. + + Parameters + ---------- + n is normal vector to the plane of the loop at the center, current + is oriented by the right-hand-rule. + r is a position vector where the Bfield is evaluated: + [x1 y2 z3 ; x2 y2 z2 ; ... ] + r is in units of d + r0 is the location of the center of the loop in units of d: [x y z] + R is the radius of the loop + + Returns + ------- + B is a vector for the B field at point r in inverse units of + (mu I) / (2 pi d) + for I in amps and d in meters and mu = 4 pi * 10^-7 we get Tesla + """ + ### Translate the coordinates in the coil's frame + n, l, m = base_vectors(n) + + # transformation matrix coil frame to lab frame + trans = np.vstack((l, m, n)) + # transformation matrix to lab frame to coil frame + inv_trans = linalg.inv(trans) + + r = r - r0 #point location from center of coil + r = np.dot(r, inv_trans) #transform vector to coil frame + + #### calculate field + + # express the coordinates in polar form + x = r[:, 0] + y = r[:, 1] + z = r[:, 2] + rho = np.sqrt(x**2 + y**2) + theta = np.arctan(x / y) + # NaNs are generated where y is zero. + theta[y == 0] = np.pi / 2 + + E = special.ellipe((4 * R * rho)/( (R + rho)**2 + z**2)) + K = special.ellipk((4 * R * rho)/( (R + rho)**2 + z**2)) + dist = ((R - rho)**2 + z**2) + Bz = 1 / np.sqrt((R + rho)**2 + z**2) * ( + K + + E * (R**2 - rho**2 - z**2) / dist + ) + Brho = z / (rho*np.sqrt((R + rho)**2 + z**2)) * ( + -K + + E * (R**2 + rho**2 + z**2)/ dist + ) + # On the axis of the coil we get a divided by zero here. This returns a + # NaN, where the field is actually zero : + Brho[dist == 0] = 0 + Brho[rho == 0] = 0 + Bz[dist == 0] = 0 + + B = np.c_[np.cos(theta)*Brho, np.sin(theta)*Brho, Bz ] + + # Rotate the field back in the lab's frame + B = np.dot(B, trans) + return B + + +############################################################################## +# The grid of points on which we want to evaluate the field +X, Y, Z = np.mgrid[-0.15:0.15:31j, -0.15:0.15:31j, -0.15:0.15:31j] +# Avoid rounding issues : +f = 1e4 # this gives the precision we are interested in: +X = np.round(X * f) / f +Y = np.round(Y * f) / f +Z = np.round(Z * f) / f + +# The (x, y, z) position vector +r = np.c_[np.ravel(X), np.ravel(Y), np.ravel(Z)] + + +############################################################################## +# The coil positions + +# The center of the coil +r0 = np.r_[0, 0, 0.1] +# The normal to the coils +n = np.r_[0, 0, 1] +# The radius +R = 0.1 + +# Add the mirror image of this coils relatively to the xy plane : +r0 = np.vstack((r0, -r0 )) +R = np.r_[R, R] +n = np.vstack((n, n)) # Helmoltz like configuration + +############################################################################## +# Calculate field +# First initialize a container matrix for the field vector : +B = np.zeros_like(r) +# Then loop through the different coils and sum the fields : +for this_n, this_r0, this_R in zip(n, r0, R): + this_n = np.array(this_n) + this_r0 = np.array(this_r0) + this_R = np.array(this_R) + B += B_field(r, this_n, this_r0, this_R) + diff --git a/packages/3d_plotting/auto_examples/compute_field.rst b/packages/3d_plotting/auto_examples/compute_field.rst new file mode 100644 index 0000000..2d11c4a --- /dev/null +++ b/packages/3d_plotting/auto_examples/compute_field.rst @@ -0,0 +1,14 @@ + + +.. _example_compute_field.py: + + +A script that computes the magnetic field generated by a pair of Helmoltz +coils. + + +**Python source code:** :download:`compute_field.py ` + +.. literalinclude:: compute_field.py + :lines: 5- + \ No newline at end of file diff --git a/advanced/3d_plotting/examples/generate_figures.py b/packages/3d_plotting/auto_examples/generate_figures.py similarity index 95% rename from advanced/3d_plotting/examples/generate_figures.py rename to packages/3d_plotting/auto_examples/generate_figures.py index 398f648..ebbcd3b 100644 --- a/advanced/3d_plotting/examples/generate_figures.py +++ b/packages/3d_plotting/auto_examples/generate_figures.py @@ -50,8 +50,7 @@ y = np.sin(phi) * np.sin(theta) z = np.cos(phi) mlab.mesh(x, y, z) -mlab.mesh(x, y, z, representation='wireframe', - color=(0, 0, 0)) +mlab.mesh(x, y, z, representation='wireframe', color=(0, 0, 0)) ### end mesh example mlab.view(distance='auto') diff --git a/packages/3d_plotting/auto_examples/generate_figures.rst b/packages/3d_plotting/auto_examples/generate_figures.rst new file mode 100644 index 0000000..68441db --- /dev/null +++ b/packages/3d_plotting/auto_examples/generate_figures.rst @@ -0,0 +1,13 @@ + + +.. _example_generate_figures.py: + + +Example generating the figures for the tutorial. + + +**Python source code:** :download:`generate_figures.py ` + +.. literalinclude:: generate_figures.py + :lines: 4- + \ No newline at end of file diff --git a/packages/3d_plotting/auto_examples/images/thumb/animate_data.png b/packages/3d_plotting/auto_examples/images/thumb/animate_data.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/packages/3d_plotting/auto_examples/images/thumb/animate_data.png differ diff --git a/packages/3d_plotting/auto_examples/images/thumb/coil_application.png b/packages/3d_plotting/auto_examples/images/thumb/coil_application.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/packages/3d_plotting/auto_examples/images/thumb/coil_application.png differ diff --git a/packages/3d_plotting/auto_examples/images/thumb/compute_field.png b/packages/3d_plotting/auto_examples/images/thumb/compute_field.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/packages/3d_plotting/auto_examples/images/thumb/compute_field.png differ diff --git a/packages/3d_plotting/auto_examples/images/thumb/generate_figures.png b/packages/3d_plotting/auto_examples/images/thumb/generate_figures.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/packages/3d_plotting/auto_examples/images/thumb/generate_figures.png differ diff --git a/packages/3d_plotting/auto_examples/images/thumb/mlab_dialog.png b/packages/3d_plotting/auto_examples/images/thumb/mlab_dialog.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/packages/3d_plotting/auto_examples/images/thumb/mlab_dialog.png differ diff --git a/packages/3d_plotting/auto_examples/images/thumb/mlab_interactive_dialog.png b/packages/3d_plotting/auto_examples/images/thumb/mlab_interactive_dialog.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/packages/3d_plotting/auto_examples/images/thumb/mlab_interactive_dialog.png differ diff --git a/packages/3d_plotting/auto_examples/images/thumb/simple_example.png b/packages/3d_plotting/auto_examples/images/thumb/simple_example.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/packages/3d_plotting/auto_examples/images/thumb/simple_example.png differ diff --git a/packages/3d_plotting/auto_examples/images/thumb/visualize_field.png b/packages/3d_plotting/auto_examples/images/thumb/visualize_field.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/packages/3d_plotting/auto_examples/images/thumb/visualize_field.png differ diff --git a/packages/3d_plotting/auto_examples/images/thumb/viz_volume_structure.png b/packages/3d_plotting/auto_examples/images/thumb/viz_volume_structure.png new file mode 100644 index 0000000..4913b99 Binary files /dev/null and b/packages/3d_plotting/auto_examples/images/thumb/viz_volume_structure.png differ diff --git a/packages/3d_plotting/auto_examples/index.rst b/packages/3d_plotting/auto_examples/index.rst new file mode 100644 index 0000000..279dcab --- /dev/null +++ b/packages/3d_plotting/auto_examples/index.rst @@ -0,0 +1,76 @@ + +.. raw:: html + + + +Examples +======== + +.. _examples-index: +.. figure:: ./images/thumb/animate_data.png + :target: ./animate_data.html + + :ref:`example_animate_data.py` + +.. figure:: ./images/thumb/coil_application.png + :target: ./coil_application.html + + :ref:`example_coil_application.py` + +.. figure:: ./images/thumb/compute_field.png + :target: ./compute_field.html + + :ref:`example_compute_field.py` + +.. figure:: ./images/thumb/generate_figures.png + :target: ./generate_figures.html + + :ref:`example_generate_figures.py` + +.. figure:: ./images/thumb/mlab_dialog.png + :target: ./mlab_dialog.html + + :ref:`example_mlab_dialog.py` + +.. figure:: ./images/thumb/mlab_interactive_dialog.png + :target: ./mlab_interactive_dialog.html + + :ref:`example_mlab_interactive_dialog.py` + +.. figure:: ./images/thumb/simple_example.png + :target: ./simple_example.html + + :ref:`example_simple_example.py` + +.. figure:: ./images/thumb/visualize_field.png + :target: ./visualize_field.html + + :ref:`example_visualize_field.py` + +.. figure:: ./images/thumb/viz_volume_structure.png + :target: ./viz_volume_structure.html + + :ref:`example_viz_volume_structure.py` + + +.. raw:: html + +
    + \ No newline at end of file diff --git a/packages/3d_plotting/auto_examples/mlab_dialog.py b/packages/3d_plotting/auto_examples/mlab_dialog.py new file mode 100644 index 0000000..d4e6edb --- /dev/null +++ b/packages/3d_plotting/auto_examples/mlab_dialog.py @@ -0,0 +1,34 @@ +""" +Simple example demoing a dialog with Mayavi +""" + +import numpy as np +from traits.api import HasTraits, Instance +from traitsui.api import View, Item, HGroup +from mayavi.core.ui.api import SceneEditor, MlabSceneModel + +def curve(n_turns): + "The function creating the x, y, z coordinates needed to plot" + phi = np.linspace(0, 2*np.pi, 2000) + return [np.cos(phi) * (1 + 0.5*np.cos(n_turns*phi)), + np.sin(phi) * (1 + 0.5*np.cos(n_turns*phi)), + 0.5*np.sin(n_turns*phi)] + + +class Visualization(HasTraits): + "The class that contains the dialog" + scene = Instance(MlabSceneModel, ()) + + def __init__(self): + HasTraits.__init__(self) + x, y, z = curve(n_turns=2) + # Populating our plot + self.plot = self.scene.mlab.plot3d(x, y, z) + + # Describe the dialog + view = View(Item('scene', height=300, show_label=False, + editor=SceneEditor()), + HGroup('n_turns'), resizable=True) + +# Fire up the dialog +Visualization().configure_traits() diff --git a/packages/3d_plotting/auto_examples/mlab_dialog.rst b/packages/3d_plotting/auto_examples/mlab_dialog.rst new file mode 100644 index 0000000..544fdb8 --- /dev/null +++ b/packages/3d_plotting/auto_examples/mlab_dialog.rst @@ -0,0 +1,13 @@ + + +.. _example_mlab_dialog.py: + + +Simple example demoing a dialog with Mayavi + + +**Python source code:** :download:`mlab_dialog.py ` + +.. literalinclude:: mlab_dialog.py + :lines: 4- + \ No newline at end of file diff --git a/packages/3d_plotting/auto_examples/mlab_interactive_dialog.py b/packages/3d_plotting/auto_examples/mlab_interactive_dialog.py new file mode 100644 index 0000000..db925f5 --- /dev/null +++ b/packages/3d_plotting/auto_examples/mlab_interactive_dialog.py @@ -0,0 +1,39 @@ +""" +Example demoing an interactive dialog with Mayavi +""" + +import numpy as np +from traits.api import HasTraits, Instance +from traitsui.api import View, Item, HGroup +from mayavi.core.ui.api import SceneEditor, MlabSceneModel + +def curve(n_turns): + phi = np.linspace(0, 2*np.pi, 2000) + return [np.cos(phi) * (1 + 0.5*np.cos(n_turns*phi)), + np.sin(phi) * (1 + 0.5*np.cos(n_turns*phi)), + 0.5*np.sin(n_turns*phi)] + + +# The class that contains the dialog +from traits.api import Range, on_trait_change + +class Visualization(HasTraits): + n_turns = Range(0, 30, 11) + scene = Instance(MlabSceneModel, ()) + + def __init__(self): + HasTraits.__init__(self) + x, y, z = curve(self.n_turns) + self.plot = self.scene.mlab.plot3d(x, y, z) + + @on_trait_change('n_turns') + def update_plot(self): + x, y, z = curve(self.n_turns) + self.plot.mlab_source.set(x=x, y=y, z=z) + + view = View(Item('scene', height=300, show_label=False, + editor=SceneEditor()), + HGroup('n_turns'), resizable=True) + +# Fire up the dialog +Visualization().configure_traits() diff --git a/packages/3d_plotting/auto_examples/mlab_interactive_dialog.rst b/packages/3d_plotting/auto_examples/mlab_interactive_dialog.rst new file mode 100644 index 0000000..f216654 --- /dev/null +++ b/packages/3d_plotting/auto_examples/mlab_interactive_dialog.rst @@ -0,0 +1,13 @@ + + +.. _example_mlab_interactive_dialog.py: + + +Example demoing an interactive dialog with Mayavi + + +**Python source code:** :download:`mlab_interactive_dialog.py ` + +.. literalinclude:: mlab_interactive_dialog.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/3d_plotting/examples/simple_example.py b/packages/3d_plotting/auto_examples/simple_example.py similarity index 100% rename from advanced/3d_plotting/examples/simple_example.py rename to packages/3d_plotting/auto_examples/simple_example.py diff --git a/packages/3d_plotting/auto_examples/simple_example.rst b/packages/3d_plotting/auto_examples/simple_example.rst new file mode 100644 index 0000000..28beb42 --- /dev/null +++ b/packages/3d_plotting/auto_examples/simple_example.rst @@ -0,0 +1,11 @@ + + +.. _example_simple_example.py: + + + +**Python source code:** :download:`simple_example.py ` + +.. literalinclude:: simple_example.py + :lines: 2- + \ No newline at end of file diff --git a/packages/3d_plotting/auto_examples/visualize_field.py b/packages/3d_plotting/auto_examples/visualize_field.py new file mode 100644 index 0000000..1efce9d --- /dev/null +++ b/packages/3d_plotting/auto_examples/visualize_field.py @@ -0,0 +1,63 @@ +""" +Visualize the field created by a pair of Helmoltz coils +""" + +import numpy as np +from scipy import stats + +from mayavi import mlab + +# "import" our data from our previous script (the import actually runs +# the script and computes B) +from compute_field import B, X, Y, Z + +############################################################################### +# Data massaging + +# Reshape the data to put it in a form that can be fed in Mayavi +Bx = B[:, 0] +By = B[:, 1] +Bz = B[:, 2] +Bx = np.reshape(Bx, X.shape) +By = np.reshape(By, X.shape) +Bz = np.reshape(Bz, X.shape) + +Bnorm = np.sqrt(Bx**2 + By**2 + Bz**2) + +# Threshold, to avoid the very high values +Bmax = stats.scoreatpercentile(Bnorm.ravel(), 99) + +Bx[Bnorm > Bmax] = Bmax * (Bx / Bnorm)[Bnorm > Bmax] +By[Bnorm > Bmax] = Bmax * (By / Bnorm)[Bnorm > Bmax] +Bz[Bnorm > Bmax] = Bmax * (Bz / Bnorm)[Bnorm > Bmax] +Bnorm[Bnorm > Bmax] = Bmax + +############################################################################### +# Visualization proper + +# Create a mayavi figure black on white +mlab.figure(bgcolor=(0., 0., 0.), fgcolor=(1., 1., 1.), size=(640, 480)) + +# Create a vector_field: a data source that we can slice and dice +field = mlab.pipeline.vector_field(X, Y, Z, Bx, By, Bz, + scalars=Bnorm, + name='B field') +# Plot the vectors +vectors = mlab.pipeline.vectors(field, + scale_factor=abs(X[0, 0, 0] - X[1, 1, 1]), + colormap='hot') +mlab.axes() + +# Mask 7 data points out of 8 +vectors.glyph.mask_input_points = True +vectors.glyph.mask_points.on_ratio = 8 + +mlab.pipeline.vector_cut_plane(field, scale_factor=.1, colormap='hot') + +# Add an iso_surface of the norm of the field +mlab.pipeline.iso_surface(mlab.pipeline.extract_vector_norm(field), + contours=[0.1*Bmax, 0.4*Bmax], + opacity=0.5, transparent=True) + +mlab.view(28, 84, 0.71) +mlab.savefig('visualize_field.png') diff --git a/packages/3d_plotting/auto_examples/visualize_field.rst b/packages/3d_plotting/auto_examples/visualize_field.rst new file mode 100644 index 0000000..775ac4f --- /dev/null +++ b/packages/3d_plotting/auto_examples/visualize_field.rst @@ -0,0 +1,13 @@ + + +.. _example_visualize_field.py: + + +Visualize the field created by a pair of Helmoltz coils + + +**Python source code:** :download:`visualize_field.py ` + +.. literalinclude:: visualize_field.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/3d_plotting/examples/viz_volume_structure.py b/packages/3d_plotting/auto_examples/viz_volume_structure.py similarity index 95% rename from advanced/3d_plotting/examples/viz_volume_structure.py rename to packages/3d_plotting/auto_examples/viz_volume_structure.py index 5f41d33..f75603f 100644 --- a/advanced/3d_plotting/examples/viz_volume_structure.py +++ b/packages/3d_plotting/auto_examples/viz_volume_structure.py @@ -2,7 +2,7 @@ Use Mayavi to visualize the structure of a VolumeImg """ -from enthought.mayavi import mlab +from mayavi import mlab import numpy as np x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j] diff --git a/packages/3d_plotting/auto_examples/viz_volume_structure.rst b/packages/3d_plotting/auto_examples/viz_volume_structure.rst new file mode 100644 index 0000000..de6a5d4 --- /dev/null +++ b/packages/3d_plotting/auto_examples/viz_volume_structure.rst @@ -0,0 +1,13 @@ + + +.. _example_viz_volume_structure.py: + + +Use Mayavi to visualize the structure of a VolumeImg + + +**Python source code:** :download:`viz_volume_structure.py ` + +.. literalinclude:: viz_volume_structure.py + :lines: 4- + \ No newline at end of file diff --git a/advanced/3d_plotting/conf.py b/packages/3d_plotting/conf.py similarity index 99% rename from advanced/3d_plotting/conf.py rename to packages/3d_plotting/conf.py index 6d1e34a..6f70af8 100644 --- a/advanced/3d_plotting/conf.py +++ b/packages/3d_plotting/conf.py @@ -61,7 +61,7 @@ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -language = 'en' +language = 'es' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: diff --git a/advanced/3d_plotting/decorations.png b/packages/3d_plotting/decorations.png similarity index 100% rename from advanced/3d_plotting/decorations.png rename to packages/3d_plotting/decorations.png diff --git a/packages/3d_plotting/examples/animate_data.py b/packages/3d_plotting/examples/animate_data.py new file mode 100644 index 0000000..501614f --- /dev/null +++ b/packages/3d_plotting/examples/animate_data.py @@ -0,0 +1,17 @@ +""" +A small demo of data animation +""" +import numpy as np +from mayavi import mlab + +# Create some simple data +x , y , z = np.ogrid[-5:5:100j ,-5:5:100j, -5:5:100j] +scalars = np.sin(x * y * z) / (x * y * z) + +iso = mlab.contour3d(scalars, transparent=True, contours=[0.5]) +for i in range(1, 20): + scalars = np.sin(i * x * y * z) /(x * y * z) + iso.mlab_source.scalars = scalars + +# Start the event loop, if needed +mlab.show() diff --git a/packages/3d_plotting/examples/coil_application.py b/packages/3d_plotting/examples/coil_application.py new file mode 100644 index 0000000..7502c02 --- /dev/null +++ b/packages/3d_plotting/examples/coil_application.py @@ -0,0 +1,272 @@ +""" +================= +Coil Application +================= + +An application to visualize the field create by a list of +coils. + +This code is fairly complex, but it is actuallty a very rich application, +and a full-blown example of what you might want to do +""" + +import numpy as np +from scipy import linalg, special +from traits.api import HasTraits, Array, CFloat, Str, List, \ + Instance, on_trait_change +from traits.ui.api import Item, View, HGroup, ListEditor, \ + HSplit, VSplit, spring +from mayavi.core.ui.api import EngineView, MlabSceneModel, \ + SceneEditor + +############################################################################## +# A current loop + +class Loop(HasTraits): + """ A current loop. + """ + direction = Array(float, value=(0, 0, 1), cols=3, + shape=(3,), desc='directing vector of the loop', + enter_set=True, auto_set=False) + + # CFloat tries to convert automatically to floats + radius = CFloat(0.1, desc='radius of the loop', + enter_set=True, auto_set=False) + + position = Array(float, value=(0, 0, 0), cols=3, + shape=(3,), desc='position of the center of the loop', + enter_set=True, auto_set=False) + + plot = None + + name = Str + + view = View(HGroup(Item('name', style='readonly', show_label=False), + spring, 'radius'), + 'position', 'direction', '_') + + # For a Borg-like pattern + __shared_state = {'number':0} + + def __init__(self, **traits): + HasTraits.__init__(self, **traits) + self.__shared_state['number'] += 1 + self.name = 'Coil %i' % self.__shared_state['number'] + + def base_vectors(self): + """ Returns 3 orthognal base vectors, the first one colinear to + the axis of the loop. + """ + # normalize n + n = self.direction / (self.direction**2).sum(axis=-1) + + # choose two vectors perpendicular to n + # choice is arbitrary since the coil is symetric about n + if np.abs(n[0])==1 : + l = np.r_[n[2], 0, -n[0]] + else: + l = np.r_[0, n[2], -n[1]] + + l /= (l**2).sum(axis=-1) + m = np.cross(n, l) + return n, l, m + + @on_trait_change('direction,radius,position') + def redraw(self): + if hasattr(self, 'app'): + self.mk_B_field() + if self.app.scene._renderer is not None: + self.display() + self.app.visualize_field() + + def display(self, half=False): + """ + Display the coil in the 3D view. + If half is True, display only one half of the coil. + """ + n, l, m = self.base_vectors() + theta = np.linspace(0, (2-half)*np.pi, 30) + theta = theta[..., np.newaxis] + coil = self.radius*(np.sin(theta)*l + np.cos(theta)*m) + coil += self.position + coil_x, coil_y, coil_z = coil.T + if self.plot is None: + self.plot = self.app.scene.mlab.plot3d(coil_x, coil_y, coil_z, + tube_radius=0.007, color=(0, 0, 1), + name=self.name ) + else: + self.plot.mlab_source.set(x=coil_x, y=coil_y, z=coil_z) + + def mk_B_field(self): + """ + returns the magnetic field for the current loop calculated + from eqns (1) and (2) in Phys Rev A Vol. 35, N 4, pp. 1535-1546; 1987. + + return: + B is a vector for the B field at point r in inverse units of + (mu I) / (2 pi d) + for I in amps and d in meters and mu = 4 pi * 10^-7 we get Tesla + """ + ### Translate the coordinates in the coil's frame + n, l, m = self.base_vectors() + R = self.radius + r0 = self.position + r = np.c_[np.ravel(self.app.X), np.ravel(self.app.Y), + np.ravel(self.app.Z)] + + # transformation matrix coil frame to lab frame + trans = np.vstack((l, m, n)) + + r -= r0 #point location from center of coil + r = np.dot(r, linalg.inv(trans) ) #transform vector to coil frame + + #### calculate field + + # express the coordinates in polar form + x = r[:, 0] + y = r[:, 1] + z = r[:, 2] + rho = np.sqrt(x**2 + y**2) + theta = np.arctan(x/y) + + E = special.ellipe((4 * R * rho)/( (R + rho)**2 + z**2)) + K = special.ellipk((4 * R * rho)/( (R + rho)**2 + z**2)) + Bz = 1/np.sqrt((R + rho)**2 + z**2) * ( + K + + E * (R**2 - rho**2 - z**2)/((R - rho)**2 + z**2) + ) + Brho = z/(rho*np.sqrt((R + rho)**2 + z**2)) * ( + -K + + E * (R**2 + rho**2 + z**2)/((R - rho)**2 + z**2) + ) + # On the axis of the coil we get a divided by zero here. This returns a + # NaN, where the field is actually zero : + Brho[np.isnan(Brho)] = 0 + + B = np.c_[np.cos(theta)*Brho, np.sin(theta)*Brho, Bz ] + + # Rotate the field back in the lab's frame + B = np.dot(B, trans) + + Bx, By, Bz = B.T + Bx = np.reshape(Bx, self.app.X.shape) + By = np.reshape(By, self.app.X.shape) + Bz = np.reshape(Bz, self.app.X.shape) + + Bnorm = np.sqrt(Bx**2 + By**2 + Bz**2) + + # We need to threshold ourselves, rather than with VTK, to be able + # to use an ImageData + Bmax = 10 * np.median(Bnorm) + + Bx[Bnorm > Bmax] = np.NAN + By[Bnorm > Bmax] = np.NAN + Bz[Bnorm > Bmax] = np.NAN + Bnorm[Bnorm > Bmax] = np.NAN + + self.Bx = Bx + self.By = By + self.Bz = Bz + self.Bnorm = Bnorm + + +############################################################################## +# The application + +class Application(HasTraits): + + scene = Instance(MlabSceneModel, (), editor=SceneEditor()) + + # The mayavi engine view. + engine_view = Instance(EngineView) + + # We use a traits List to be able to add coils to it + coils = List(Loop, + value=( Loop(position=(0, 0, -0.05), ), + Loop(position=(0, 0, 0.05), ), ), + editor=ListEditor(use_notebook=True, deletable=False, + style='custom'), + ) + + # The grid of points on which we want to evaluate the field + X, Y, Z = np.mgrid[-0.15:0.15:20j, -0.15:0.15:20j, -0.15:0.15:20j] + + # Avoid rounding issues: + f = 1e4 # this gives the precision we are interested by : + X = np.round(X * f) / f + Y = np.round(Y * f) / f + Z = np.round(Z * f) / f + + Bx = Array(value=np.zeros_like(X)) + By = Array(value=np.zeros_like(X)) + Bz = Array(value=np.zeros_like(X)) + Bnorm = Array(value=np.zeros_like(X)) + + field = None + + def __init__(self, **traits): + HasTraits.__init__(self, **traits) + self.engine_view = EngineView(engine=self.scene.engine) + + @on_trait_change('scene.activated') + def init_view(self): + # This gets fired when the viewer of the scene is created + self.scene.scene_editor.background = (0, 0, 0) + for coil in self.coils: + coil.app = self + coil.display() + coil.mk_B_field() + + self.visualize_field() + + def visualize_field(self): + self.Bx = np.zeros_like(self.X) + self.By = np.zeros_like(self.X) + self.Bz = np.zeros_like(self.X) + self.Bnorm = np.zeros_like(self.X) + for coil in self.coils: + if hasattr(coil, 'Bx'): + self.Bx += coil.Bx + self.By += coil.By + self.Bz += coil.Bz + self.Bnorm += coil.Bnorm + + if self.field is None: + self.field = self.scene.mlab.pipeline.vector_field( + self.X, self.Y, self.Z, self.Bx, self.By, self.Bz, + scalars = self.Bnorm, + name='B field') + vectors = self.scene.mlab.pipeline.vectors(self.field, + mode='arrow', resolution=10, + mask_points=6, colormap='YlOrRd', + scale_factor=2*np.abs(self.X[0,0,0] + -self.X[1,1,1]) ) + vectors.module_manager.vector_lut_manager.reverse_lut = True + vectors.glyph.mask_points.random_mode = False + self.scene.mlab.axes() + self.scp = self.scene.mlab.pipeline.scalar_cut_plane(self.field, + colormap='hot') + else: + self.field.mlab_source.set(x=self.X, y=self.Y, z=self.Z, + u=self.Bx, v=self.By, w=self.Bz, + scalars=self.Bnorm) + + view = View(HSplit( + VSplit(Item(name='engine_view', + style='custom', + resizable=True), + Item('coils', springy=True), + show_labels=False), + 'scene', + show_labels=False), + resizable=True, + title='Coils...', + height=0.8, + width=0.8, + ) + +############################################################################## +if __name__ == '__main__': + app = Application() + app.configure_traits() + diff --git a/packages/3d_plotting/examples/compute_field.py b/packages/3d_plotting/examples/compute_field.py new file mode 100644 index 0000000..1c6f62f --- /dev/null +++ b/packages/3d_plotting/examples/compute_field.py @@ -0,0 +1,135 @@ +""" +A script that computes the magnetic field generated by a pair of Helmoltz +coils. +""" + +import numpy as np +from scipy import special, linalg + +############################################################################## +# Function to caculate the field of a loop + +def base_vectors(n): + """ Returns 3 orthognal base vectors, the first one colinear to n. + """ + # normalize n + n = n / np.sqrt(np.square(n).sum(axis=-1)) + + # choose two vectors perpendicular to n + # choice is arbitrary since the coil is symetric about n + if abs(n[0]) == 1 : + l = np.r_[n[2], 0, -n[0]] + else: + l = np.r_[0, n[2], -n[1]] + + l = l / np.sqrt(np.square(l).sum(axis=-1)) + m = np.cross(n, l) + return n, l, m + + +def B_field(r, n, r0, R): + """ + returns the magnetic field from an arbitrary current loop calculated from + eqns (1) and (2) in Phys Rev A Vol. 35, N 4, pp. 1535-1546; 1987. + + Parameters + ---------- + n is normal vector to the plane of the loop at the center, current + is oriented by the right-hand-rule. + r is a position vector where the Bfield is evaluated: + [x1 y2 z3 ; x2 y2 z2 ; ... ] + r is in units of d + r0 is the location of the center of the loop in units of d: [x y z] + R is the radius of the loop + + Returns + ------- + B is a vector for the B field at point r in inverse units of + (mu I) / (2 pi d) + for I in amps and d in meters and mu = 4 pi * 10^-7 we get Tesla + """ + ### Translate the coordinates in the coil's frame + n, l, m = base_vectors(n) + + # transformation matrix coil frame to lab frame + trans = np.vstack((l, m, n)) + # transformation matrix to lab frame to coil frame + inv_trans = linalg.inv(trans) + + r = r - r0 #point location from center of coil + r = np.dot(r, inv_trans) #transform vector to coil frame + + #### calculate field + + # express the coordinates in polar form + x = r[:, 0] + y = r[:, 1] + z = r[:, 2] + rho = np.sqrt(x**2 + y**2) + theta = np.arctan(x / y) + # NaNs are generated where y is zero. + theta[y == 0] = np.pi / 2 + + E = special.ellipe((4 * R * rho)/( (R + rho)**2 + z**2)) + K = special.ellipk((4 * R * rho)/( (R + rho)**2 + z**2)) + dist = ((R - rho)**2 + z**2) + Bz = 1 / np.sqrt((R + rho)**2 + z**2) * ( + K + + E * (R**2 - rho**2 - z**2) / dist + ) + Brho = z / (rho*np.sqrt((R + rho)**2 + z**2)) * ( + -K + + E * (R**2 + rho**2 + z**2)/ dist + ) + # On the axis of the coil we get a divided by zero here. This returns a + # NaN, where the field is actually zero : + Brho[dist == 0] = 0 + Brho[rho == 0] = 0 + Bz[dist == 0] = 0 + + B = np.c_[np.cos(theta)*Brho, np.sin(theta)*Brho, Bz ] + + # Rotate the field back in the lab's frame + B = np.dot(B, trans) + return B + + +############################################################################## +# The grid of points on which we want to evaluate the field +X, Y, Z = np.mgrid[-0.15:0.15:31j, -0.15:0.15:31j, -0.15:0.15:31j] +# Avoid rounding issues : +f = 1e4 # this gives the precision we are interested in: +X = np.round(X * f) / f +Y = np.round(Y * f) / f +Z = np.round(Z * f) / f + +# The (x, y, z) position vector +r = np.c_[np.ravel(X), np.ravel(Y), np.ravel(Z)] + + +############################################################################## +# The coil positions + +# The center of the coil +r0 = np.r_[0, 0, 0.1] +# The normal to the coils +n = np.r_[0, 0, 1] +# The radius +R = 0.1 + +# Add the mirror image of this coils relatively to the xy plane : +r0 = np.vstack((r0, -r0 )) +R = np.r_[R, R] +n = np.vstack((n, n)) # Helmoltz like configuration + +############################################################################## +# Calculate field +# First initialize a container matrix for the field vector : +B = np.zeros_like(r) +# Then loop through the different coils and sum the fields : +for this_n, this_r0, this_R in zip(n, r0, R): + this_n = np.array(this_n) + this_r0 = np.array(this_r0) + this_R = np.array(this_R) + B += B_field(r, this_n, this_r0, this_R) + diff --git a/advanced/3d_plotting/examples/contour3d.png b/packages/3d_plotting/examples/contour3d.png similarity index 100% rename from advanced/3d_plotting/examples/contour3d.png rename to packages/3d_plotting/examples/contour3d.png diff --git a/packages/3d_plotting/examples/generate_figures.py b/packages/3d_plotting/examples/generate_figures.py new file mode 100644 index 0000000..ebbcd3b --- /dev/null +++ b/packages/3d_plotting/examples/generate_figures.py @@ -0,0 +1,70 @@ +""" +Example generating the figures for the tutorial. +""" +import numpy as np +from mayavi import mlab + +# Seed the random number generator, for reproducibility +np.random.seed(0) + +mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300)) +mlab.clf() + +### begin points3d example +x, y, z, value = np.random.random((4, 40)) +mlab.points3d(x, y, z, value) +### end points3d example + +mlab.view(distance='auto') +mlab.text(.02, .9, 'points3d', width=.35) +mlab.savefig('points3d.png') + + +### begin plot3d example +mlab.clf() # Clear the figure +t = np.linspace(0, 20, 200) +mlab.plot3d(np.sin(t), np.cos(t), 0.1*t, t) +### end plot3d example + +mlab.view(distance='auto') +mlab.text(.02, .9, 'plot3d', width=.25) +mlab.savefig('plot3d.png') + + +### begin surf example +mlab.clf() +x, y = np.mgrid[-10:10:100j, -10:10:100j] +r = np.sqrt(x**2 + y**2) +z = np.sin(r)/r +mlab.surf(z, warp_scale='auto') +### end surf example + +mlab.view(distance='auto') +mlab.text(.02, .9, 'surf', width=.15) +mlab.savefig('surf.png') + +### begin mesh example +mlab.clf() +phi, theta = np.mgrid[0:np.pi:11j, 0:2*np.pi:11j] +x = np.sin(phi) * np.cos(theta) +y = np.sin(phi) * np.sin(theta) +z = np.cos(phi) +mlab.mesh(x, y, z) +mlab.mesh(x, y, z, representation='wireframe', color=(0, 0, 0)) +### end mesh example + +mlab.view(distance='auto') +mlab.text(.02, .9, 'mesh', width=.2) +mlab.savefig('mesh.png') + +### begin contour3d example +mlab.clf() +x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j] +values = x*x*0.5 + y*y + z*z*2.0 +mlab.contour3d(values) +### end contour3d example + +mlab.view(distance='auto') +mlab.text(.02, .9, 'contour3d', width=.45) +mlab.savefig('contour3d.png') + diff --git a/advanced/3d_plotting/examples/mesh.png b/packages/3d_plotting/examples/mesh.png similarity index 100% rename from advanced/3d_plotting/examples/mesh.png rename to packages/3d_plotting/examples/mesh.png diff --git a/packages/3d_plotting/examples/mlab_dialog.py b/packages/3d_plotting/examples/mlab_dialog.py new file mode 100644 index 0000000..d4e6edb --- /dev/null +++ b/packages/3d_plotting/examples/mlab_dialog.py @@ -0,0 +1,34 @@ +""" +Simple example demoing a dialog with Mayavi +""" + +import numpy as np +from traits.api import HasTraits, Instance +from traitsui.api import View, Item, HGroup +from mayavi.core.ui.api import SceneEditor, MlabSceneModel + +def curve(n_turns): + "The function creating the x, y, z coordinates needed to plot" + phi = np.linspace(0, 2*np.pi, 2000) + return [np.cos(phi) * (1 + 0.5*np.cos(n_turns*phi)), + np.sin(phi) * (1 + 0.5*np.cos(n_turns*phi)), + 0.5*np.sin(n_turns*phi)] + + +class Visualization(HasTraits): + "The class that contains the dialog" + scene = Instance(MlabSceneModel, ()) + + def __init__(self): + HasTraits.__init__(self) + x, y, z = curve(n_turns=2) + # Populating our plot + self.plot = self.scene.mlab.plot3d(x, y, z) + + # Describe the dialog + view = View(Item('scene', height=300, show_label=False, + editor=SceneEditor()), + HGroup('n_turns'), resizable=True) + +# Fire up the dialog +Visualization().configure_traits() diff --git a/packages/3d_plotting/examples/mlab_interactive_dialog.png b/packages/3d_plotting/examples/mlab_interactive_dialog.png new file mode 100644 index 0000000..a260477 Binary files /dev/null and b/packages/3d_plotting/examples/mlab_interactive_dialog.png differ diff --git a/packages/3d_plotting/examples/mlab_interactive_dialog.py b/packages/3d_plotting/examples/mlab_interactive_dialog.py new file mode 100644 index 0000000..db925f5 --- /dev/null +++ b/packages/3d_plotting/examples/mlab_interactive_dialog.py @@ -0,0 +1,39 @@ +""" +Example demoing an interactive dialog with Mayavi +""" + +import numpy as np +from traits.api import HasTraits, Instance +from traitsui.api import View, Item, HGroup +from mayavi.core.ui.api import SceneEditor, MlabSceneModel + +def curve(n_turns): + phi = np.linspace(0, 2*np.pi, 2000) + return [np.cos(phi) * (1 + 0.5*np.cos(n_turns*phi)), + np.sin(phi) * (1 + 0.5*np.cos(n_turns*phi)), + 0.5*np.sin(n_turns*phi)] + + +# The class that contains the dialog +from traits.api import Range, on_trait_change + +class Visualization(HasTraits): + n_turns = Range(0, 30, 11) + scene = Instance(MlabSceneModel, ()) + + def __init__(self): + HasTraits.__init__(self) + x, y, z = curve(self.n_turns) + self.plot = self.scene.mlab.plot3d(x, y, z) + + @on_trait_change('n_turns') + def update_plot(self): + x, y, z = curve(self.n_turns) + self.plot.mlab_source.set(x=x, y=y, z=z) + + view = View(Item('scene', height=300, show_label=False, + editor=SceneEditor()), + HGroup('n_turns'), resizable=True) + +# Fire up the dialog +Visualization().configure_traits() diff --git a/advanced/3d_plotting/examples/plot3d.png b/packages/3d_plotting/examples/plot3d.png similarity index 100% rename from advanced/3d_plotting/examples/plot3d.png rename to packages/3d_plotting/examples/plot3d.png diff --git a/advanced/3d_plotting/examples/points3d.png b/packages/3d_plotting/examples/points3d.png similarity index 100% rename from advanced/3d_plotting/examples/points3d.png rename to packages/3d_plotting/examples/points3d.png diff --git a/packages/3d_plotting/examples/simple_example.py b/packages/3d_plotting/examples/simple_example.py new file mode 100644 index 0000000..5e5e464 --- /dev/null +++ b/packages/3d_plotting/examples/simple_example.py @@ -0,0 +1,11 @@ +import numpy as np + +x, y = np.mgrid[-10:10:100j, -10:10:100j] +r = np.sqrt(x**2 + y**2) +z = np.sin(r)/r + +from enthought.mayavi import mlab +mlab.surf(z, warp_scale='auto') + +mlab.outline() +mlab.axes() diff --git a/advanced/3d_plotting/examples/surf.png b/packages/3d_plotting/examples/surf.png similarity index 100% rename from advanced/3d_plotting/examples/surf.png rename to packages/3d_plotting/examples/surf.png diff --git a/packages/3d_plotting/examples/visualize_field.png b/packages/3d_plotting/examples/visualize_field.png new file mode 100644 index 0000000..9eba54e Binary files /dev/null and b/packages/3d_plotting/examples/visualize_field.png differ diff --git a/packages/3d_plotting/examples/visualize_field.py b/packages/3d_plotting/examples/visualize_field.py new file mode 100644 index 0000000..1efce9d --- /dev/null +++ b/packages/3d_plotting/examples/visualize_field.py @@ -0,0 +1,63 @@ +""" +Visualize the field created by a pair of Helmoltz coils +""" + +import numpy as np +from scipy import stats + +from mayavi import mlab + +# "import" our data from our previous script (the import actually runs +# the script and computes B) +from compute_field import B, X, Y, Z + +############################################################################### +# Data massaging + +# Reshape the data to put it in a form that can be fed in Mayavi +Bx = B[:, 0] +By = B[:, 1] +Bz = B[:, 2] +Bx = np.reshape(Bx, X.shape) +By = np.reshape(By, X.shape) +Bz = np.reshape(Bz, X.shape) + +Bnorm = np.sqrt(Bx**2 + By**2 + Bz**2) + +# Threshold, to avoid the very high values +Bmax = stats.scoreatpercentile(Bnorm.ravel(), 99) + +Bx[Bnorm > Bmax] = Bmax * (Bx / Bnorm)[Bnorm > Bmax] +By[Bnorm > Bmax] = Bmax * (By / Bnorm)[Bnorm > Bmax] +Bz[Bnorm > Bmax] = Bmax * (Bz / Bnorm)[Bnorm > Bmax] +Bnorm[Bnorm > Bmax] = Bmax + +############################################################################### +# Visualization proper + +# Create a mayavi figure black on white +mlab.figure(bgcolor=(0., 0., 0.), fgcolor=(1., 1., 1.), size=(640, 480)) + +# Create a vector_field: a data source that we can slice and dice +field = mlab.pipeline.vector_field(X, Y, Z, Bx, By, Bz, + scalars=Bnorm, + name='B field') +# Plot the vectors +vectors = mlab.pipeline.vectors(field, + scale_factor=abs(X[0, 0, 0] - X[1, 1, 1]), + colormap='hot') +mlab.axes() + +# Mask 7 data points out of 8 +vectors.glyph.mask_input_points = True +vectors.glyph.mask_points.on_ratio = 8 + +mlab.pipeline.vector_cut_plane(field, scale_factor=.1, colormap='hot') + +# Add an iso_surface of the norm of the field +mlab.pipeline.iso_surface(mlab.pipeline.extract_vector_norm(field), + contours=[0.1*Bmax, 0.4*Bmax], + opacity=0.5, transparent=True) + +mlab.view(28, 84, 0.71) +mlab.savefig('visualize_field.png') diff --git a/packages/3d_plotting/examples/viz_volume_structure.png b/packages/3d_plotting/examples/viz_volume_structure.png new file mode 100644 index 0000000..c53da51 Binary files /dev/null and b/packages/3d_plotting/examples/viz_volume_structure.png differ diff --git a/packages/3d_plotting/examples/viz_volume_structure.py b/packages/3d_plotting/examples/viz_volume_structure.py new file mode 100644 index 0000000..f75603f --- /dev/null +++ b/packages/3d_plotting/examples/viz_volume_structure.py @@ -0,0 +1,28 @@ +""" +Use Mayavi to visualize the structure of a VolumeImg +""" + +from mayavi import mlab +import numpy as np + +x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j] + +data = x*x*0.5 + y*y + z*z*2.0 + +mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)) +mlab.clf() + +src = mlab.pipeline.scalar_field(x, y, z, data) + +mlab.pipeline.surface(src, opacity=0.4) + +src2 = mlab.pipeline.scalar_field(x[::9, ::9, ::9], + y[::9, ::9, ::9], + z[::9, ::9, ::9], + data[::9, ::9, ::9]) +mlab.pipeline.surface(mlab.pipeline.extract_edges(src2), color=(0, 0, 0)) +mlab.pipeline.glyph(src2, mode='cube', scale_factor=0.4, scale_mode='none') +mlab.savefig('viz_volume_structure.png') +mlab.show() + + diff --git a/packages/3d_plotting/examples/viz_volume_unstructure.png b/packages/3d_plotting/examples/viz_volume_unstructure.png new file mode 100644 index 0000000..e7c7cc1 Binary files /dev/null and b/packages/3d_plotting/examples/viz_volume_unstructure.png differ diff --git a/packages/3d_plotting/index.rst b/packages/3d_plotting/index.rst new file mode 100644 index 0000000..7be52bf --- /dev/null +++ b/packages/3d_plotting/index.rst @@ -0,0 +1,609 @@ +.. currentmodule:: mayavi + +.. _mayavi-label: + +====================== +Gráficos 3D con Mayavi +====================== + +.. only:: html + + .. image:: mayavi-logo.png + :align: right + +:Autor: Gaël Varoquaux + +.. tip:: + + `Mayavi `_ is an interactive + 3D plotting package. :ref:`matplotlib ` can also do + simple 3D plotting, but Mayavi relies on a more powerful engine ( + `VTK `_ ) and is more suited to displaying large + or complex data. + +.. contents:: Contenidos de los capítulos + :local: + :depth: 3 + + +Mlab: la interfaz de scripting +============================== + +El módulo :mod:`mayavi.mlab` proporciona funciones simples para hacer gráficas +aplicables a arrays numpy. Puedes probar las funciones usando IPython inicializando IPython con la +opción ``--gui=wx``. + +Funciones para gráficos 3D +-------------------------- + +Puntos +...... + +.. image:: examples/points3d.png + :align: right + :scale: 50 + +.. hint:: + + Points in 3D, represented with markers (or "glyphs") and optionaly + different sizes. + + +.. literalinclude:: examples/generate_figures.py + :start-after: ### begin points3d example + :end-before: ### end points3d example + +Líneas +...... + +.. image:: examples/plot3d.png + :align: right + :scale: 50 + +.. hint:: + + A line connecting points in 3D, with optional thickness and varying + color. + +.. literalinclude:: examples/generate_figures.py + :start-after: ### begin plot3d example + :end-before: ### end plot3d example + +Superficies de elevación +........................ + +.. image:: examples/surf.png + :align: right + :scale: 50 + +.. hint:: + + A surface given by its elevation, coded as a 2D array + +.. literalinclude:: examples/generate_figures.py + :start-after: ### begin surf example + :end-before: ### end surf example + +Mallas arbitrariamente irregulares +.................................. + +.. image:: examples/mesh.png + :align: right + :scale: 50 + +.. hint:: + + A surface mesh given by x, y, z positions of its node points + +.. literalinclude:: examples/generate_figures.py + :start-after: ### begin mesh example + :end-before: ### end mesh example + +.. note:: + + Una superficie se encuentra definida por puntos **connectados** formando triángulos o + polígonos. En `mlab.surf` y `mlab.mesh`, el layout de los arrays proporciona de + forma implícita las conexiones y la conectividad. Ver también + `mlab.triangular_mesh`. + +**Nuestros datos suelen ser algo más que puntos y valores: necesitan información de la +conectividad** + +.. _mayavi-voldata-label: + +Datos volumétricos +.................. + +.. image:: examples/contour3d.png + :align: right + :scale: 50 + +.. hint:: + + If your data is *dense* in 3D, it is more difficult to display. One + option is to take iso-contours of the data. + +.. literalinclude:: examples/generate_figures.py + :start-after: ### begin contour3d example + :end-before: ### end contour3d example + +.. image:: examples/viz_volume_structure.png + :align: right + :scale: 50 + +**Esta función funciona con un grid ortogonal regular:** El array de `valores` es un array +3D que proporciona la forma del grid. + +Figuras y decoraciones +---------------------- + +Gestión de figuras +.................. + +.. tip:: + + Aquí se puede ver una lista de funciones útiles para el control de la figura en uso + + +====================================== ============================================================== +Obtener la figura en uso: `mlab.gcf()` +-------------------------------------- -------------------------------------------------------------- +Limpiar la figura en uso: `mlab.clf()` +-------------------------------------- -------------------------------------------------------------- +Establecer la figura a usar: `mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5)` +-------------------------------------- -------------------------------------------------------------- +Guardar la figura a un fichero imagen: `mlab.savefig('foo.png', size=(300, 300))` +-------------------------------------- -------------------------------------------------------------- +Cambiar la vista: `mlab.view(azimuth=45, elevation=54, distance=1.)` +====================================== ============================================================== + +Cambiando las propiedades del gráfico +..................................... + +.. tip:: + + En general, muchas propiedades de los distintos objetos presentes en la figura + podrían cambiarse. Si las visualizaciones son creadas via funciones presentes en el módulo `mlab`, + la forma más sencilla de modificar estas visualizaciones sería modificando los argumentos de las + palabras clave (`keywords`) de cada función usada tal como se describe en la documentación (`docstrings`). + +.. topic:: **Ejemplo de documentación (`docstring`, lo dejamos en inglés puesto que es + como te aparecerá cuando lo veas en el código):** `mlab.mesh` + + Plots a surface using grid-spaced data supplied as 2D arrays. + + **Function signatures**:: + + mesh(x, y, z, ...) + + x, y, z are 2D arrays, all of the same shape, giving the positions of + the vertices of the surface. The connectivity between these points is + implied by the connectivity on the arrays. + + For simple structures (such as orthogonal grids) prefer the surf function, + as it will create more efficient data structures. + + **Keyword arguments:** + + :color: the color of the vtk object. Overides the colormap, + if any, when specified. This is specified as a + triplet of float ranging from 0 to 1, eg (1, 1, + 1) for white. + + :colormap: type of colormap to use. + + :extent: [xmin, xmax, ymin, ymax, zmin, zmax] + Default is the x, y, z arrays extents. Use + this to change the extent of the object + created. + + :figure: Figure to populate. + + :line_width: The with of the lines, if any used. Must be a float. + Default: 2.0 + + :mask: boolean mask array to suppress some data points. + + :mask_points: If supplied, only one out of 'mask_points' data point is + displayed. This option is usefull to reduce the number + of points displayed on large datasets Must be an integer + or None. + + :mode: the mode of the glyphs. Must be '2darrow' or '2dcircle' or + '2dcross' or '2ddash' or '2ddiamond' or '2dhooked_arrow' or + '2dsquare' or '2dthick_arrow' or '2dthick_cross' or + '2dtriangle' or '2dvertex' or 'arrow' or 'cone' or 'cube' or + 'cylinder' or 'point' or 'sphere'. Default: sphere + + :name: the name of the vtk object created. + + :representation: the representation type used for the surface. Must be + 'surface' or 'wireframe' or 'points' or 'mesh' or + 'fancymesh'. Default: surface + + :resolution: The resolution of the glyph created. For spheres, for + instance, this is the number of divisions along theta and + phi. Must be an integer. Default: 8 + + :scalars: optional scalar data. + + :scale_factor: scale factor of the glyphs used to represent + the vertices, in fancy_mesh mode. Must be a float. + Default: 0.05 + + :scale_mode: the scaling mode for the glyphs + ('vector', 'scalar', or 'none'). + + :transparent: make the opacity of the actor depend on the + scalar. + + :tube_radius: radius of the tubes used to represent the + lines, in mesh mode. If None, simple lines are used. + + :tube_sides: number of sides of the tubes used to + represent the lines. Must be an integer. Default: 6 + + :vmax: vmax is used to scale the colormap + If None, the max of the data will be used + + :vmin: vmin is used to scale the colormap + If None, the min of the data will be used + +.. image:: polar_mesh.png + :align: right + :scale: 90 + +**Ejemplo:** + +.. sourcecode:: ipython + + In [1]: import numpy as np + + In [2]: r, theta = np.mgrid[0:10, -np.pi:np.pi:10j] + + In [3]: x = r*np.cos(theta) + + In [4]: y = r*np.sin(theta) + + In [5]: z = np.sin(r)/r + + In [6]: from enthought.mayavi import mlab + + In [7]: mlab.mesh(x, y, z, colormap='gist_earth', extent=[0, 1, 0, 1, 0, 1]) + Out[7]: + + In [8]: mlab.mesh(x, y, z, extent=[0, 1, 0, 1, 0, 1], + ...: representation='wireframe', line_width=1, color=(0.5, 0.5, 0.5)) + Out[8]: + +Decoraciones +............ + +.. tip:: + + Se pueden añadir piezas extra en la figura para mostrar información de interés, + como una barra de colores o un título. + +.. sourcecode:: ipython + + In [9]: mlab.colorbar(Out[7], orientation='vertical') + Out[9]: + + In [10]: mlab.title('Malla polar') + Out[10]: + + In [11]: mlab.outline(Out[7]) + Out[11]: + + In [12]: mlab.axes(Out[7]) + Out[12]: + +.. image:: decorations.png + :align: center + :scale: 80 + +.. warning:: + + **extensión:** Si especificamos la extensión de un objeto gráfico, + `mlab.outline' y `mlab.axes` no tendrán esa extensión por defecto y habría que especificarla. + + + mlab_scripting_interface.rst + interaction.rst + + +Trabajo interactivo +=================== + +.. tip:: + + Probablemente, la manera más rápida y efectiva de crear visualizaciones bonitas con Mayavi sería + interactuando y modificando los distintos ajustes de forma interactiva. + +El "pipeline dialog" +-------------------- + +Pulsa en el botón 'Mayavi' que se encuentra en la figura para poder controlar las propiedades +de los objetos con la ayuda de ventanas de diálogos. + +.. image:: pipeline.png + :align: center + :scale: 80 + +* Establece el fondo de la figura en el nodo de las `Mayavi Scene` +* Establece el mapa de colores en el nodo `Colors and legends` +* Se pueden añadir módulos y/o filtras pulsando en el botón derecho del ratón + +El botón de grabación del script +-------------------------------- + +Para descubrir con qué códido podríamos modificar los cambios realizados de forma interactiva +podemos pulsar sobre el botón rojo cuando vayamos a realizar las modificaciones y se generarán +las correspondientes líneas de código. + +Slicing and dicing data: sources, modules and filters +===================================================== + +An example: inspecting magnetic fields +-------------------------------------- + +Suppose we are simulating the magnetic field generated by Helmholtz coils. +The :download:`examples/compute_field.py` script does this computation +and gives you a `B` array, that is (3 x n), where the first axis is the +direction of the field (Bx, By, Bz), and the second axis the index number +of the point. Arrays `X`, `Y` and `Z` give the positions of these data +points. + +.. topic:: **Excercise** + :class: green + + Visualize this field. Your goal is to make sure that the simulation + code is correct. + +.. image:: examples/visualize_field.png + :align: center + :scale: 80 + + +.. topic:: **Suggestions** + + * If you compute the norm of the vector field, you can apply an + isosurface to it. + + * using :func:`mayavi.mlab.quiver3d` you can plot vectors. You can + also use the 'masking' options (in the GUI) to make the plot a bit + less dense. + +Different views on data: sources and modules +--------------------------------------------- + +.. tip:: + + As we see above, it may be desirable to look at the same data in + different ways. + +Mayavi visualization are created by loading the data in a ``data +source`` and then displayed on the screen using ``modules``. + +This can be seen by looking at the "pipeline" view. By right-clicking on +the nodes of the pipeline, you can add new modules. + +.. topic:: Quiz + :class: green + + Why is it not possible to add a `VectorCutPlane` to the vectors + created by :func:`mayavi.mlab.quiver3d`? + +Different sources: scatters and fields +....................................... + +.. tip:: + + Data comes in different descriptions. + + * A 3D block of regularly-spaced value is structured: it is easy to know + how one measurement is related to another neighboring and how to + continuously interpolate between these. We can call such data a + **field**, borrowing from terminology used in physics, as it is + continuously defined in space. + + * A set of data points measured at random positions in a random order + gives rise to much more difficult and ill-posed interpolation + problems: the data structure itself does not tell us what are the + neighbors of a data point. We call such data a **scatter**. + +.. |unstructured| image:: examples/viz_volume_unstructure.png + :scale: 90 + +.. |structured| image:: examples/viz_volume_structure.png + :scale: 90 + +================================================= ========================================== +|structured| |unstructured| +================================================= ========================================== +Unstructured and unconnected data: a **scatter** Structured and connected data: a **field** + +mlab.points3d, mlab.quiver3d mlab.contour3d +================================================= ========================================== + +Data sources corresponding to **scatters** can be created with +:func:`mayavi.mlab.pipeline.scalar_scatter` or +:func:`mayavi.mlab.pipeline.vector_scatter`; **field** data sources can be +created with :func:`mlab.pipeline.scalar_field` or +:func:`mlab.pipeline.vector_field`. + +.. topic:: Exercice: + :class: green + + 1. Create a contour (for instance of the magnetic field norm) by + using one of those functions and adding the right *module* by + clicking on the GUI dialog. + + 2. Create the right source to apply a 'vector_cut_plane' and + reproduce the picture of the magnetic field shown previously. + + Note that one of the difficulties is providing the data in the right + form (number of arrays, shape) to the functions. This is often the + case with real-life data. + +.. seealso:: + + Sources are described in details in the `Mayavi manual + `_. + +Transforming data: filters +........................... + +If you create a *vector field*, you may want to visualize the +iso-contours of its magnitude. But the isosurface module can only be +applied to scalar data, and not vector data. We can use a *filter*, +``ExtractVectorNorm`` to add this scalar value to the vector field. + + Filters apply a transformation to data, and can be added between + sources and modules + +.. topic:: Excercice + :class: green + + Using the GUI, add the ExtractVectorNorm filter to display + iso-contours of the field magnitude. + +``mlab.pipeline``: the scripting layer +....................................... + +The ``mlab`` scripting layer builds pipelines for you. You can reproduce +these pipelines programmatically with the ``mlab.pipeline`` interface: +each step has a corresponding ``mlab.pipeline`` function (simply convert +the name of the step to lower-case underscore-separated: +ExtractVectorNorm gives extract_vector_norm). This function takes as an +argument the node that it applies to, as well as optional parameters, and +returns the new node. + +For example, iso-contours of the magnitude are coded as:: + + mlab.pipeline.iso_surface(mlab.pipeline.extract_vector_norm(field), + contours=[0.1*Bmax, 0.4*Bmax], + opacity=0.5) + +.. image:: examples/visualize_field.png + :align: left + :scale: 60 + :target: auto_examples/visualize_field.html + + +.. topic:: Excercice + :class: green + + Using the mlab.pipeline interface, generate a complete visualization, + with iso-contours of the field magnitude, and a vector cut plane. + + (click on the figure for a solution) + +|clear-floats| + +Animating the data +=================== + +.. tip:: + + To make movies, or interactive application, you may want to change the + data represented on a given visualization. + +If you have built a visualization, using the ``mlab`` plotting functions, +or the ``mlab.pipeline`` function, we can update the data by assigning +new values to the ``mlab_source`` attributes + +.. literalinclude:: examples/animate_data.py + :start-after: # Create some simple data + :end-before: # Start the event loop, if needed + +.. seealso:: + + More details in the `Mayavi documentation + `_ + +.. topic:: **Event loops** + + For the interaction with the user (for instance changing the view with + the mouse), Mayavi needs some time to process these events. The for + loop above prevents this. The Mayavi documentation details `a workaround + `_ + +Making interactive dialogs +=========================== + +It is very simple to make interactive dialogs with Mayavi using the +Traits library (see the dedicated chapter :ref:`traits`). + +A simple dialog +--------------- + +.. literalinclude:: examples/mlab_dialog.py + :start-after: import numpy as np + +.. tip:: + + Let us read a bit the code above (:download:`examples/mlab_dialog.py`). + + First, the ``curve`` function is used to compute the coordinate of the + curve we want to plot. + + Second, the dialog is defined by an object inheriting from HasTraits, + as it is done with :ref:`Traits `. The important point here + is that a Mayavi scene is added as a specific Traits attribute + (``Instance``). This is important for embedding it in the dialog. + The view of this dialog is defined by the ``view`` attribute of the + object. In the init of this object, we populate the 3D scene with a + curve. + + Finally, the ``configure_traits`` method creates the dialog and starts + the event loop. + +.. seealso:: + + There are a few things to be aware of when doing dialogs with Mayavi. + Please read the `Mayavi documentation + `_ + +Making it interactive +---------------------- + +We can combine the :ref:`Traits events handler ` +with the ``mlab_source`` to modify the visualization with the dialog. + +We will enable the user to vary the ``n_turns`` parameter in the definition +of the curve. For this, we need: + +* to define an ``n_turns`` attribute on our visualization object, so that + it can appear in the dialog. We use a ``Range`` type. + +* to wire modification of this attribute to a recomputation of the curve. + For this, we use the ``on_traits_change`` decorator. + +.. image:: examples/mlab_interactive_dialog.png + :scale: 70 + :align: right + +.. literalinclude:: examples/mlab_interactive_dialog.py + :start-after: # The class that contains the dialog + +.. tip:: + + Full code of the example: :download:`examples/mlab_dialog.py`. + + +Putting it together +=================== + +.. topic:: Exercise + :class: green + + Using the code from the magnetic field simulation, create a dialog + that enable to move the 2 coils: change their parameters. + + Hint: to define a dialog entry for a vector of dimension 3 :: + + direction = Array(float, value=(0, 0, 1), cols=3, shape=(3,)) + +You can look at the :ref:`example_coil_application.py` to see a +full-blown application for coil design in 270 lines of code. diff --git a/advanced/3d_plotting/interaction.rst b/packages/3d_plotting/interaction.rst similarity index 93% rename from advanced/3d_plotting/interaction.rst rename to packages/3d_plotting/interaction.rst index 582d9e3..a045f78 100644 --- a/advanced/3d_plotting/interaction.rst +++ b/packages/3d_plotting/interaction.rst @@ -7,7 +7,7 @@ Trabajo interactivo probablemente, modificar interactivamente los distintos settings. El "pipeline dialog" ----------------------- +-------------------- Pulsa sobre el botón 'Mayavi' en la escena para controlar las propiedades de los objetos mediante ventanas de diálogos. @@ -21,7 +21,7 @@ de los objetos mediante ventanas de diálogos. * Pulsa en el botón derecho del ratón sobre el nodo para añadir módulos o filtros El botón de grabación del script ------------------------------ +-------------------------------- Para conocer qué código hay que usar para programar los cambios, pulsa sobre el botón rojo a medida que vas modificando las propiedades y se irán diff --git a/advanced/3d_plotting/mayavi-logo.png b/packages/3d_plotting/mayavi-logo.png similarity index 100% rename from advanced/3d_plotting/mayavi-logo.png rename to packages/3d_plotting/mayavi-logo.png diff --git a/advanced/3d_plotting/mlab_scripting_interface.rst b/packages/3d_plotting/mlab_scripting_interface.rst similarity index 100% rename from advanced/3d_plotting/mlab_scripting_interface.rst rename to packages/3d_plotting/mlab_scripting_interface.rst diff --git a/advanced/3d_plotting/pipeline.png b/packages/3d_plotting/pipeline.png similarity index 100% rename from advanced/3d_plotting/pipeline.png rename to packages/3d_plotting/pipeline.png diff --git a/advanced/3d_plotting/polar_mesh.png b/packages/3d_plotting/polar_mesh.png similarity index 100% rename from advanced/3d_plotting/polar_mesh.png rename to packages/3d_plotting/polar_mesh.png diff --git a/advanced/3d_plotting/simple_example.png b/packages/3d_plotting/simple_example.png similarity index 100% rename from advanced/3d_plotting/simple_example.png rename to packages/3d_plotting/simple_example.png diff --git a/packages/index.rst b/packages/index.rst new file mode 100644 index 0000000..275f660 --- /dev/null +++ b/packages/index.rst @@ -0,0 +1,26 @@ +Paquetes y aplicaciones +======================= + +Esta parte de *Scipy lecture notes* está dedicado a diversos paquetes científicos útiles para diversas necesidades. + +|clear-floats| + +_____ + +|clear-floats| + + + +.. include:: ../includes/big_toc_css.rst + +.. include:: ../tune_toc.rst + +.. toctree:: + :maxdepth: 3 + + sympy.rst + scikit-image/index.rst + traits/index.rst + 3d_plotting/index.rst + scikit-learn/index.rst + diff --git a/packages/scikit-image/auto_examples/images/plot_boundaries_1.png b/packages/scikit-image/auto_examples/images/plot_boundaries_1.png new file mode 100644 index 0000000..4d9bbb6 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_boundaries_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_camera_1.png b/packages/scikit-image/auto_examples/images/plot_camera_1.png new file mode 100644 index 0000000..763009b Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_camera_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_camera_uint_1.png b/packages/scikit-image/auto_examples/images/plot_camera_uint_1.png new file mode 100644 index 0000000..ab170d9 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_camera_uint_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_check_1.png b/packages/scikit-image/auto_examples/images/plot_check_1.png new file mode 100644 index 0000000..dca3932 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_check_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_equalize_hist_1.png b/packages/scikit-image/auto_examples/images/plot_equalize_hist_1.png new file mode 100644 index 0000000..eb40271 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_equalize_hist_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_features_1.png b/packages/scikit-image/auto_examples/images/plot_features_1.png new file mode 100644 index 0000000..7440dc1 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_features_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_filter_coins_1.png b/packages/scikit-image/auto_examples/images/plot_filter_coins_1.png new file mode 100644 index 0000000..ea2cb81 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_filter_coins_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_labels_1.png b/packages/scikit-image/auto_examples/images/plot_labels_1.png new file mode 100644 index 0000000..2127020 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_labels_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_segmentations_1.png b/packages/scikit-image/auto_examples/images/plot_segmentations_1.png new file mode 100644 index 0000000..049a636 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_segmentations_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_sobel_1.png b/packages/scikit-image/auto_examples/images/plot_sobel_1.png new file mode 100644 index 0000000..d5e8d4c Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_sobel_1.png differ diff --git a/packages/scikit-image/auto_examples/images/plot_threshold_1.png b/packages/scikit-image/auto_examples/images/plot_threshold_1.png new file mode 100644 index 0000000..f357eaf Binary files /dev/null and b/packages/scikit-image/auto_examples/images/plot_threshold_1.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_boundaries.png b/packages/scikit-image/auto_examples/images/thumb/plot_boundaries.png new file mode 100644 index 0000000..a42a409 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_boundaries.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_camera.png b/packages/scikit-image/auto_examples/images/thumb/plot_camera.png new file mode 100644 index 0000000..621bbcb Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_camera.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_camera_uint.png b/packages/scikit-image/auto_examples/images/thumb/plot_camera_uint.png new file mode 100644 index 0000000..c47a149 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_camera_uint.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_check.png b/packages/scikit-image/auto_examples/images/thumb/plot_check.png new file mode 100644 index 0000000..cbb1e55 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_check.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_equalize_hist.png b/packages/scikit-image/auto_examples/images/thumb/plot_equalize_hist.png new file mode 100644 index 0000000..5c497a0 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_equalize_hist.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_features.png b/packages/scikit-image/auto_examples/images/thumb/plot_features.png new file mode 100644 index 0000000..49c7b83 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_features.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_filter_coins.png b/packages/scikit-image/auto_examples/images/thumb/plot_filter_coins.png new file mode 100644 index 0000000..e15b3ba Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_filter_coins.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_labels.png b/packages/scikit-image/auto_examples/images/thumb/plot_labels.png new file mode 100644 index 0000000..29b4dcf Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_labels.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_segmentations.png b/packages/scikit-image/auto_examples/images/thumb/plot_segmentations.png new file mode 100644 index 0000000..8723433 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_segmentations.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_sobel.png b/packages/scikit-image/auto_examples/images/thumb/plot_sobel.png new file mode 100644 index 0000000..da78742 Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_sobel.png differ diff --git a/packages/scikit-image/auto_examples/images/thumb/plot_threshold.png b/packages/scikit-image/auto_examples/images/thumb/plot_threshold.png new file mode 100644 index 0000000..f0f8fdb Binary files /dev/null and b/packages/scikit-image/auto_examples/images/thumb/plot_threshold.png differ diff --git a/packages/scikit-image/auto_examples/index.rst b/packages/scikit-image/auto_examples/index.rst new file mode 100644 index 0000000..9a586bc --- /dev/null +++ b/packages/scikit-image/auto_examples/index.rst @@ -0,0 +1,86 @@ + +.. raw:: html + + + +Examples +======== + +.. _examples-index: +.. figure:: ./images/thumb/plot_boundaries.png + :target: ./plot_boundaries.html + + :ref:`example_plot_boundaries.py` + +.. figure:: ./images/thumb/plot_camera.png + :target: ./plot_camera.html + + :ref:`example_plot_camera.py` + +.. figure:: ./images/thumb/plot_camera_uint.png + :target: ./plot_camera_uint.html + + :ref:`example_plot_camera_uint.py` + +.. figure:: ./images/thumb/plot_check.png + :target: ./plot_check.html + + :ref:`example_plot_check.py` + +.. figure:: ./images/thumb/plot_equalize_hist.png + :target: ./plot_equalize_hist.html + + :ref:`example_plot_equalize_hist.py` + +.. figure:: ./images/thumb/plot_features.png + :target: ./plot_features.html + + :ref:`example_plot_features.py` + +.. figure:: ./images/thumb/plot_filter_coins.png + :target: ./plot_filter_coins.html + + :ref:`example_plot_filter_coins.py` + +.. figure:: ./images/thumb/plot_labels.png + :target: ./plot_labels.html + + :ref:`example_plot_labels.py` + +.. figure:: ./images/thumb/plot_segmentations.png + :target: ./plot_segmentations.html + + :ref:`example_plot_segmentations.py` + +.. figure:: ./images/thumb/plot_sobel.png + :target: ./plot_sobel.html + + :ref:`example_plot_sobel.py` + +.. figure:: ./images/thumb/plot_threshold.png + :target: ./plot_threshold.html + + :ref:`example_plot_threshold.py` + + +.. raw:: html + +
    + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_boundaries.py b/packages/scikit-image/auto_examples/plot_boundaries.py new file mode 100644 index 0000000..69ba633 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_boundaries.py @@ -0,0 +1,24 @@ +""" +Visiualize segmentation contours on original grayscale image. +""" + +from skimage import data, segmentation, filter, color +import matplotlib.pyplot as plt + +coins = data.coins() +mask = coins > filter.threshold_otsu(coins) +clean_border = segmentation.clear_border(mask) + +coins_edges = segmentation.visualize_boundaries(color.gray2rgb(coins), + clean_border) + +plt.figure(figsize=(8, 3.5)) +plt.subplot(121) +plt.imshow(clean_border, cmap='gray') +plt.axis('off') +plt.subplot(122) +plt.imshow(coins_edges) +plt.axis('off') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_boundaries.rst b/packages/scikit-image/auto_examples/plot_boundaries.rst new file mode 100644 index 0000000..935009b --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_boundaries.rst @@ -0,0 +1,18 @@ + + +.. _example_plot_boundaries.py: + + +Visiualize segmentation contours on original grayscale image. + + + +.. image:: images/plot_boundaries_1.png + :align: center + + +**Python source code:** :download:`plot_boundaries.py ` + +.. literalinclude:: plot_boundaries.py + :lines: 4- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_camera.py b/packages/scikit-image/auto_examples/plot_camera.py new file mode 100644 index 0000000..0bac0ca --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_camera.py @@ -0,0 +1,16 @@ +""" +Load and display an image +""" + +import matplotlib.pyplot as plt +from skimage import data + +camera = data.camera() + + +plt.figure(figsize=(4, 4)) +plt.imshow(camera, cmap='gray', interpolation='nearest') +plt.axis('off') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_camera.rst b/packages/scikit-image/auto_examples/plot_camera.rst new file mode 100644 index 0000000..b0b5a90 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_camera.rst @@ -0,0 +1,18 @@ + + +.. _example_plot_camera.py: + + +Load and display an image + + + +.. image:: images/plot_camera_1.png + :align: center + + +**Python source code:** :download:`plot_camera.py ` + +.. literalinclude:: plot_camera.py + :lines: 4- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_camera_uint.py b/packages/scikit-image/auto_examples/plot_camera_uint.py new file mode 100644 index 0000000..1d35ba9 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_camera_uint.py @@ -0,0 +1,20 @@ +""" +An illustration of overflow problem arising when working with integers +""" + +import matplotlib.pyplot as plt +from skimage import data + +camera = data.camera() +camera_multiply = 3 * camera + +plt.figure(figsize=(8, 4)) +plt.subplot(121) +plt.imshow(camera, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(122) +plt.imshow(camera_multiply, cmap='gray', interpolation='nearest') +plt.axis('off') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_camera_uint.rst b/packages/scikit-image/auto_examples/plot_camera_uint.rst new file mode 100644 index 0000000..3893311 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_camera_uint.rst @@ -0,0 +1,18 @@ + + +.. _example_plot_camera_uint.py: + + +An illustration of overflow problem arising when working with integers + + + +.. image:: images/plot_camera_uint_1.png + :align: center + + +**Python source code:** :download:`plot_camera_uint.py ` + +.. literalinclude:: plot_camera_uint.py + :lines: 4- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_check.py b/packages/scikit-image/auto_examples/plot_check.py new file mode 100644 index 0000000..b2dd81d --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_check.py @@ -0,0 +1,14 @@ +""" +How to create an image with basic NumPy commands : ``np.zeros``, slicing... + +This examples show how to create a simple checkerboard. +""" + +import numpy as np +import matplotlib.pyplot as plt + +check = np.zeros((9, 9)) +check[::2, 1::2] = 1 +check[1::2, ::2] = 1 +plt.matshow(check, cmap='gray') +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_check.rst b/packages/scikit-image/auto_examples/plot_check.rst new file mode 100644 index 0000000..bfcc414 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_check.rst @@ -0,0 +1,20 @@ + + +.. _example_plot_check.py: + + +How to create an image with basic NumPy commands : ``np.zeros``, slicing... + +This examples show how to create a simple checkerboard. + + + +.. image:: images/plot_check_1.png + :align: center + + +**Python source code:** :download:`plot_check.py ` + +.. literalinclude:: plot_check.py + :lines: 6- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_equalize_hist.py b/packages/scikit-image/auto_examples/plot_equalize_hist.py new file mode 100644 index 0000000..3b7d9e3 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_equalize_hist.py @@ -0,0 +1,22 @@ +""" + +""" + +from skimage import data, exposure +import matplotlib.pyplot as plt + +camera = data.camera() +camera_equalized = exposure.equalize(camera) + + + +plt.figure(figsize=(7, 3)) + +plt.subplot(121) +plt.imshow(camera, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(122) +plt.imshow(camera_equalized, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_equalize_hist.rst b/packages/scikit-image/auto_examples/plot_equalize_hist.rst new file mode 100644 index 0000000..9cdd9f4 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_equalize_hist.rst @@ -0,0 +1,18 @@ + + +.. _example_plot_equalize_hist.py: + + + + + + +.. image:: images/plot_equalize_hist_1.png + :align: center + + +**Python source code:** :download:`plot_equalize_hist.py ` + +.. literalinclude:: plot_equalize_hist.py + :lines: 4- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_features.py b/packages/scikit-image/auto_examples/plot_features.py new file mode 100644 index 0000000..89191c6 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_features.py @@ -0,0 +1,20 @@ +from matplotlib import pyplot as plt + +from skimage import data +from skimage.feature import corner_harris, corner_subpix, corner_peaks +from skimage.transform import warp, AffineTransform + + +tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, + translation=(210, 50)) +image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350)) + +coords = corner_peaks(corner_harris(image), min_distance=5) +coords_subpix = corner_subpix(image, coords, window_size=13) + +plt.gray() +plt.imshow(image, interpolation='nearest') +plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15, mew=5) +plt.plot(coords[:, 1], coords[:, 0], '.b', markersize=7) +plt.axis('off') +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_features.rst b/packages/scikit-image/auto_examples/plot_features.rst new file mode 100644 index 0000000..208d304 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_features.rst @@ -0,0 +1,16 @@ + + +.. _example_plot_features.py: + + + + +.. image:: images/plot_features_1.png + :align: center + + +**Python source code:** :download:`plot_features.py ` + +.. literalinclude:: plot_features.py + :lines: 2- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_filter_coins.py b/packages/scikit-image/auto_examples/plot_filter_coins.py new file mode 100644 index 0000000..f5d6bf5 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_filter_coins.py @@ -0,0 +1,36 @@ +""" +This example compares several denoising filters available in scikit-image: +a Gaussian filter, a median filter, and total variation denoising. +""" + +import matplotlib.pyplot as plt +from skimage import data +from skimage import filter +from scipy import ndimage + +coins = data.coins() +gaussian_filter_coins = ndimage.gaussian_filter(coins, sigma=2) +med_filter_coins = filter.median_filter(coins) +tv_filter_coins = filter.tv_denoise(coins, weight=0.1) + +plt.figure(figsize=(16, 4)) +plt.subplot(141) +plt.imshow(coins[10:80, 300:370], cmap='gray', interpolation='nearest') +plt.axis('off') +plt.title('Image') +plt.subplot(142) +plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap='gray', + interpolation='nearest') +plt.axis('off') +plt.title('Gaussian filter') +plt.subplot(143) +plt.imshow(med_filter_coins[10:80, 300:370], cmap='gray', + interpolation='nearest') +plt.axis('off') +plt.title('Median filter') +plt.subplot(144) +plt.imshow(tv_filter_coins[10:80, 300:370], cmap='gray', + interpolation='nearest') +plt.axis('off') +plt.title('TV filter') +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_filter_coins.rst b/packages/scikit-image/auto_examples/plot_filter_coins.rst new file mode 100644 index 0000000..6058018 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_filter_coins.rst @@ -0,0 +1,19 @@ + + +.. _example_plot_filter_coins.py: + + +This example compares several denoising filters available in scikit-image: +a Gaussian filter, a median filter, and total variation denoising. + + + +.. image:: images/plot_filter_coins_1.png + :align: center + + +**Python source code:** :download:`plot_filter_coins.py ` + +.. literalinclude:: plot_filter_coins.py + :lines: 5- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_labels.py b/packages/scikit-image/auto_examples/plot_labels.py new file mode 100644 index 0000000..6a8fc70 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_labels.py @@ -0,0 +1,35 @@ +""" +This example shows how to label connected components of a binary image, using +the dedicated skimage.morphology.label function. +""" + +from skimage import morphology +import matplotlib.pyplot as plt +from scipy import ndimage +import numpy as np + +n = 12 +l = 256 +np.random.seed(1) +im = np.zeros((l, l)) +points = l*np.random.random((2, n**2)) +im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 +im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) +blobs = im > 0.7 * im.mean() + +all_labels = morphology.label(blobs) +blobs_labels = morphology.label(blobs, background=0) + +plt.figure(figsize=(9, 3.5)) +plt.subplot(131) +plt.imshow(blobs, cmap='gray') +plt.axis('off') +plt.subplot(132) +plt.imshow(all_labels) +plt.axis('off') +plt.subplot(133) +plt.imshow(blobs_labels) +plt.axis('off') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_labels.rst b/packages/scikit-image/auto_examples/plot_labels.rst new file mode 100644 index 0000000..a4474c3 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_labels.rst @@ -0,0 +1,19 @@ + + +.. _example_plot_labels.py: + + +This example shows how to label connected components of a binary image, using +the dedicated skimage.morphology.label function. + + + +.. image:: images/plot_labels_1.png + :align: center + + +**Python source code:** :download:`plot_labels.py ` + +.. literalinclude:: plot_labels.py + :lines: 5- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_segmentations.py b/packages/scikit-image/auto_examples/plot_segmentations.py new file mode 100644 index 0000000..abcdbcf --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_segmentations.py @@ -0,0 +1,54 @@ +""" +This example compares two segmentation methods in order to separate two +connected disks: the watershed algorithm, and the random walker algorithm. + +Both segmentation methods require seeds, that are pixels belonging +unambigusouly to a reagion. Here, local maxima of the distance map to the +background are used as seeds. +""" + +import numpy as np +from skimage.morphology import watershed, is_local_maximum +from skimage import morphology +from skimage.segmentation import random_walker +import matplotlib.pyplot as plt +from scipy import ndimage + +# Generate an initial image with two overlapping circles +x, y = np.indices((80, 80)) +x1, y1, x2, y2 = 28, 28, 44, 52 +r1, r2 = 16, 20 +mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2 +mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2 +image = np.logical_or(mask_circle1, mask_circle2) +# Now we want to separate the two objects in image +# Generate the markers as local maxima of the distance +# to the background +distance = ndimage.distance_transform_edt(image) +local_maxi = is_local_maximum(distance, image, np.ones((3, 3))) +markers = morphology.label(local_maxi) +labels_ws = watershed(-distance, markers, mask=image) + +markers[~image] = -1 +labels_rw = random_walker(image, markers) + +plt.figure(figsize=(12, 3.5)) +plt.subplot(141) +plt.imshow(image, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.title('image') +plt.subplot(142) +plt.imshow(-distance, interpolation='nearest') +plt.axis('off') +plt.title('distance map') +plt.subplot(143) +plt.imshow(labels_ws, cmap='spectral', interpolation='nearest') +plt.axis('off') +plt.title('watershed segmentation') +plt.subplot(144) +plt.imshow(labels_rw, cmap='spectral', interpolation='nearest') +plt.axis('off') +plt.title('random walker segmentation') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_segmentations.rst b/packages/scikit-image/auto_examples/plot_segmentations.rst new file mode 100644 index 0000000..d5285ce --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_segmentations.rst @@ -0,0 +1,23 @@ + + +.. _example_plot_segmentations.py: + + +This example compares two segmentation methods in order to separate two +connected disks: the watershed algorithm, and the random walker algorithm. + +Both segmentation methods require seeds, that are pixels belonging +unambigusouly to a reagion. Here, local maxima of the distance map to the +background are used as seeds. + + + +.. image:: images/plot_segmentations_1.png + :align: center + + +**Python source code:** :download:`plot_segmentations.py ` + +.. literalinclude:: plot_segmentations.py + :lines: 9- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_sobel.py b/packages/scikit-image/auto_examples/plot_sobel.py new file mode 100644 index 0000000..f3fea29 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_sobel.py @@ -0,0 +1,21 @@ +""" +This example illustrates the use of the horizontal Sobel filter, to compute +horizontal gradients. +""" + +from skimage import data, filter +import matplotlib.pyplot as plt + +text = data.text() +hsobel_text = filter.hsobel(text) + +plt.figure(figsize=(12, 3)) + +plt.subplot(121) +plt.imshow(text, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(122) +plt.imshow(hsobel_text, cmap='jet', interpolation='nearest') +plt.axis('off') +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_sobel.rst b/packages/scikit-image/auto_examples/plot_sobel.rst new file mode 100644 index 0000000..f28fc74 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_sobel.rst @@ -0,0 +1,19 @@ + + +.. _example_plot_sobel.py: + + +This example illustrates the use of the horizontal Sobel filter, to compute +horizontal gradients. + + + +.. image:: images/plot_sobel_1.png + :align: center + + +**Python source code:** :download:`plot_sobel.py ` + +.. literalinclude:: plot_sobel.py + :lines: 5- + \ No newline at end of file diff --git a/packages/scikit-image/auto_examples/plot_threshold.py b/packages/scikit-image/auto_examples/plot_threshold.py new file mode 100644 index 0000000..c630d5d --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_threshold.py @@ -0,0 +1,27 @@ +""" +This example illustrates automatic Otsu thresholding. +""" + +import matplotlib.pyplot as plt +from skimage import data +from skimage import filter +from skimage import exposure + +camera = data.camera() +val = filter.threshold_otsu(camera) + +hist, bins_center = exposure.histogram(camera) + +plt.figure(figsize=(9, 4)) +plt.subplot(131) +plt.imshow(camera, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(132) +plt.imshow(camera < val, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(133) +plt.plot(bins_center, hist, lw=2) +plt.axvline(val, color='k', ls='--') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/auto_examples/plot_threshold.rst b/packages/scikit-image/auto_examples/plot_threshold.rst new file mode 100644 index 0000000..5cff993 --- /dev/null +++ b/packages/scikit-image/auto_examples/plot_threshold.rst @@ -0,0 +1,18 @@ + + +.. _example_plot_threshold.py: + + +This example illustrates automatic Otsu thresholding. + + + +.. image:: images/plot_threshold_1.png + :align: center + + +**Python source code:** :download:`plot_threshold.py ` + +.. literalinclude:: plot_threshold.py + :lines: 4- + \ No newline at end of file diff --git a/packages/scikit-image/examples/plot_boundaries.py b/packages/scikit-image/examples/plot_boundaries.py new file mode 100644 index 0000000..69ba633 --- /dev/null +++ b/packages/scikit-image/examples/plot_boundaries.py @@ -0,0 +1,24 @@ +""" +Visiualize segmentation contours on original grayscale image. +""" + +from skimage import data, segmentation, filter, color +import matplotlib.pyplot as plt + +coins = data.coins() +mask = coins > filter.threshold_otsu(coins) +clean_border = segmentation.clear_border(mask) + +coins_edges = segmentation.visualize_boundaries(color.gray2rgb(coins), + clean_border) + +plt.figure(figsize=(8, 3.5)) +plt.subplot(121) +plt.imshow(clean_border, cmap='gray') +plt.axis('off') +plt.subplot(122) +plt.imshow(coins_edges) +plt.axis('off') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/examples/plot_camera.py b/packages/scikit-image/examples/plot_camera.py new file mode 100644 index 0000000..0bac0ca --- /dev/null +++ b/packages/scikit-image/examples/plot_camera.py @@ -0,0 +1,16 @@ +""" +Load and display an image +""" + +import matplotlib.pyplot as plt +from skimage import data + +camera = data.camera() + + +plt.figure(figsize=(4, 4)) +plt.imshow(camera, cmap='gray', interpolation='nearest') +plt.axis('off') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/examples/plot_camera_uint.py b/packages/scikit-image/examples/plot_camera_uint.py new file mode 100644 index 0000000..1d35ba9 --- /dev/null +++ b/packages/scikit-image/examples/plot_camera_uint.py @@ -0,0 +1,20 @@ +""" +An illustration of overflow problem arising when working with integers +""" + +import matplotlib.pyplot as plt +from skimage import data + +camera = data.camera() +camera_multiply = 3 * camera + +plt.figure(figsize=(8, 4)) +plt.subplot(121) +plt.imshow(camera, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(122) +plt.imshow(camera_multiply, cmap='gray', interpolation='nearest') +plt.axis('off') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/examples/plot_check.py b/packages/scikit-image/examples/plot_check.py new file mode 100644 index 0000000..b2dd81d --- /dev/null +++ b/packages/scikit-image/examples/plot_check.py @@ -0,0 +1,14 @@ +""" +How to create an image with basic NumPy commands : ``np.zeros``, slicing... + +This examples show how to create a simple checkerboard. +""" + +import numpy as np +import matplotlib.pyplot as plt + +check = np.zeros((9, 9)) +check[::2, 1::2] = 1 +check[1::2, ::2] = 1 +plt.matshow(check, cmap='gray') +plt.show() diff --git a/packages/scikit-image/examples/plot_equalize_hist.py b/packages/scikit-image/examples/plot_equalize_hist.py new file mode 100644 index 0000000..3b7d9e3 --- /dev/null +++ b/packages/scikit-image/examples/plot_equalize_hist.py @@ -0,0 +1,22 @@ +""" + +""" + +from skimage import data, exposure +import matplotlib.pyplot as plt + +camera = data.camera() +camera_equalized = exposure.equalize(camera) + + + +plt.figure(figsize=(7, 3)) + +plt.subplot(121) +plt.imshow(camera, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(122) +plt.imshow(camera_equalized, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/examples/plot_features.py b/packages/scikit-image/examples/plot_features.py new file mode 100644 index 0000000..89191c6 --- /dev/null +++ b/packages/scikit-image/examples/plot_features.py @@ -0,0 +1,20 @@ +from matplotlib import pyplot as plt + +from skimage import data +from skimage.feature import corner_harris, corner_subpix, corner_peaks +from skimage.transform import warp, AffineTransform + + +tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, + translation=(210, 50)) +image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350)) + +coords = corner_peaks(corner_harris(image), min_distance=5) +coords_subpix = corner_subpix(image, coords, window_size=13) + +plt.gray() +plt.imshow(image, interpolation='nearest') +plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15, mew=5) +plt.plot(coords[:, 1], coords[:, 0], '.b', markersize=7) +plt.axis('off') +plt.show() diff --git a/packages/scikit-image/examples/plot_filter_coins.py b/packages/scikit-image/examples/plot_filter_coins.py new file mode 100644 index 0000000..f5d6bf5 --- /dev/null +++ b/packages/scikit-image/examples/plot_filter_coins.py @@ -0,0 +1,36 @@ +""" +This example compares several denoising filters available in scikit-image: +a Gaussian filter, a median filter, and total variation denoising. +""" + +import matplotlib.pyplot as plt +from skimage import data +from skimage import filter +from scipy import ndimage + +coins = data.coins() +gaussian_filter_coins = ndimage.gaussian_filter(coins, sigma=2) +med_filter_coins = filter.median_filter(coins) +tv_filter_coins = filter.tv_denoise(coins, weight=0.1) + +plt.figure(figsize=(16, 4)) +plt.subplot(141) +plt.imshow(coins[10:80, 300:370], cmap='gray', interpolation='nearest') +plt.axis('off') +plt.title('Image') +plt.subplot(142) +plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap='gray', + interpolation='nearest') +plt.axis('off') +plt.title('Gaussian filter') +plt.subplot(143) +plt.imshow(med_filter_coins[10:80, 300:370], cmap='gray', + interpolation='nearest') +plt.axis('off') +plt.title('Median filter') +plt.subplot(144) +plt.imshow(tv_filter_coins[10:80, 300:370], cmap='gray', + interpolation='nearest') +plt.axis('off') +plt.title('TV filter') +plt.show() diff --git a/packages/scikit-image/examples/plot_labels.py b/packages/scikit-image/examples/plot_labels.py new file mode 100644 index 0000000..6a8fc70 --- /dev/null +++ b/packages/scikit-image/examples/plot_labels.py @@ -0,0 +1,35 @@ +""" +This example shows how to label connected components of a binary image, using +the dedicated skimage.morphology.label function. +""" + +from skimage import morphology +import matplotlib.pyplot as plt +from scipy import ndimage +import numpy as np + +n = 12 +l = 256 +np.random.seed(1) +im = np.zeros((l, l)) +points = l*np.random.random((2, n**2)) +im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 +im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) +blobs = im > 0.7 * im.mean() + +all_labels = morphology.label(blobs) +blobs_labels = morphology.label(blobs, background=0) + +plt.figure(figsize=(9, 3.5)) +plt.subplot(131) +plt.imshow(blobs, cmap='gray') +plt.axis('off') +plt.subplot(132) +plt.imshow(all_labels) +plt.axis('off') +plt.subplot(133) +plt.imshow(blobs_labels) +plt.axis('off') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/examples/plot_segmentations.py b/packages/scikit-image/examples/plot_segmentations.py new file mode 100644 index 0000000..abcdbcf --- /dev/null +++ b/packages/scikit-image/examples/plot_segmentations.py @@ -0,0 +1,54 @@ +""" +This example compares two segmentation methods in order to separate two +connected disks: the watershed algorithm, and the random walker algorithm. + +Both segmentation methods require seeds, that are pixels belonging +unambigusouly to a reagion. Here, local maxima of the distance map to the +background are used as seeds. +""" + +import numpy as np +from skimage.morphology import watershed, is_local_maximum +from skimage import morphology +from skimage.segmentation import random_walker +import matplotlib.pyplot as plt +from scipy import ndimage + +# Generate an initial image with two overlapping circles +x, y = np.indices((80, 80)) +x1, y1, x2, y2 = 28, 28, 44, 52 +r1, r2 = 16, 20 +mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2 +mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2 +image = np.logical_or(mask_circle1, mask_circle2) +# Now we want to separate the two objects in image +# Generate the markers as local maxima of the distance +# to the background +distance = ndimage.distance_transform_edt(image) +local_maxi = is_local_maximum(distance, image, np.ones((3, 3))) +markers = morphology.label(local_maxi) +labels_ws = watershed(-distance, markers, mask=image) + +markers[~image] = -1 +labels_rw = random_walker(image, markers) + +plt.figure(figsize=(12, 3.5)) +plt.subplot(141) +plt.imshow(image, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.title('image') +plt.subplot(142) +plt.imshow(-distance, interpolation='nearest') +plt.axis('off') +plt.title('distance map') +plt.subplot(143) +plt.imshow(labels_ws, cmap='spectral', interpolation='nearest') +plt.axis('off') +plt.title('watershed segmentation') +plt.subplot(144) +plt.imshow(labels_rw, cmap='spectral', interpolation='nearest') +plt.axis('off') +plt.title('random walker segmentation') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/examples/plot_sobel.py b/packages/scikit-image/examples/plot_sobel.py new file mode 100644 index 0000000..f3fea29 --- /dev/null +++ b/packages/scikit-image/examples/plot_sobel.py @@ -0,0 +1,21 @@ +""" +This example illustrates the use of the horizontal Sobel filter, to compute +horizontal gradients. +""" + +from skimage import data, filter +import matplotlib.pyplot as plt + +text = data.text() +hsobel_text = filter.hsobel(text) + +plt.figure(figsize=(12, 3)) + +plt.subplot(121) +plt.imshow(text, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(122) +plt.imshow(hsobel_text, cmap='jet', interpolation='nearest') +plt.axis('off') +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/examples/plot_threshold.py b/packages/scikit-image/examples/plot_threshold.py new file mode 100644 index 0000000..c630d5d --- /dev/null +++ b/packages/scikit-image/examples/plot_threshold.py @@ -0,0 +1,27 @@ +""" +This example illustrates automatic Otsu thresholding. +""" + +import matplotlib.pyplot as plt +from skimage import data +from skimage import filter +from skimage import exposure + +camera = data.camera() +val = filter.threshold_otsu(camera) + +hist, bins_center = exposure.histogram(camera) + +plt.figure(figsize=(9, 4)) +plt.subplot(131) +plt.imshow(camera, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(132) +plt.imshow(camera < val, cmap='gray', interpolation='nearest') +plt.axis('off') +plt.subplot(133) +plt.plot(bins_center, hist, lw=2) +plt.axvline(val, color='k', ls='--') + +plt.tight_layout() +plt.show() diff --git a/packages/scikit-image/index.rst b/packages/scikit-image/index.rst new file mode 100644 index 0000000..fa66129 --- /dev/null +++ b/packages/scikit-image/index.rst @@ -0,0 +1,723 @@ +.. _scikit_image: + +.. currentmodule:: skimage + +Scikit-image: image processing +============================== + +:author: Emmanuelle Gouillart + +`scikit-image `_ is a Python package dedicated +to image processing, and using natively NumPy arrays as image objects. +This chapter describes how to use ``scikit-image`` on various image +processing tasks, and insists on the link with other scientific Python +modules such as NumPy and SciPy. + +.. seealso:: + + For basic image manipulation, such as image cropping or simple + filtering, a large number of simple operations can be realized with + NumPy and SciPy only. See :ref:`basic_image`. + + Note that you should be familiar with the content of the previous + chapter before reading the current one, as basic operations such as + masking and labeling are a prerequisite. + +.. contents:: Chapters contents + :local: + :depth: 2 + + +Introduction and concepts +------------------------- + +Image = ``np.ndarray`` + +:image: + + ``np.ndarray`` + +:pixels: + + array values: ``a[2, 3]`` + +:channels: + + array dimensions + +:image encoding: + + ``dtype`` (``np.uint8``, ``np.uint16``, ``np.float``) + +:filters: + + functions (``numpy``, ``skimage``, ``scipy``) + + +:: + + >>> check = np.zeros((9, 9)) + >>> check[::2, 1::2] = 1 + >>> check[1::2, ::2] = 1 + >>> import matplotlib.pyplot as plt + >>> plt.imshow(check, cmap='gray', interpolation='nearest') + + +.. image:: auto_examples/images/plot_check_1.png + :scale: 60 + :target: auto_examples/plot_check.html + :align: center + +``scikit-image`` and the ``SciPy`` ecosystem +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Stable release : 0.8 (included in Canopy and Anaconda) + +0.7 release packaged in Ubuntu + +:: + + + >>> import skimage + >>> from skimage import data, filter # most functions are in subpackages  + +Most ``scikit-image`` functions take NumPy ``ndarrays`` as arguments :: + + >>> camera = data.camera() + >>> camera.dtype + dtype('uint8') + >>> filtered_camera = filter.median_filter(camera) + >>> type(filtered_camera) + + +Other Python packages are available for image processing and work with +NumPy arrays: + + * :mod:`scipy.ndimage` : for nd-arrays (no image magics). Basic + filtering, mathematical morphology, regions properties + + * `Mahotas `_ + +Also, powerful image processing libraries have Python bindings: + + * `OpenCV `_ (computer vision) + + * `ITK `_ (3D images and registration) + + * and many others + +(but they are less Pythonic and NumPy friendly). + +.. warning:: The ``Image`` wrapper class around ``np.ndarray`` + + ``skimage`` is meant to work "natively" with NumPy arrays, and most + skimage functions return NumPy arrays. Some functions of the ``data`` + submodule return instead an instance of the ``Image`` class, which is + just a wrapper class around NumPy ``ndarray``. + + >>> camera = data.camera() + >>> camera + Image([[156, 157, 160, ..., 152, 152, 152], + [156, 157, 159, ..., 152, 152, 152], + [158, 157, 156, ..., 152, 152, 152], + ..., + [121, 123, 126, ..., 121, 113, 111], + [121, 123, 126, ..., 121, 113, 111], + [121, 123, 126, ..., 121, 113, 111]], dtype=uint8) + >>> isinstance(camera, np.ndarray) + True + + You should just consider that an ``Image`` instance is a regular + ``ndarray``. + +What's to be found in scikit-image +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* Website: http://scikit-image.org/ + +* Gallery of examples (as in + `matplotlib `_ or + `scikit-learn `_): + http://scikit-image.org/docs/dev/auto_examples/ + +Different kinds of functions, from boilerplate utility functions to +high-level recent algorithms. + + * Filters: functions transforming images into other images. + + * NumPy machinery + + * Common filtering algorithms + + * Data reduction functions: computation of image histogram, position of + local maxima, of corners, etc. + + * Other actions: I/O, visualization, etc. + +Input/output, data types and colorspaces +---------------------------------------- + +I/O: :mod:`skimage.io` :: + + >>> from skimage import io + + +Reading from files: :func:`skimage.io.imread` :: + + >>> filename = os.path.join(skimage.data_dir, 'camera.png') + >>> camera = io.imread(filename) + +.. image:: auto_examples/images/plot_camera_1.png + :width: 50% + :target: auto_examples/plot_camera.html + :align: center + +Works with all data formats supported by the Python Imaging Library +(or any other I/O plugin provided to ``imread`` with the ``plugin`` +keyword argument). + +Also works with URL image paths:: + + >>> logo = io.imread('http://scikit-image.org/_static/img/logo.png') + +Saving to files:: + + >>> io.imsave('local_logo.png', logo) + +(``imsave`` also uses an external plugin such as PIL) + +I/O also available for videos if external backends such as GStreamer +or OpenCV are present +:: + + >>> movie = io.video.Video('video_file.avi') + >>> image_array = movie.get_index_frame(10) + +Data types +~~~~~~~~~~ + + +.. image:: auto_examples/images/plot_camera_uint_1.png + :align: right + :width: 50% + :target: auto_examples/plot_camera_uint.html + +Image ndarrays can be represented either by integers (signed or unsigned) or +floats. + +Careful with overflows with integer data types + +:: + + >>> camera = data.camera() + >>> camera.dtype + dtype('uint8') + >>> camera_multiply = 3 * camera + +Different integer sizes are possible: 8-, 16- or 32-bytes, signed or +unsigned. + +.. warning:: + + An important (if questionable) ``skimage`` **convention**: float images + are supposed to lie in [-1, 1] (in order to have comparable contrast for + all float images) :: + + >>> camera_float = util.img_as_float(camera) + >>> camera.max(), camera_float.max() + (Image(255, dtype=uint8), 1.0) + +Some image processing routines need to work with float arrays, and may +hence output an array with a different type and the data range from the +input array :: + + >>> from skimage import filter + >>> camera_sobel = filter.sobel(camera) + >>> camera_sobel.max() + 0.8365106670670005 + + +Utility functions are provided in :mod:`skimage.util` to convert both the +dtype and the data range, following skimage's conventions: +``util.img_as_float``, ``util.img_as_ubyte``, etc. + +See the `user guide +`_ for +more details. + +Colorspaces +~~~~~~~~~~~ + +Color images are of shape (N, M, 3) or (N, M, 4) (when an alpha channel +encodes transparency) :: + + >>> lena = data.lena() + >>> lena.shape + (512, 512, 3) + + +Routines converting between different colorspaces (RGB, HSV, LAB etc.) +are available in :mod:`skimage.color` : ``color.rgb2hsv``, ``color.lab2rgb``, +etc. Check the docstring for the expected dtype (and data range) of input +images. + +.. topic:: 3D images + + Some functions of ``skimage`` can take 3D images as input arguments. + Check the docstring to know if a function can be used on 3D images + (for example MRI or CT images). + + + +.. topic:: Exercise + :class: green + + Open a color image on your disk as a NumPy array. + + Find a skimage function computing the histogram of an image and + plot the histogram of each color channel + + Convert the image to grayscale and plot its histogram. + +Image preprocessing / enhancement +--------------------------------- + +Goals: denoising, feature (edges) extraction, ... + + +Local filters +~~~~~~~~~~~~~ + +Local filters replace the value of pixels by a function of the +values of neighboring pixels. The function can be linear or non-linear. + +Neighbourhood: square (choose size), disk, or more complicated +*structuring element*. + +.. image:: ../../advanced/image_processing/kernels.png + :width: 80% + :align: center + +Example : horizontal Sobel filter :: + + >>> text = data.text() + >>> hsobel_text = filter.hsobel(text) + + +Uses the following linear kernel for computing horizontal gradients:: + + 1 2 1 + 0 0 0 + -1 -2 -1 + +.. image:: auto_examples/images/plot_sobel_1.png + :width: 70% + :target: auto_examples/plot_sobel.html + :align: center + + +Non-local filters +~~~~~~~~~~~~~~~~~ + +Non-local filters use a large region of the image (or all the image) to +transform the value of one pixel:: + + >>> camera = data.camera() + >>> camera_equalized = exposure.equalize_hist(camera) + >>> # Rk: use instead exposure.equalize in skimage 0.7 + +Enhances contrast in large almost uniform regions. + +.. image:: auto_examples/images/plot_equalize_hist_1.png + :width: 70% + :target: auto_examples/plot_equalize_hist.html + :align: center + +Mathematical morphology +~~~~~~~~~~~~~~~~~~~~~~~ + +See http://en.wikipedia.org/wiki/Mathematical_morphology + +Probe an image with a simple shape (a **structuring element**), and +modify this image according to how the shape locally fits or misses the +image. + +Default structuring element: 4-connectivity of a pixel :: + + >>> from skimage import morphology + >>> morphology.diamond(1) + array([[0, 1, 0], + [1, 1, 1], + [0, 1, 0]], dtype=uint8) + + +.. image:: ../../advanced/image_processing/diamond_kernel.png + :align: center + +**Erosion** = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring element.:: + + >>> a = np.zeros((7,7), dtype=np.int) + >>> a[1:6, 2:5] = 1 + >>> a + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0]]) + >>> morphology.binary_erosion(a, morphology.diamond(1)).astype(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + >>> #Erosion removes objects smaller than the structure + >>> morphology.binary_erosion(a, morphology.diamond(2)).astype(np.uint8) + array([[0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) + +**Dilation**: maximum filter:: + + >>> a = np.zeros((5, 5)) + >>> a[2, 2] = 1 + >>> a + array([[ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 1., 0., 0.], + [ 0., 0., 0., 0., 0.], + [ 0., 0., 0., 0., 0.]]) + >>> morphology.binary_dilation(a, morphology.diamond(1)).astype(np.uint8) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + +**Opening**: erosion + dilation:: + + >>> a = np.zeros((5,5), dtype=np.int) + >>> a[1:4, 1:4] = 1; a[4, 4] = 1 + >>> a + array([[0, 0, 0, 0, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 1]]) + >>> morphology.binary_opening(a, morphology.diamond(1)).astype(np.uint8) + array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=uint8) + +Opening removes small objects and smoothes corners. + +.. topic:: Grayscale mathematical morphology + + Mathematical morphology operations are also available for + (non-binary) grayscale images (int or float type). Erosion and dilation + correspond to minimum (resp. maximum) filters. + +Higher-level mathematical morphology are available: tophat, +skeletonization, etc. + +.. seealso:: + + Basic mathematical morphology is also implemented in + :mod:`scipy.ndimage.morphology`. The ``scipy.ndimage`` implementation + works on arbitrary-dimensional arrays. + +--------------------- + +.. topic:: Example of filters comparison: image denoising + + :: + + >>> from skimage import filter + >>> coins = data.coins() + >>> coins_zoom = coins[10:80, 300:370] + >>> median_coins = filter.median_filter(coins_zoom) + >>> tv_coins = filter.tv_denoise(coins_zoom, weight=0.1) + >>> from scipy import ndimage + >>> gaussian_coins = ndimage.gaussian_filter(coins, sigma=2) + + .. image:: auto_examples/images/plot_filter_coins_1.png + :width: 99% + :target: auto_examples/plot_filter_coins.html + +Image segmentation +------------------ + +Segmentation = filter that maps an image onto an image of labels +corresponding to different regions. + +Binary segmentation: foreground + background +............................................. + +Histogram-based method: **Otsu thresholding** +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. tip:: + + The `Otsu method `_ is a + simple heuristic to find a threshold to separate the foreground from + the background. + +:: + + from skimage import data + from skimage import filter + camera = data.camera() + val = filter.threshold_otsu(camera) + mask = camera < val + +.. image:: auto_examples/images/plot_threshold_1.png + :width: 70% + :target: auto_examples/plot_threshold.html + :align: center + +Labeling connected components of a discrete image +.................................................. + +.. tip:: + + Once you have separated foreground objects, it is use to separate them + from each other. For this, we can assign a different integer labels to + each one. + +Synthetic data:: + + >>> n = 20 + >>> l = 256 + >>> im = np.zeros((l, l)) + >>> points = l*np.random.random((2, n**2)) + >>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 + >>> im = ndimage.gaussian_filter(im, sigma=l/(4.*n)) + >>> blobs = im > im.mean() + +Label all connected components:: + + >>> all_labels = morphology.label(blobs) + +Label only foreground connected components:: + + >>> blobs_labels = morphology.label(blobs, background=0) + + +.. image:: auto_examples/images/plot_labels_1.png + :width: 90% + :target: auto_examples/plot_labels.html + :align: center + +.. seealso:: + + :func:`scipy.ndimage.find_objects` is useful to return slices on + object in an image. + +Marker based methods +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you have markers inside a set of regions, you can use these to segment +the regions. + +*Watershed* segmentation +.......................... + +The Watershed (:func:`skimage.morphology.watershed`) is a region-growing +approach that fills "bassins" in the image :: + + >>> from skimage.morphology import watershed, is_local_maximum + >>> + >>> # Generate an initial image with two overlapping circles + >>> x, y = np.indices((80, 80)) + >>> x1, y1, x2, y2 = 28, 28, 44, 52 + >>> r1, r2 = 16, 20 + >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2 + >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2 + >>> image = np.logical_or(mask_circle1, mask_circle2) + >>> # Now we want to separate the two objects in image + >>> # Generate the markers as local maxima of the distance + >>> # to the background + >>> from scipy import ndimage + >>> distance = ndimage.distance_transform_edt(image) + >>> local_maxi = is_local_maximum(distance, image, np.ones((3, 3))) + >>> markers = morphology.label(local_maxi) + >>> labels_ws = watershed(-distance, markers, mask=image) + +*Random walker* segmentation +.............................. + +The random walker algorithm (:func:`skimage.segmentation.random_walker`) +is similar to the Watershed, but with a more "probabilistic" appraoch. It +is based on the idea of the diffusion of labels in the image:: + + >>> # Transform markers image so that 0-valued pixels are to + >>> # be labelled, and -1-valued pixels represent background + >>> markers[~image] = -1 + >>> labels_rw = segmentation.random_walker(image, markers) + +.. image:: auto_examples/images/plot_segmentations_1.png + :width: 90% + :target: auto_examples/plot_segmentations.html + :align: center + + +.. topic:: Postprocessing label images + + ``skimage`` provides several utility functions that can be used on + label images (ie images where different discrete values identify + different regions). Functions names are often self-explaining: + :func:`skimage.segmentation.clear_border`, + :func:`skimage.segmentation.relabel_from_one`, + :func:`skimage.morphology.remove_small_objects`, etc. + + +.. topic:: Exercise + :class: green + + * Load the ``coins`` image from the ``data`` submodule. + + * Separate the coins from the background by testing several + segmentation methods: Otsu thresholding, adaptive thresholding, and + watershed or random walker segmentation. + + * If necessary, use a postprocessing function to improve the coins / + background segmentation. + + +Measuring regions' properties +----------------------------- + +:: + + >>> from skimage import measure + >>> measure.regionprops? + +Example: compute the size and perimeter of the two segmented regions:: + + >>> measure.regionprops(labels_rw, properties=['Area', 'Perimeter']) + [{'Perimeter': 117.25483399593905, 'Area': 770.0, 'Label': 1}, + {'Perimeter': 149.1543289325507, 'Area': 1168.0, 'Label': 2}] + +.. seealso:: + + for some properties, functions are available as well in + :mod:`scipy.ndimage.measurements` with a different API (a list is + returned). + + +.. topic:: Exercise (cont'd) + :class: green + + * Use the binary image of the coins and background from the previous + exercise. + + * Compute an image of labels for the different coins. + + * Compute the size and eccentricity of all coins. + +Data visualization and interaction +---------------------------------- + +Meaningful visualizations are useful when testing a given processing +pipeline. + +Some image processing operations:: + + >>> coins = data.coins() + >>> mask = coins > filter.threshold_otsu(coins) + >>> clean_border = segmentation.clear_border(mask) + +Visualize binary result:: + + >>> plt.figure() + >>> plt.imshow(clean_border, cmap='gray') + +Visualize contour :: + + >>> plt.figure() + >>> plt.imshow(coins, cmap='gray') + >>> plt.contour(clean_border, [0.5]) + +Use ``skimage`` dedicated utility function:: + + >>> # In >= 0.8 + >>> coins_edges = segmentation.mark_boundaries(coins, clean_border) + >>> # In 0.7 + >>> # segmentation.visualize_boundaries(color.gray2rgb(coins), clean_border) + >>> plt.imshow(coins_edges) + +.. image:: auto_examples/images/plot_boundaries_1.png + :width: 90% + :target: auto_examples/plot_boundaries.html + :align: center + +**The (experimental) scikit-image viewer** + +``skimage.viewer`` = matplotlib-based canvas for displaying images + +experimental Qt-based GUI-toolkit :: + + >>> from skimage import viewer + >>> new_viewer = viewer.ImageViewer(coins) + >>> new_viewer.show() + +Useful for displaying pixel values. + +For more interaction, plugins can be added to the viewer:: + + >>> new_viewer = viewer.ImageViewer(coins) + >>> from skimage.viewer.plugins import lineprofile + >>> new_viewer += lineprofile.LineProfile() + >>> new_viewer.show() + +.. image:: viewer.png + :align: center + +Feature extraction for computer vision +-------------------------------------- + +Geometric or textural descriptor can be extracted from images in order to + +* classify parts of the image (e.g. sky vs. buildings) + +* match parts of different images (e.g. for object detection) + +* and many other applications of + `Computer Vision `_ + +:: + + >>> from skimage import feature + +Example: detecting corners using Harris detector :: + + from skimage.feature import corner_harris, corner_subpix, corner_peaks + from skimage.transform import warp, AffineTransform + + + tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, + translation=(210, 50)) + image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350)) + + coords = corner_peaks(corner_harris(image), min_distance=5) + coords_subpix = corner_subpix(image, coords, window_size=13) + +.. image:: auto_examples/images/plot_features_1.png + :width: 90% + :target: auto_examples/plot_features.html + :align: center + +(this example is taken from +http://scikit-image.org/docs/dev/auto_examples/plot_corner.html) + +Points of interest such as corners can then be used to match objects in +different images, as described in +http://scikit-image.org/docs/dev/auto_examples/plot_matching.html diff --git a/packages/scikit-image/viewer.png b/packages/scikit-image/viewer.png new file mode 100644 index 0000000..189a95a Binary files /dev/null and b/packages/scikit-image/viewer.png differ diff --git a/advanced/scikit-learn/cluster_iris_truth.png b/packages/scikit-learn/cluster_iris_truth.png similarity index 100% rename from advanced/scikit-learn/cluster_iris_truth.png rename to packages/scikit-learn/cluster_iris_truth.png diff --git a/advanced/scikit-learn/digits_first_image.png b/packages/scikit-learn/digits_first_image.png similarity index 100% rename from advanced/scikit-learn/digits_first_image.png rename to packages/scikit-learn/digits_first_image.png diff --git a/advanced/scikit-learn/digits_svm.py b/packages/scikit-learn/digits_svm.py similarity index 100% rename from advanced/scikit-learn/digits_svm.py rename to packages/scikit-learn/digits_svm.py diff --git a/advanced/scikit-learn/faces.png b/packages/scikit-learn/faces.png similarity index 100% rename from advanced/scikit-learn/faces.png rename to packages/scikit-learn/faces.png diff --git a/advanced/scikit-learn/faces.py b/packages/scikit-learn/faces.py similarity index 93% rename from advanced/scikit-learn/faces.py rename to packages/scikit-learn/faces.py index 8f5839a..8565be7 100644 --- a/advanced/scikit-learn/faces.py +++ b/packages/scikit-learn/faces.py @@ -7,7 +7,7 @@ """ import numpy as np -from sklearn import cross_val, datasets, decomposition, svm +from sklearn import cross_validation, datasets, decomposition, svm # .. # .. load data .. diff --git a/advanced/scikit-learn/images/Virginia_Iris.png b/packages/scikit-learn/images/Virginia_Iris.png similarity index 100% rename from advanced/scikit-learn/images/Virginia_Iris.png rename to packages/scikit-learn/images/Virginia_Iris.png diff --git a/advanced/scikit-learn/index.rst b/packages/scikit-learn/index.rst similarity index 100% rename from advanced/scikit-learn/index.rst rename to packages/scikit-learn/index.rst diff --git a/advanced/scikit-learn/iris_knn.png b/packages/scikit-learn/iris_knn.png similarity index 100% rename from advanced/scikit-learn/iris_knn.png rename to packages/scikit-learn/iris_knn.png diff --git a/advanced/scikit-learn/iris_svm.png b/packages/scikit-learn/iris_svm.png similarity index 100% rename from advanced/scikit-learn/iris_svm.png rename to packages/scikit-learn/iris_svm.png diff --git a/advanced/scikit-learn/k_means_iris_3.png b/packages/scikit-learn/k_means_iris_3.png similarity index 100% rename from advanced/scikit-learn/k_means_iris_3.png rename to packages/scikit-learn/k_means_iris_3.png diff --git a/advanced/scikit-learn/k_means_iris_8.png b/packages/scikit-learn/k_means_iris_8.png similarity index 100% rename from advanced/scikit-learn/k_means_iris_8.png rename to packages/scikit-learn/k_means_iris_8.png diff --git a/advanced/scikit-learn/lena.png b/packages/scikit-learn/lena.png similarity index 100% rename from advanced/scikit-learn/lena.png rename to packages/scikit-learn/lena.png diff --git a/advanced/scikit-learn/lena_compressed.png b/packages/scikit-learn/lena_compressed.png similarity index 100% rename from advanced/scikit-learn/lena_compressed.png rename to packages/scikit-learn/lena_compressed.png diff --git a/advanced/scikit-learn/lena_regular.png b/packages/scikit-learn/lena_regular.png similarity index 100% rename from advanced/scikit-learn/lena_regular.png rename to packages/scikit-learn/lena_regular.png diff --git a/advanced/scikit-learn/pca_3d_aligned.jpg b/packages/scikit-learn/pca_3d_aligned.jpg similarity index 100% rename from advanced/scikit-learn/pca_3d_aligned.jpg rename to packages/scikit-learn/pca_3d_aligned.jpg diff --git a/advanced/scikit-learn/pca_3d_axis.jpg b/packages/scikit-learn/pca_3d_axis.jpg similarity index 100% rename from advanced/scikit-learn/pca_3d_axis.jpg rename to packages/scikit-learn/pca_3d_axis.jpg diff --git a/advanced/scikit-learn/pca_digits_spectrum.png b/packages/scikit-learn/pca_digits_spectrum.png similarity index 100% rename from advanced/scikit-learn/pca_digits_spectrum.png rename to packages/scikit-learn/pca_digits_spectrum.png diff --git a/advanced/scikit-learn/pca_iris.png b/packages/scikit-learn/pca_iris.png similarity index 100% rename from advanced/scikit-learn/pca_iris.png rename to packages/scikit-learn/pca_iris.png diff --git a/advanced/scikit-learn/plot_compare_methods_1.png b/packages/scikit-learn/plot_compare_methods_1.png similarity index 100% rename from advanced/scikit-learn/plot_compare_methods_1.png rename to packages/scikit-learn/plot_compare_methods_1.png diff --git a/advanced/scikit-learn/plot_faces_decomposition_2.png b/packages/scikit-learn/plot_faces_decomposition_2.png similarity index 100% rename from advanced/scikit-learn/plot_faces_decomposition_2.png rename to packages/scikit-learn/plot_faces_decomposition_2.png diff --git a/advanced/scikit-learn/scikit-learn-logo.png b/packages/scikit-learn/scikit-learn-logo.png similarity index 100% rename from advanced/scikit-learn/scikit-learn-logo.png rename to packages/scikit-learn/scikit-learn-logo.png diff --git a/advanced/scikit-learn/show_digit.py b/packages/scikit-learn/show_digit.py similarity index 100% rename from advanced/scikit-learn/show_digit.py rename to packages/scikit-learn/show_digit.py diff --git a/advanced/scikit-learn/show_ica.py b/packages/scikit-learn/show_ica.py similarity index 100% rename from advanced/scikit-learn/show_ica.py rename to packages/scikit-learn/show_ica.py diff --git a/advanced/scikit-learn/show_pca.py b/packages/scikit-learn/show_pca.py similarity index 100% rename from advanced/scikit-learn/show_pca.py rename to packages/scikit-learn/show_pca.py diff --git a/advanced/scikit-learn/svm_kernel_linear.png b/packages/scikit-learn/svm_kernel_linear.png similarity index 100% rename from advanced/scikit-learn/svm_kernel_linear.png rename to packages/scikit-learn/svm_kernel_linear.png diff --git a/advanced/scikit-learn/svm_kernel_poly.png b/packages/scikit-learn/svm_kernel_poly.png similarity index 100% rename from advanced/scikit-learn/svm_kernel_poly.png rename to packages/scikit-learn/svm_kernel_poly.png diff --git a/advanced/scikit-learn/svm_kernel_rbf.png b/packages/scikit-learn/svm_kernel_rbf.png similarity index 100% rename from advanced/scikit-learn/svm_kernel_rbf.png rename to packages/scikit-learn/svm_kernel_rbf.png diff --git a/advanced/scikit-learn/svm_margin.png b/packages/scikit-learn/svm_margin.png similarity index 100% rename from advanced/scikit-learn/svm_margin.png rename to packages/scikit-learn/svm_margin.png diff --git a/advanced/scikit-learn/svm_margin_no_penalty.png b/packages/scikit-learn/svm_margin_no_penalty.png similarity index 100% rename from advanced/scikit-learn/svm_margin_no_penalty.png rename to packages/scikit-learn/svm_margin_no_penalty.png diff --git a/advanced/sympy.rst b/packages/sympy.rst similarity index 50% rename from advanced/sympy.rst rename to packages/sympy.rst index c31e34c..90d5851 100644 --- a/advanced/sympy.rst +++ b/packages/sympy.rst @@ -8,37 +8,29 @@ Sympy : Matemáticas simbólicas en Python ====================================== -:autor: Fabian Pedregosa +:Autor: Fabian Pedregosa .. topic:: Objetivos - 1. Evaluar expresiones con precisión arbitraria. - 2. Ejecutar manipulaciones algebráicas en expresiones simbólicas. - 3. Ejecutar tareas básicas de cálculo (límites, diferenciación e integración) - con expresiones simbólicas. - 4. Resolver ecuaciones polinómicas y transcendentales. - 5. Resolver algunas ecuaciones diferenciales. + 1. Evaluar expresiones con precisión arbitraria. + 2. Ejecutar manipulaciones algebráicas en expresiones simbólicas. + 3. Ejecutar tareas básicas de cálculo (límites, diferenciación e integración) con expresiones simbólicas. + 4. Resolver ecuaciones polinómicas y transcendentales. + 5. Resolver algunas ecuaciones diferenciales. .. role:: input(strong) -**¿Qué es SymPy?** SymPy es una biblioteca Python para matemática simbólica. Su -propósito es convertirse en un completo sistema de álgebra computacional que pueda -competir directamente con alternativas comerciales (Mathematica, Maple) manteniendo, -a la vez, el código tan simple como sea posible para hacerlo extensible de manera fácil -e integral. SymPy está escrito completamente en Python y no necesita usar otras bibliotecas. +**Qué es SymPy?** SymPy es una biblioteca Python para matemática simbólica. Su propósito es convertirse en un completo sistema de álgebra computacional que pueda competir directamente con alternativas comerciales (Mathematica, Maple) manteniendo, a la vez, el código tan simple como sea posible para hacerlo extensible de manera fácil e integral. SymPy está escrito completamente en Python y no necesita usar otras bibliotecas. -La documentación y los paquetes Sympy para instalarlo pueden encontrarse en: -http://sympy.org/ +La documentación y los paquetes Sympy para instalarlo pueden encontrarse en: http://sympy.org/ -.. contents:: Contenidos de los capítulos +.. contents:: Contenido :local: :depth: 4 - Primeros pasos con SymPy ======================== - Usando SymPy como una calculadora --------------------------------- @@ -46,41 +38,43 @@ SymPy define tres tipos numéricos: Real, Racional y Entero. La clase Racional representa un número racional como una pareja de números Enteros: el numerador y el denominador, de esta forma Rational(1,2) -representa 1/2, Rational(5,2) 5/2, etcétera:: +representa 1/2, Rational(5,2) 5/2, etcétera + +.. code-block:: python - >>> from sympy import * - >>> a = Rational(1,2) + >>> from sympy import * + >>> a = Rational(1,2) - >>> a - 1/2 + >>> a + 1/2 + + >>> a*2 + 1 - >>> a*2 - 1 +SymPy usa mpmath en segundo plano (background), lo que hace posible ejecutar cálculos usando aritmética con precisión arbitraria. De esta forma, algunas constantes especiales como e, pi, oo (Infinito), son tratadas como símbolos y pueden ser evaluadas con precisión arbitraria -SymPy usa mpmath en segundo plano (background), lo que hace posible -ejecutar cálculos usando aritmética con precisión arbitraria. De -esta forma, algunas constantes especiales como e, pi, oo (Infinito), son tratadas como -símbolos y pueden ser evaluadas con precisión arbitraria:: +.. code-block:: python - >>> pi**2 - pi**2 + >>> pi**2 + pi**2 - >>> pi.evalf() - 3.14159265358979 + >>> pi.evalf() + 3.14159265358979 - >>> (pi+exp(1)).evalf() - 5.85987448204884 + >>> (pi+exp(1)).evalf() + 5.85987448204884 como puedes ver, evalf evalua la expresión como un número decimal. También existe una clase para representar el infinito (matemático) llamada -``oo``:: +``oo`` - >>> oo > 99999 - True - >>> oo + 1 - oo +.. code-block:: python + >>> oo > 99999 + True + >>> oo + 1 + oo Ejercicios ---------- @@ -93,24 +87,26 @@ Símbolos -------- En contraste a otros sistemas de álgebra computacional, en SymPy hay que declarar -las variables simbólicas de forma explícita:: +las variables simbólicas de forma explícita - >>> from sympy import * - >>> x = Symbol('x') - >>> y = Symbol('y') +.. code-block:: python -Después de declararlas podrán ser usadas:: + >>> from sympy import * + >>> x = Symbol('x') + >>> y = Symbol('y') - >>> x+y+x-y - 2*x +Después de declararlas podrán ser usadas - >>> (x+y)**2 - (x + y)**2 +.. code-block:: python -Los símbolos, ahora, pueden ser manipulados usando algunos de los operadores python: +, -, \*, \*\* -(arithmetic), &, |, ~ , >>, << (boolean). + >>> x+y+x-y + 2*x + >>> (x+y)**2 + (x + y)**2 +Los símbolos, ahora, pueden ser manipulados usando algunos de los operadores python: +, -, \*, \*\* +(arithmetic), &, |, ~ , >>, << (boolean). Manipulaciones algebraicas ========================== @@ -122,28 +118,32 @@ Expandir -------- Usa lo siguiente para expandir una expresión algebráica. Tratará de expandir -las potencias y multiplicaciones:: +las potencias y multiplicaciones + +.. sourcecode:: ipython - In [23]: expand((x+y)**3) - Out[23]: 3*x*y**2 + 3*y*x**2 + x**3 + y**3 + In [23]: expand((x+y)**3) + Out[23]: 3*x*y**2 + 3*y*x**2 + x**3 + y**3 -Se pueden usar diferentes opciones a partir de palabras clave (keywords):: +Se pueden usar diferentes opciones a partir de palabras clave (keywords) - In [28]: expand(x+y, complex=True) - Out[28]: I*im(x) + I*im(y) + re(x) + re(y) +.. sourcecode:: ipython - In [30]: expand(cos(x+y), trig=True) - Out[30]: cos(x)*cos(y) - sin(x)*sin(y) + In [28]: expand(x+y, complex=True) + Out[28]: I*im(x) + I*im(y) + re(x) + re(y) + In [30]: expand(cos(x+y), trig=True) + Out[30]: cos(x)*cos(y) - sin(x)*sin(y) Simplificación -------------- -Usa simplify si quieres transformar una expresión en algo más sencillo:: +Usa simplify si quieres transformar una expresión en algo más sencillo - In [19]: simplify((x+x*y)/x) - Out[19]: 1 + y +.. sourcecode:: ipython + In [19]: simplify((x+x*y)/x) + Out[19]: 1 + y Simplificación es un término vago, es por ello que existen alternativas más precisas que simplify: powsimp (simplificación de @@ -165,12 +165,16 @@ Límites Los límites son fáciles de usar en SymPy, siguen la sintáxis limit(función, variable, punto). Así, para calcular el límite de f(x) como x -> 0, deberías -usar la siguiente expresión limit(f, x, 0):: +usar la siguiente expresión limit(f, x, 0) + +.. code-block:: python >>> limit(sin(x)/x, x, 0) 1 -también puedes calcular el límite en el infinito:: +también puedes calcular el límite en el infinito + +.. code-block:: python >>> limit(x, x, oo) oo @@ -187,45 +191,50 @@ también puedes calcular el límite en el infinito:: Diferenciación/Derivación ------------------------- -Puedes derivar cualquier expresión SymPy usando ``diff(func, -var)``. Ejemplos:: +Puedes derivar cualquier expresión SymPy usando ``diff(func, var)``. Ejemplos + +.. code-block:: python - >>> diff(sin(x), x) - cos(x) - >>> diff(sin(2*x), x) - 2*cos(2*x) + >>> diff(sin(x), x) + cos(x) + >>> diff(sin(2*x), x) + 2*cos(2*x) - >>> diff(tan(x), x) - 1 + tan(x)**2 + >>> diff(tan(x), x) + 1 + tan(x)**2 -Puedes comprobar que esto es correcto mediante:: +Puedes comprobar que esto es correcto mediante - >>> limit((tan(x+y)-tan(x))/y, y, 0) - 1 + tan(x)**2 +.. code-block:: python -Se pueden obtener derivadas de orden superior mediante el método ``diff(func, var, n)``:: + >>> limit((tan(x+y)-tan(x))/y, y, 0) + 1 + tan(x)**2 - >>> diff(sin(2*x), x, 1) - 2*cos(2*x) +Se pueden obtener derivadas de orden superior mediante el método ``diff(func, var, n)`` - >>> diff(sin(2*x), x, 2) - -4*sin(2*x) +.. code-block:: python - >>> diff(sin(2*x), x, 3) - -8*cos(2*x) + >>> diff(sin(2*x), x, 1) + 2*cos(2*x) + + >>> diff(sin(2*x), x, 2) + -4*sin(2*x) + + >>> diff(sin(2*x), x, 3) + -8*cos(2*x) Expansión de series ------------------- -SymPy también permite computar la serie de Taylor de una expresión en un -punto. Usa ``series(expr, var)``:: +SymPy también permite computar la serie de Taylor de una expresión en un punto. Usa ``series(expr, var)`` - >>> series(cos(x), x) - 1 - x**2/2 + x**4/24 + O(x**6) - >>> series(1/cos(x), x) - 1 + x**2/2 + 5*x**4/24 + O(x**6) +.. code-block:: python + >>> series(cos(x), x) + 1 - x**2/2 + x**4/24 + O(x**6) + >>> series(1/cos(x), x) + 1 + x**2/2 + 5*x**4/24 + O(x**6) Ejercicios ---------- @@ -239,74 +248,83 @@ Integración ----------- SymPy ofrece soporte para integrales definidas o indefinidas de funciones transcendentes elementales -y de funciones especiales via `integrate()`, que usa una potente extensión del algoritmo Risch-Norman -y algo de heurística y de reconocimiento de patrones. Puedes integrar funciones elementales -de la siguiente forma:: +y de funciones especiales via `integrate()`, que usa una potente extensión del algoritmo Risch-Norman y algo de heurística y de reconocimiento de patrones. Puedes integrar funciones elementales +de la siguiente forma + +.. code-block:: python + + >>> integrate(6*x**5, x) + x**6 + >>> integrate(sin(x), x) + -cos(x) + >>> integrate(log(x), x) + -x + x*log(x) + >>> integrate(2*x + sinh(x), x) + cosh(x) + x**2 - >>> integrate(6*x**5, x) - x**6 - >>> integrate(sin(x), x) - -cos(x) - >>> integrate(log(x), x) - -x + x*log(x) - >>> integrate(2*x + sinh(x), x) - cosh(x) + x**2 +También se pueden manejar funciones especiales de forma sencilla -También se pueden manejar funciones especiales de forma sencilla:: +.. code-block:: python - >>> integrate(exp(-x**2)*erf(x), x) - pi**(1/2)*erf(x)**2/4 + >>> integrate(exp(-x**2)*erf(x), x) + pi**(1/2)*erf(x)**2/4 -Es posible calcular integrales definidas:: +Es posible calcular integrales definidas - >>> integrate(x**3, (x, -1, 1)) - 0 - >>> integrate(sin(x), (x, 0, pi/2)) - 1 - >>> integrate(cos(x), (x, -pi/2, pi/2)) - 2 +.. code-block:: python -También están soportadas las integrales impropias:: + >>> integrate(x**3, (x, -1, 1)) + 0 + >>> integrate(sin(x), (x, 0, pi/2)) + 1 + >>> integrate(cos(x), (x, -pi/2, pi/2)) + 2 - >>> integrate(exp(-x), (x, 0, oo)) - 1 - >>> integrate(exp(-x**2), (x, -oo, oo)) - pi**(1/2) +También están soportadas las integrales impropias +.. code-block:: python -.. index:: equations; algebraic, solve + >>> integrate(exp(-x), (x, 0, oo)) + 1 + >>> integrate(exp(-x**2), (x, -oo, oo)) + pi**(1/2) +.. index:: equations; algebraic, solve Ejercicios ---------- - - Resolución de ecuaciones ======================== -SymPy es capaz de resolver ecuaciones algebraicas de una o varias variables:: +SymPy es capaz de resolver ecuaciones algebraicas de una o varias variables - In [7]: solve(x**4 - 1, x) - Out[7]: [I, 1, -1, -I] +.. sourcecode:: ipython + + In [7]: solve(x**4 - 1, x) + Out[7]: [I, 1, -1, -I] Como has visto anteriormente, toma una expresión como primer argumento que se supone que es igual a 0. Es capaz de resolver una gran parte de ecuaciones polinómicas. Además, es capar de resolver múltiples ecuaciones respecto a múltiples variables (sistemas de ecuaciones) proporcionando -una tupla como segundo argumento:: +una tupla como segundo argumento + +.. sourcecode:: ipython - In [8]: solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y]) - Out[8]: {y: 1, x: -3} + In [8]: solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y]) + Out[8]: {y: 1, x: -3} -También tiene capacidad (limitada) de resolver ecuaciones transcendentales:: +También tiene capacidad (limitada) de resolver ecuaciones transcendentales + +.. sourcecode:: ipython In [9]: solve(exp(x) + 1, x) Out[9]: [pi*I] -Otra alternativa, en el caso de ecuaciones polinómicas, es -`factor`. `factor` devuelve el polinomio factorizado en términos irreducibles -y es capaz de calcular la factorización sobre varios dominios:: +Otra alternativa, en el caso de ecuaciones polinómicas, es `factor`. `factor` devuelve el polinomio factorizado en términos irreducibles y es capaz de calcular la factorización sobre varios dominios + +.. sourcecode:: ipython In [10]: f = x**4 - 3*x**2 + 1 In [11]: factor(f) @@ -315,30 +333,28 @@ y es capaz de calcular la factorización sobre varios dominios:: In [12]: factor(f, modulus=5) Out[12]: (2 + x)**2*(2 - x)**2 +SymPy también resuelve ecuaciones booleanas, esto es, decide si una determinada expresión booleana se cumple o no. Para ello se usa la función satisfiable - -SymPy también resuelve ecuaciones booleanas, esto es, decide si una -determinada expresión booleana se cumple o no. Para ello se usa la -función satisfiable:: +.. sourcecode:: ipython In [13]: satisfiable(x & y) Out[13]: {x: True, y: True} Lo anterior nos dice que (x & y) es True (verdadero) siempre que ambas variables, x e y, sean True. Si una expresión no puede ser verdadera, i.e. los valores de sus argumentos no pueden hacer -que la expresión sea True (verdadera), obtendremos el resultado False (Falso):: +que la expresión sea True (verdadera), obtendremos el resultado False (Falso) + +.. sourcecode:: ipython In [14]: satisfiable(x & ~x) Out[14]: False - Ejercicios ---------- 1. Resuelve el sistema de ecuaciones :math:`x + y = 2`, :math:`2\cdot x + y = 0` 2. ¿Hay expresiones booleanas ``x``, ``y`` que hacen que ``(~x | y) & (~y | x)`` sea verdadero? - .. Computaciones polinomiales .. ========================== @@ -354,49 +370,52 @@ Ejercicios Matrices -------- -Las Matrices se crean como instancias de la clase Matrix:: +Las Matrices se crean como instancias de la clase Matrix + +.. code-block:: python - >>> from sympy import Matrix - >>> Matrix([[1,0], [0,1]]) - [1, 0] - [0, 1] + >>> from sympy import Matrix + >>> Matrix([[1,0], [0,1]]) + [1, 0] + [0, 1] -A diferencia de un NumPy array, en una matriz (de Sympy) se pueden incluir también símbolos:: +A diferencia de un NumPy array, en una matriz (de Sympy) se pueden incluir también símbolos - >>> x = Symbol('x') - >>> y = Symbol('y') - >>> A = Matrix([[1,x], [y,1]]) - >>> A - [1, x] - [y, 1] +.. code-block:: python - >>> A**2 - [1 + x*y, 2*x] - [ 2*y, 1 + x*y] + >>> x = Symbol('x') + >>> y = Symbol('y') + >>> A = Matrix([[1,x], [y,1]]) + >>> A + [1, x] + [y, 1] + >>> A**2 + [1 + x*y, 2*x] + [ 2*y, 1 + x*y] .. index:: equations; differential, diff, dsolve Ecuaciones diferenciales ------------------------ -SymPy es capaz de resolver (algunas) ecuaciones diferenciales ordinarias. -sympy.ode.dsolve funciona de la siguiente forma:: +SymPy es capaz de resolver (algunas) ecuaciones diferenciales ordinarias. sympy.ode.dsolve funciona de la siguiente forma + +.. sourcecode:: ipython + + In [4]: f(x).diff(x, x) + f(x) + Out[4]: + 2 + d + ─────(f(x)) + f(x) + dx dx - In [4]: f(x).diff(x, x) + f(x) - Out[4]: - 2 - d - ─────(f(x)) + f(x) - dx dx + In [5]: dsolve(f(x).diff(x, x) + f(x), f(x)) + Out[5]: C₁*sin(x) + C₂*cos(x) - In [5]: dsolve(f(x).diff(x, x) + f(x), f(x)) - Out[5]: C₁*sin(x) + C₂*cos(x) +Se pueden usar argumentos en las keywords para ayudar a encontrar el mejor sistema de resolución posible. Por ejemplo, si a priori conoces que estás tratando con ecuaciones separables, puedes usar la palabra clave (keyword) hint='separable' para forzar a dsolve a que lo resuelva como una ecuación separable. -Se pueden usar argumentos en las keywords para ayudar a encontrar el -mejor sistema de resolución posible. Por ejemplo, si a priori conoces -que estás tratando con ecuaciones separables, puedes usar la palabra clave (keyword) hint='separable' -para forzar a dsolve a que lo resuelva como una ecuación separable. +.. sourcecode:: ipython In [6]: dsolve(sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x), f(x), hint='separable') Out[6]: -log(1 - sin(f(x))**2)/2 == C1 + log(1 - sin(x)**2)/2 @@ -409,6 +428,6 @@ Ejercicios .. warning:: - TODO: correct this equation and convert to math directive! +.. TODO: correct this equation and convert to math directive! 2. resuelve la misma ecuación usando hint='Bernoulli'. ¿Qué observas? diff --git a/advanced/traits/ETS.jpg b/packages/traits/ETS.jpg similarity index 100% rename from advanced/traits/ETS.jpg rename to packages/traits/ETS.jpg diff --git a/advanced/traits/index.rst b/packages/traits/index.rst similarity index 86% rename from advanced/traits/index.rst rename to packages/traits/index.rst index 07f89ab..dc1434d 100644 --- a/advanced/traits/index.rst +++ b/packages/traits/index.rst @@ -1,12 +1,22 @@ -====== -Traits -====== +.. _traits: + +====================================== +Traits: building interactive dialogs +====================================== :author: Didrik Pinte -The Traits project allows you to simply add validation, initialization, delegation, notification and a graphical user interface to Python object attributes. In this tutorial we will explore the Traits toolset and learn how to dramatically reduce the amount of boilerplate code you write, do rapid GUI application development, and understand the ideas which underly other parts of the Enthought Tool Suite. +The Traits project allows you to simply add validation, initialization, delegation, notification and a graphical user interface to Python object attributes. + +.. tip:: + + In this tutorial we will explore the Traits toolset and learn how to + dramatically reduce the amount of boilerplate code you write, do + rapid GUI application development, and understand the ideas which + underly other parts of the Enthought Tool Suite. -Traits and the Enthought Tool Suite are open source projects licensed under a BSD-style license. + Traits and the Enthought Tool Suite are open source projects licensed + under a BSD-style license. .. topic:: Intended Audience @@ -29,9 +39,17 @@ Traits and the Enthought Tool Suite are open source projects licensed under a BS Introduction ============ -The Enthought Tool Suite enable the construction of sophisticated application frameworks for data analysis, 2D plotting and 3D visualization. These powerful, reusable components are released under liberal BSD-style licenses. +.. tip:: + + The Enthought Tool Suite enable the construction of sophisticated + application frameworks for data analysis, 2D plotting and 3D + visualization. These powerful, reusable components are released under + liberal BSD-style licenses. + + .. image:: ETS.jpg + :align: right -The main packages are: +The main packages of the Enthought Tool Suite are: * Traits - component based approach to build our applications. * Kiva - 2D primitives supporting path based rendering, affine transforms, @@ -42,9 +60,6 @@ The main packages are: * Envisage - application plugin framework for building scriptable and extensible applications -.. image:: ETS.jpg - :align: center - In this tutorial, we will focus on Traits. Example @@ -64,7 +79,9 @@ reservoir and the dams do have a set of parameters : * Efficiency of the turbines The reservoir has a known behaviour. One part is related to the energy -production based on the water released. A simple formula for approximating electric power production at a hydroelectric plant is :math:`P = \rho hrgk`, where: +production based on the water released. A simple formula for +approximating electric power production at a hydroelectric plant is +:math:`P = \rho hrgk`, where: * :math:`P` is Power in watts, * :math:`\rho` is the density of water (~1000 kg/m3), @@ -73,11 +90,14 @@ production based on the water released. A simple formula for approximating elect * :math:`g` is acceleration due to gravity of 9.8 m/s2, * :math:`k` is a coefficient of efficiency ranging from 0 to 1. -Annual electric energy production depends on the available water supply. In some installations the water flow rate can vary by a factor of 10:1 over the course of a year. +.. tip:: + Annual electric energy production depends on the available water supply. + In some installations the water flow rate can vary by a factor of 10:1 + over the course of a year. -The second part of the behaviour is the state of the storage that depends on -controlled and uncontrolled parameters : +The second part of the behaviour is the state of the storage that depends +on controlled and uncontrolled parameters : :math:`storage_{t+1} = storage_t + inflows - release - spillage - irrigation` @@ -89,7 +109,8 @@ controlled and uncontrolled parameters : What are Traits =============== -A trait is a type definition that can be used for normal Python object attributes, giving the attributes some additional characteristics: +A trait is a type definition that can be used for normal Python object +attributes, giving the attributes some additional characteristics: * Standardization: * Initialization @@ -99,7 +120,10 @@ A trait is a type definition that can be used for normal Python object attribute * Visualization * Documentation -A class can freely mix trait-based attributes with normal Python attributes, or can opt to allow the use of only a fixed or open set of trait attributes within the class. Trait attributes defined by a class are automatically inherited by any subclass derived from the class. +A class can freely mix trait-based attributes with normal Python +attributes, or can opt to allow the use of only a fixed or open set of +trait attributes within the class. Trait attributes defined by a class +are automatically inherited by any subclass derived from the class. The common way of creating a traits class is by extending from the **HasTraits** base class and defining class traits : @@ -166,7 +190,7 @@ Custom default values can be defined in the code: reservoir = Reservoir(name='Lac de Vouglans') -.. note:: Complex initialisation +.. topic:: **Complex initialisation** When a complex initialisation is required for a trait, a _XXX_default magic method can be implemented. It will be lazily called when trying to access @@ -235,8 +259,8 @@ Let's now define the complete reservoir class: .. include:: reservoir.py :literal: -Visualisation -------------- +Visualization: opening a dialog +-------------------------------- The Traits library is also aware of user interfaces and can pop up a default view for the Reservoir class:: @@ -310,6 +334,8 @@ behaviour. .. include:: reservoir_turbine_prototype_from.py :literal: +.. _traits_notification: + Notification ------------ @@ -333,7 +359,7 @@ The static trait notification signatures can be: * def _release_changed(self, name, old, new pass -.. note:: Listening to all the changes +.. topic:: **Listening to all the changes** To listen to all the changes on a HasTraits class, the magic **_any_trait_changed** method can be implemented. diff --git a/advanced/traits/reservoir.py b/packages/traits/reservoir.py similarity index 100% rename from advanced/traits/reservoir.py rename to packages/traits/reservoir.py diff --git a/advanced/traits/reservoir_default_view.png b/packages/traits/reservoir_default_view.png similarity index 100% rename from advanced/traits/reservoir_default_view.png rename to packages/traits/reservoir_default_view.png diff --git a/advanced/traits/reservoir_evolution.png b/packages/traits/reservoir_evolution.png similarity index 100% rename from advanced/traits/reservoir_evolution.png rename to packages/traits/reservoir_evolution.png diff --git a/advanced/traits/reservoir_evolution.py b/packages/traits/reservoir_evolution.py similarity index 100% rename from advanced/traits/reservoir_evolution.py rename to packages/traits/reservoir_evolution.py diff --git a/advanced/traits/reservoir_simple_view.py b/packages/traits/reservoir_simple_view.py similarity index 100% rename from advanced/traits/reservoir_simple_view.py rename to packages/traits/reservoir_simple_view.py diff --git a/advanced/traits/reservoir_state.py b/packages/traits/reservoir_state.py similarity index 100% rename from advanced/traits/reservoir_state.py rename to packages/traits/reservoir_state.py diff --git a/advanced/traits/reservoir_state_dynamic_listener.py b/packages/traits/reservoir_state_dynamic_listener.py similarity index 100% rename from advanced/traits/reservoir_state_dynamic_listener.py rename to packages/traits/reservoir_state_dynamic_listener.py diff --git a/advanced/traits/reservoir_state_event.py b/packages/traits/reservoir_state_event.py similarity index 100% rename from advanced/traits/reservoir_state_event.py rename to packages/traits/reservoir_state_event.py diff --git a/advanced/traits/reservoir_state_property.py b/packages/traits/reservoir_state_property.py similarity index 100% rename from advanced/traits/reservoir_state_property.py rename to packages/traits/reservoir_state_property.py diff --git a/advanced/traits/reservoir_state_property_ontraitchange.py b/packages/traits/reservoir_state_property_ontraitchange.py similarity index 100% rename from advanced/traits/reservoir_state_property_ontraitchange.py rename to packages/traits/reservoir_state_property_ontraitchange.py diff --git a/advanced/traits/reservoir_state_property_view.py b/packages/traits/reservoir_state_property_view.py similarity index 100% rename from advanced/traits/reservoir_state_property_view.py rename to packages/traits/reservoir_state_property_view.py diff --git a/advanced/traits/reservoir_state_static_listener.py b/packages/traits/reservoir_state_static_listener.py similarity index 100% rename from advanced/traits/reservoir_state_static_listener.py rename to packages/traits/reservoir_state_static_listener.py diff --git a/advanced/traits/reservoir_state_view.png b/packages/traits/reservoir_state_view.png similarity index 100% rename from advanced/traits/reservoir_state_view.png rename to packages/traits/reservoir_state_view.png diff --git a/advanced/traits/reservoir_turbine_prototype_from.py b/packages/traits/reservoir_turbine_prototype_from.py similarity index 100% rename from advanced/traits/reservoir_turbine_prototype_from.py rename to packages/traits/reservoir_turbine_prototype_from.py diff --git a/advanced/traits/reservoir_view.png b/packages/traits/reservoir_view.png similarity index 100% rename from advanced/traits/reservoir_view.png rename to packages/traits/reservoir_view.png diff --git a/advanced/traits/reservoir_with_irrigation.py b/packages/traits/reservoir_with_irrigation.py similarity index 100% rename from advanced/traits/reservoir_with_irrigation.py rename to packages/traits/reservoir_with_irrigation.py diff --git a/advanced/traits/reservoir_with_irrigation_listener.py b/packages/traits/reservoir_with_irrigation_listener.py similarity index 100% rename from advanced/traits/reservoir_with_irrigation_listener.py rename to packages/traits/reservoir_with_irrigation_listener.py diff --git a/pyplots/plot.png b/pyplots/plot.png new file mode 100644 index 0000000..548ec8f Binary files /dev/null and b/pyplots/plot.png differ diff --git a/pyplots/red_elephant.png b/pyplots/red_elephant.png new file mode 100644 index 0000000..6df958b Binary files /dev/null and b/pyplots/red_elephant.png differ diff --git a/pyplots/tiny_elephant.png b/pyplots/tiny_elephant.png new file mode 100644 index 0000000..5d4c225 Binary files /dev/null and b/pyplots/tiny_elephant.png differ diff --git a/themes/minBox.png b/themes/minBox.png deleted file mode 100644 index 8224c32..0000000 Binary files a/themes/minBox.png and /dev/null differ diff --git a/themes/minBoxHighlight.png b/themes/minBoxHighlight.png deleted file mode 100644 index e0171c8..0000000 Binary files a/themes/minBoxHighlight.png and /dev/null differ diff --git a/themes/noneBox.png b/themes/noneBox.png deleted file mode 100644 index e92692c..0000000 Binary files a/themes/noneBox.png and /dev/null differ diff --git a/themes/plusBoxHighlight.png b/themes/plusBoxHighlight.png deleted file mode 100644 index 34eb3f5..0000000 Binary files a/themes/plusBoxHighlight.png and /dev/null differ diff --git a/themes/scipy_lectures/static/copybutton.js b/themes/scipy_lectures/static/copybutton.js new file mode 100644 index 0000000..527cf83 --- /dev/null +++ b/themes/scipy_lectures/static/copybutton.js @@ -0,0 +1,57 @@ +$(document).ready(function() { + /* Add a [>>>] button on the top-right corner of code samples to hide + * the >>> and ... prompts and the output and thus make the code + * copyable. */ + var div = $('.highlight-python .highlight,' + + '.highlight-python3 .highlight,' + + '.highlight-pycon .highlight') + var pre = div.find('pre'); + + // get the styles from the current theme + pre.parent().parent().css('position', 'relative'); + var hide_text = 'Hide the prompts and output'; + var show_text = 'Show the prompts and output'; + var border_width = pre.css('border-top-width'); + var border_style = pre.css('border-top-style'); + var border_color = pre.css('border-top-color'); + var button_styles = { + 'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0', + 'border-color': border_color, 'border-style': border_style, + 'border-width': border_width, 'color': border_color, 'text-size': '75%', + 'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em' + } + + // create and add the button to all the code blocks that contain >>> + div.each(function(index) { + var jthis = $(this); + if (jthis.find('.gp').length > 0) { + var button = $('>>>'); + button.css(button_styles) + button.attr('title', hide_text); + jthis.prepend(button); + } + // tracebacks (.gt) contain bare text elements that need to be + // wrapped in a span to work with .nextUntil() (see later) + jthis.find('pre:has(.gt)').contents().filter(function() { + return ((this.nodeType == 3) && (this.data.trim().length > 0)); + }).wrap(''); + }); + + // define the behavior of the button when it's clicked + $('.copybutton').toggle( + function() { + var button = $(this); + button.parent().find('.go, .gp, .gt').hide(); + button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden'); + button.css('text-decoration', 'line-through'); + button.attr('title', show_text); + }, + function() { + var button = $(this); + button.parent().find('.go, .gp, .gt').show(); + button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible'); + button.css('text-decoration', 'none'); + button.attr('title', hide_text); + }); +}); + diff --git a/themes/scipy_lectures/static/nature.css_t b/themes/scipy_lectures/static/nature.css_t index f54d8fa..b5572be 100644 --- a/themes/scipy_lectures/static/nature.css_t +++ b/themes/scipy_lectures/static/nature.css_t @@ -10,7 +10,111 @@ */ @import url("basic.css"); @import url("default.css"); + +/************************ Header *****************************/ + +div.related li { + display: inline-block; +} + +div.related a { + border-radius: 6px; + color: white; + display: inline-block; + border: none; +} + +div.related li.left { + margin-right: .5ex; + position: absolute; + left: -.8ex; + top: .2ex; +} + +/* Give a button-like feeling to the next/previous links */ +div.related li.right a { + font-weight: bold; + border-width: 1px; + /*border: solid; + border-width: 1px;*/ + border-color: #777; + padding: 0px 8px; + background-color: #333; + background-image: linear-gradient(#444, #111); + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);ul +} + +div.related a:hover { + background-image: linear-gradient(#777, #444); + text-decoration: none; +} + +div.related li.right a:hover { + background-image: linear-gradient(#666, #333); +} + + +div.related ul { + margin-left: .8ex; +} + +div.related li.left img { + padding: 0ex; +} + +div.related { + background-color: #555; + background-image: linear-gradient(#555, #333); + color: #777; + padding: 2px 0; +} + +/* Hide the footer */ +div.footer { + display: none; +} + +span.hiddenlink { + display: none; + z-index: 100; + background-color: rgb(355, 253, 242); + position: absolute; + left: 4px; + top: 20px; + width: 20ex; + padding: 3px; + border: 1px solid #888; + color: black; + line-height: 100%; +} + +li.left:hover span.hiddenlink { + display: block; +} + +li.transparent:hover span.hiddenlink { + display: none; +} + /* -- page layout ----------------------------------------------------------- */ + +/* Restrict the width of the body, to avoid very long lines */ +div.body { + max-width: 90ex; + margin-left: auto; + margin-right: auto; + /*border: solid; + border-width: 0px 1px 0px 1px; + border-color: rgb(204, 204, 204);*/ +} + +div.document { + /*background-color: #edf7fb;*/ + background-color: white; + border: solid; + border-color: #777; + border-width: 2px 0; +} /* special colors for exercises */ div.green { @@ -23,8 +127,28 @@ div.body h1, div.body h2 { font-weight: bold; } +/* more spacing for visual air */ +div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body +h6 { + margin: 20px 0px 20px -20px; + padding: 3px 0px 3px 5px; +} + +div.body h2 { + margin-top: 37px; +} + +div.body h3, div.body hr { + margin-top: 30px; +} + +div.body hr.docutils { + border-style: solid; + color: gray; +} + /* clear both after section titles */ -div.body h1, div.body h2, div.body h3, div.body h4 { +div.body h1, div.body h2, div.body h3, div.body h4, hr { clear: both; } @@ -37,14 +161,17 @@ div.body pre { /* The following lines ensure that no horizontal scrolling is * necessary to see code lines */ overflow: visible; - white-space: pre-wrap; text-overflow: ellipsis; +} + +div.highlight pre { /* Hack to have indented line wraps */ + white-space: pre-wrap; padding-left: 3.6em; text-indent: -3.5em; } /* Hack to have indented line wraps */ -pre div.newline { +div.highlight pre div.newline { margin-right: -4.5em; padding-left: 1em; display: inline-block; @@ -53,9 +180,25 @@ pre div.newline { div.body p { margin-bottom : .3em; - margin-top : 1.3em; + margin-top : .7em; +} + +div.body ul, div.body ol, div.body blockquote { + margin-top : .3em; +} + +/* Required for clean overlap in left or right align */ +div.body img { + position: relative; + z-index: 10; } +/* Center figures that are large than 100% of the figure */ +div.body div.figure { + margin-left: -200px; + margin-right: -200px; + text-align: center; +} /* alternating colors in table rows */ table.docutils tr:nth-child(even) { @@ -71,9 +214,19 @@ table.docutils tr { border-color: #AAAAAA; } +/* Boxes */ +div.topic, div.admonition { + border-radius: 4px 4px 4px 4px; +} + +div.topic, div.sidebar { + padding-top: 2px; +} + /* Content div */ div.contents { - background-color: #FFFFF6; + background-color: #FFFFF6; + border-color: #c0ac5c; } div.contents li { @@ -87,6 +240,10 @@ div.contents p { margin-top : 0px; } +div.body p.topic-title, div.body p.sidebar-title { + margin-bottom: 3px; +} + div.contents ul { margin-bottom : 4px; margin-top : 0px; @@ -134,16 +291,14 @@ table.hlist td { vertical-align: top; } -/* Admonitions */ -div.hint { - line-height: 1.5em; - margin: 0; - padding: 3px 5px; - width: 260px; - border: 1px solid #cccccc; - background-color: #FFD; +table.hlist ul { + margin-top: 0em; } + + +/************************ Admonitions ************************/ + div.admonition p { text-align: left; margin: 0; @@ -157,6 +312,96 @@ div.admonition .first { font-weight: bold; } +/* hint */ +div.hint { + line-height: 1.5em; + margin: 0; + padding: 3px 5px; + width: 260px; + border: 1px solid #cccccc; + background-color: #FFD; +} + +/* tip */ +div.tip .first { + visibility: hidden; + display: inline-block; + /*overflow: hidden;*/ + margin-right: -2ex; + margin-left: -2ex; + height: auto; +} + + +div.tip { + font-size: 95% ; + margin: 0px; + padding: 0px; + margin-left: -2ex; + padding-left: 2ex; + display: inline; + background-image: none; +} + +div.tip:hover { + background-image: url("minus.png"); + background-repeat: no-repeat; + background-position: .1ex, 1ex; +} + +div.collapsed { + color: #CCC; + background-position: .1ex, 1ex;*/ + font-size: 90% ; +} + +div.collapsed:hover { + background-image: none; +} + +div.collapsed p.summary img { + margin-left: -1.9ex; + margin-right: .6ex; + opacity: .5; +} + +div.collapsed p.admonition-title + p, div.collapsed p.admonition-title, +div.collapsed p, div.collapsed img, div.collapsed div, div.collapsed ul, +div.collapsed ol { + display: none; +} + +div.collapsed p.summary { + display: inline; +} + +div.collapsed:hover p.summary img { + opacity: 1; +} + +div.collapsed p.summary img { + display: inline; +} + +div.collapsed:hover { + background-position: .1ex, 1ex; + color: #999; +} + +.transparent img { + opacity: .5; +} + +.collapsed a { + color: #CCC; +} + +div.tip p.summary { + display: inline; +} + + +/* sidebar */ div.sidebar ul { padding-top: 0px; margin-top: 0px; @@ -166,4 +411,7 @@ div.sidebar .first { margin-bottom: 5px; } +div.sidebar { + margin-right: 2px; +} diff --git a/tune_toc.rst b/tune_toc.rst new file mode 100644 index 0000000..2fcb898 --- /dev/null +++ b/tune_toc.rst @@ -0,0 +1,138 @@ +.. raw:: html + + + + + +