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 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