**Oggetti tipo funzione**

Methods are associated with types, so it is possible to make any arbitrary Julia object “callable” by adding methods to its type. (Such “callable” objects are sometimes called “functors.”)

For example, you can define a type that stores the coefficients of a polynomial, but behaves like a function evaluating the polynomial:

Notice that the function is specified by type instead of by name. In the function body, ** p** will refer to the object that was called. A

`Polynomial`

This mechanism is also the key to how type constructors and closures (inner functions that refer to their surrounding environment) work in Julia, discussed later in the manual.

**Funzioni generiche vuote**

Occasionally it is useful to introduce a generic function without yet adding methods. This can be used to separate interface definitions from implementations. It might also be done for the purpose of documentation or code readability. The syntax for this is an empty function block without a tuple of arguments:

**Progettazione di metodi evitando ambiguità**

Julia’s method polymorphism is one of its most powerful features, yet exploiting this power can pose design challenges. In particular, in more complex method hierarchies it is not uncommon for ambiguities to arise.

Above, it was pointed out that one can resolve ambiguities like

by defining a method

This is often the right strategy; however, there are circumstances where following this advice blindly can be counterproductive. In particular, the more methods a generic function has, the more possibilities there are for ambiguities. When your method hierarchies get more complicated than this simple example, it can be worth your while to think carefully about alternative strategies.

Below we discuss particular challenges and some alternative ways to resolve such issues.

**argomenti Tuple e NTuple**

** Tuple** (and

`NTuple`

are ambiguous because of the possibility that ** N == 0**: there are no elements to determine whether the

`Int`

`Float64`

Alternatively, for all methods but one you can insist that there is at least one element in the tuple:

**ortogonalizzare il progetto**

When you might be tempted to dispatch on two or more arguments, consider whether a “wrapper” function might make for a simpler design. For example, instead of writing multiple variants:

`f(x::A, y::A) = ...`

`f(x::A, y::B) = ...`

`f(x::B, y::A) = ...`

`f(x::B, y::B) = ...`

you might consider defining

`f(x::A, y::A) = ...`

`f(x, y) = f(g(x), g(y))`

where ** g** converts the argument to type

`A`

`g`

`g(x::A) = x`

A related strategy exploits promote to bring ** x** and

`y`

`f(x::T, y::T) where {T} = ...`

`f(x, y) = f(promote(x, y)...)`

One risk with this design is the possibility that if there is no suitable promotion method converting ** x** and

`y`

`Base.promote_noncircular`

**inviare gli argomenti uno per volta**

If you need to dispatch on multiple arguments, and there are many fallbacks with too many combinations to make it practical to define all possible variants, then consider introducing a “name cascade” where (for example) you dispatch on the first argument and then call an internal method:

`f(x::A, y) = _fA(x, y)`

`f(x::B, y) = _fB(x, y)`

Then the internal methods ** _fA** and

`_fB`

`y`

`x`

Be aware that this strategy has at least one major disadvantage: in many cases, it is not possible for users to further customize the behavior of ** f** by defining further specializations of your exported function

`f`

`_fA`

`_fB`

**containers astratti e tipi di elementi**

Where possible, try to avoid defining methods that dispatch on specific element types of abstract containers. For example,

`-(A::AbstractArray{T}, b::Date) where {T<:Date}`

generates ambiguities for anyone who defines a method

`-(A::MyArrayType{T}, b::T) where {T}`

The best approach is to avoid defining either of these methods: instead, rely on a generic method ** -(A::AbstractArray, b)** and make sure this method is implemented with generic calls (like

`similar`

`-`

When this approach is not possible, it may be worth starting a discussion with other developers about resolving the ambiguity; just because one method was defined first does not necessarily mean that it can’t be modified or eliminated. As a last resort, one developer can define the “band-aid” method

`-(A::MyArrayType{T}, b::Date) where {T<:Date} = ...`

that resolves the ambiguity by brute force.

**metodo complesso a casata con argomenti di default**

If you are defining a method “cascade” that supplies defaults, be careful about dropping any arguments that correspond to potential defaults. For example, suppose you’re writing a digital filtering algorithm and you have a method that handles the edges of the signal by applying padding:

`function myfilter(A, kernel, ::Replicate) Apadded = replicate_edges(A, size(kernel)) myfilter(Apadded, kernel) # now perform the "real" computation end`

This will run afoul of a method that supplies default padding:

`myfilter(A, kernel) = myfilter(A, kernel, Replicate()) `

`# replicate the edge by default`

Together, these two methods generate an infinite recursion with ** A** constantly growing bigger.

The better design would be to define your call hierarchy like this:

`struct NoPad end # indicate that no padding is desired, # or that it's already applied myfilter(A, kernel) = myfilter(A, kernel, Replicate()) # default boundary conditions function myfilter(A, kernel, ::Replicate) Apadded = replicate_edges(A, size(kernel)) myfilter(Apadded, kernel, NoPad()) # indicate the new boundary conditions end # other padding methods go here function myfilter(A, kernel, ::NoPad) # Here's the "real" implementation of the core computation end`

** NoPad** is supplied in the same argument position as any other kind of padding, so it keeps the dispatch hierarchy well organized and with reduced likelihood of ambiguities. Moreover, it extends the “public”

`myfilter`

`NoPad`

**Yeppanico**

ma si può evitare, anzi si deve, *imho*

Archiviato in:Julia, Linguaggi ]]>

Continuo da qui.

Ho così finito la serie iniziata con NumPy, qui. Poi –come le ciliegie– una cosa tira l’altra e sono arrivati centinaia di post che contengono molto più di quello che m’interessa. Per contro per applicarli operativamente ogni singola funzione è da approfondire.

Pochi giorni fa ho assistito un giovane collega über-nerd alle prese con Java, con IDE über e supporto di memos sul telefono; anzi il telefono era un secondo ‘puter. Non riuscivo a seguirlo, sono niubbo, è vero, lo so; ma anche tardigrado. O forse è la specializzazione spinta? (spero).

Con NumPy, Matplotlib, SciPy &co è la stessa cosa: è richiesto un notevole investimento iniziale prima di essere operativi. E, almeno per chi conosco, c’è un rivale affermato: MATLAB. Si deve dire MATLAB (e tutto maiuscolo, à la bimbominkia) anche se in pratica è Octave; tranne casi molto particolari. Mi dicono che tutti usano quello e allora usi quello per evitare di doverti giustificare, spiegare. È cosa già sentita, dai tempi del Fortran IV, poi 77, poi –basta, alla fine si è passato ad altro.

Ma più in generale questo vale anche per Visual Basic, Delphi e altri ancora. Ah! sì Windows, quasi tutti (o sono io che sono sfigato) usano quello.

Poi gli altri, quelli normali, sono alle prese con il Web quindi JavaScript e, poco-poco, Java. C’è ancora chi usa il C++? Chissà…

OK, sono uscito fuori tema con questa tirata, non leggetela.

Io invece, trascinato dalla serie di packages Python penso di iniziare con un ulteriore argomento. Probabilmente senza applicazioni pratiche, ma intrigante. Prossimamente. Forse

Archiviato in:Linguaggi, Python, SciPy ]]>

**Ridefinire metodi**

When redefining a method or adding new methods, it is important to realize that these changes don’t take effect immediately. This is key to Julia’s ability to statically infer and compile code to run fast, without the usual JIT tricks and overhead. Indeed, any new method definition won’t be visible to the current runtime environment, including Tasks and Threads (and any previously defined ** @generated** functions). Let’s start with an example to see what this means:

In this example, observe that the new definition for ** newfun** has been created, but can’t be immediately called. The new global is immediately visible to the

`tryeval`

`return`

But there’s an exception: future calls to ** newfun** from the REPL work as expected, being able to both see and call the new definition of

`newfun`

However, future calls to ** tryeval** will continue to see the definition of

`newfun`

`tryeval`

The implementation of this behavior is a “world age counter”. This monotonically increasing value tracks each method definition operation. This allows describing “the set of method definitions visible to a given runtime environment” as a single number, or “world age”. It also allows comparing the methods available in two worlds just by comparing their ordinal value. In the example above, we see that the “current world” (in which the method ** newfun()** exists), is one greater than the task-local “runtime world” that was fixed when the execution of

`tryeval`

Sometimes it is necessary to get around this (for example, if you are implementing the above REPL). Fortunately, there is an easy solution: call the function using ** Base.invokelatest**:

Finally, let’s take a look at some more complex examples where this rule comes into play. Define a function ** f(x)**, which initially has one method:

Start some other operations that use ** f(x)**:

Now we add some new methods to ** f(x)**:

Compare how these results differ:

**Metodi Varargs vincolati parametricamente**

Function parameters can also be used to constrain the number of arguments that may be supplied to a “varargs” function (Varargs Functions [qui]). The notation ** Vararg{T,N}** is used to indicate such a constraint. For example:

More usefully, it is possible to constrain varargs methods by a parameter. For example:

**Nota sugli argomenti opzionali e keyword**

As mentioned briefly in Functions [qui], optional arguments are implemented as syntax for multiple method definitions. For example, this definition:

translates to the following three methods:

`f(a,b) = a+2b`

`f(a) = f(a,2)`

`f() = f(1,2)`

This means that calling ** f()** is equivalent to calling

`f(1,2)`

`5`

`f(1,2)`

`f`

then the result of both ** f()** and

`f(1,2)`

`-3`

Keyword arguments behave quite differently from ordinary positional arguments. In particular, they do not participate in method dispatch. Methods are dispatched based only on positional arguments, with keyword arguments processed after the matching method is identified.

Archiviato in:Julia, Linguaggi ]]>

**Interagire con MATLAB / Octave**

Faccio riferimento a Octave, ha tutto quel che serve (e anche di più) della versione e$o$a.

** loadmat(file_name[, mdict, appendmat])** load MATLAB file.

`savemat(file_name, mdict[, appendmat, ...])`

`.mat`

`whosmat(file_name[, appendmat])`

**Le funzioni base**

We’ll start by importing ** scipy.io** and calling it

`sio`

If you are using IPython, try tab completing on sio. Among the many options, you will find:

in particolare:

`sio.loadmat`

`sio.savemat`

`sio.whosmat`

These are the high-level functions you will most likely use when working with MATLAB files. You’ll also find:

`sio.matlab`

This is the package from which ** loadmat**,

`savemat`

`whosmat`

`sio.matlab`

`mio`

`loadmat`

`savemat`

**Come partire**

You may have a ** .mat** file that you want to read into Scipy. Or, you want to pass some variables from Scipy / Numpy into MATLAB.

To save us using a MATLAB license, let’s start in Octave. Octave has MATLAB-compatible save and load functions. Start Octave (** octave** at the command line):

Now, to Python:

Now let’s try the other way round:

Then back to Octave:

If you want to inspect the contents of a MATLAB file without reading the data into memory, use the ** whosmat** command:

** whosmat** returns a list of tuples, one for each array (or other object) in the file. Each tuple contains the name, shape and data type of the array.

**Structs di MATLAB**

MATLAB structs are a little bit like Python dicts, except the field names must be strings. Any MATLAB object can be a value of a field. As for all objects in MATLAB, structs are in fact arrays of structs, where a single struct is an array of shape (1, 1).

We can load this in Python:

In versions of Scipy from 0.12.0, MATLAB structs come back as ** numpy** structured arrays, with fields named for the struct fields. You can see the field names in the

`dtype`

and

So, in MATLAB, the struct array must be at least 2D, and we replicate that when we read into Scipy. If you want all length 1 dimensions squeezed out, try this:

Sometimes, it’s more convenient to load the MATLAB structs as python objects rather than ** numpy** structured arrays – it can make the access syntax in Python a bit more similar to that in MATLAB. In order to do this, use the

`struct_as_record=False`

`loadmat`

** struct_as_record=False** works nicely with

`squeeze_me`

Saving struct arrays can be done in various ways. One simple method is to use dicts:

loaded as:

You can also save structs back again to MATLAB (or Octave in our case) like this:

**Arrays di celle MATLAB**

Cell arrays in MATLAB are rather like python lists, in the sense that the elements in the arrays can contain any type of MATLAB object. In fact they are most similar to ** numpy** object arrays, and that is how we load them into

`numpy`

Back to Python:

Saving to a MATLAB cell array just involves making a ** numpy** object array:

Come si vede SciPy e Octave (MATLAB) possono dialogare, anche se non credo sia roba da tutti i giorni.

A questo punto si segue con altri programmi, IDL per esempio, ma non solo. Salto. E mi sa che devo cominciare a pensare a qualche nota di conclusioni personali.

Archiviato in:Linguaggi, Python, SICP ]]>

**Trasformare e combinare painters**

An operation on painters (such as ** flip-vert** or

`beside`

`frame`

`flip-vert`

Painter operations are based on the procedure ** transform-painter**, which takes as arguments a painter and information on how to transform a frame and produces a new painter. The transformed painter, when called on a frame, transforms the frame and calls the original painter on the transformed frame. The arguments to

`transform-painter`

`(define (transform-painter painter origin corner1 corner2) (lambda (frame) (let ((m (frame-coord-map frame))) (let ((new-origin (m origin))) (painter (make-frame new-origin (sub-vect (m corner1) new-origin) (sub-vect (m corner2) new-origin)))))))`

Here’s how to flip painter images vertically:

`(define (flip-vert painter) (transform-painter painter (make-vect 0.0 1.0) ; new origin (make-vect 1.0 1.0) ; new end of edge1 (make-vect 0.0 0.0))) ; new end of edge2`

Using ** transform-painter**, we can easily define new transformations. For example, we can define a painter that shrinks its image to the upper-right quarter of the frame it is given:

`(define (shrink-to-upper-right painter) (transform-painter painter (make-vect 0.5 0.5) (make-vect 1.0 0.5) (make-vect 0.5 1.0)))`

Other transformations rotate images counterclockwise by 90 degrees (** rotate90** is a pure rotation only for square frames, because it also stretches and shrinks the image to fit into the rotated frame.)

`(define (rotate90 painter) (transform-painter painter (make-vect 1.0 0.0) (make-vect 1.0 1.0) (make-vect 0.0 0.0)))`

or squash images towards the center of the frame:

`(define (squash-inwards painter) (transform-painter painter (make-vect 0.0 0.0) (make-vect 0.65 0.35) (make-vect 0.35 0.65)))`

Frame transformation is also the key to defining means of combining two or more painters. The ** beside** procedure, for example, takes two painters, transforms them to paint in the left and right halves of an argument frame respectively, and produces a new, compound painter. When the compound painter is given a frame, it calls the first transformed painter to paint in the left half of the frame and calls the second transformed painter to paint in the right half of the frame:

`(define (beside painter1 painter2) (let ((split-point (make-vect 0.5 0.0))) (let ((paint-left (transform-painter painter1 (make-vect 0.0 0.0) split-point (make-vect 0.0 1.0))) (paint-right (transform-painter painter2 split-point (make-vect 1.0 0.0) (make-vect 0.5 1.0)))) (lambda (frame) (paint-left frame) (paint-right frame)))))`

Observe how the painter data abstraction, and in particular the representation of painters as procedures, makes ** beside** easy to implement. The

`beside`

Da studiare bene che arrivano gli esercizi.

Archiviato in:Linguaggi, Racket, SICP ]]>

**Russian Group That Hacked DNC Used NSA Attack Code In Attack On Hotels**

*#:sicurezza, spionaggio, virus*

::: Slashdot

**Hype or Not? Some Perspective on OpenAI’s DotA 2 Bot**

*#:artificial intelligence*

::: dennybritz

**#OpenSource is a big deal for software vendors, but mainstream enterprises derive the biggest benefits**

*#:free open source software*

::: JenInnovate

**A New Amiga Will Go On Sale In Late 2017**

*#:hardware*

::: Slashdot

**User-programmable infix operators in Racket**

Lexi rockz!

*#:lisp(s)*

::: Alexis King

**Bitcoin Just Surged Past $4,000. TechCrunch Explains Why**

*#:Web, Internet*

::: Slashdot

**Tell @fommil how much this in-progress book would be worth to you: Functional Programming in #Scala For Mortals**

*#:programmazione funzionale*

::: Symbo1ics

**Why AI Won’t Take Over The Earth**

*#:artificial intelligence*

::: Slashdot

**the world might be better off if some people remain disconnected and far apart**

*#:Web, Internet*

::: fabiochiusi

**#Rust for the Web**

*#:linguaggi di programmazione #:Web, Internet*

::: Donearm

**GNOME at 20: Four reasons it’s still my favorite GUI**

*#:sistemi operativi*

::: lucaciavatta

**Parser combinators in the wild**

*#:linguaggi di programmazione*

::: thompson_si

**A visual programming language for microcontrollers**

*#:linguaggi di programmazione*

::: algoritmic

**I dati diffusi da @r0gue_0 “si sono dimostrati privi di fondamento”, scrive Ass. Rousseau**

Beppe buffone & bugiardo

*#:sicurezza, spionaggio, virus*

::: fabiochiusi ::: fabiochiusi

**64-bit Firefox is the New Default on 64-bit Windows**

*#:Web, Internet #:tools, componenti software*

::: Slashdot

**Today I put up a static HTML version of the Python Data Science Handbook so that search engines can index it**

*#:linguaggi di programmazione*

::: jakevdp

**I just learned about #asciinema**

*#:tools, componenti software*

::: MonaJalal_

**Perhaps useful: Simplicity is complicated**

*#:linguaggi di programmazione*

::: Sajma

**Using JavaScript to hack the web**

*#:linguaggi di programmazione*

::: lucaciavatta

**Dimissioni**

*#:free open source software*

::: italovignoli

**Moral Machine**

*#:artificial intelligence*

::: vikkio88

**Our friends at @fightthefuture @freepress @demandprogress need volunteers to save #NetNeutrality. Join the fight**

*#:Web, Internet*

::: mozilla

**Right and left folds, primitive recursion patterns in Python and Haskell**

*#:algoritmi, codice*

::: Eli Bendersky

**Andrew Ng dreams of an AI-powered society**

*#:artificial intelligence*

::: TechCrunch

**These are the 25 most high-tech cities in the world**

*#:economia*

::: Davos

**An Early Door to Cyberspace: The Community Memory Terminal**

*#:storia*

::: Computer History Museum

**We found the first Windows virus in history in August 1992**

*#:storia*

::: mikko

**my only conclusion is that most Python code should avoid the use of classes**

*#:linguaggi di programmazione*

::: asmeurer

**Unhiding the decline**

This is the initial release of my new GHCN software, titled UNHIDING THE DECLINE. It is designed to allow you to process large GHCN databases on a small computer with little memory, and make graphs very quickly

*#:linguaggi di programmazione*

::: The Deplorable Climate Science

**Secondo me #Internet c’è sempre stata**

*#:Web, Internet*

::: SergioGridelli

**riassunto sulla vicenda #hack5stelle**

*#:sicurezza, spionaggio, virus*

::: Clodo76

**Artificial Intelligence programs exclude minority voices, while conservatives rail against tech for including them**

*#:artificial intelligence*

::: Liberationtech

**Lasciate che gli idioti vengano a me**

*#:Web, Internet #:censura*

::: manteblog

**10 advantages of open source for the enterprise**

*#:free open source software*

::: lucaciavatta

**To find the right product, we must focus on the right problem. The one Facebook can’t solve, or makes worse**

*#:Web, Internet*

::: marklittlenews

**In un paese di non analfabeti informatici, quello che è successo a Rousseau**

*#:sicurezza, spionaggio, virus*

::: fabiochiusi

**We have incredible ways to store and produce information**

*#:Web, Internet*

::: thek3nger

**Introducing Puppeteer: A modern Node.js API for headless Chrome**

*#:linguaggi di programmazione #:Web, Internet*

::: ChromeDevTools

**Graham Hutton on lambda calculus and even how it relates to self-replicating DNA (aka “life”)**

mooolto bello

*#:programmazione funzionale*

::: mittie

**Margaret Hamilton – Comic by @LukeKingma profiles the computer science pioneer**

*#:storia*

::: MIT

**Il buonsenso dei fondatori di TOR sui nazisti americani e la loro esistenza in rete**

*#:free open source software #:Web, Internet*

::: mante

**WikiLeaks turned down leaks on Russian government during U.S. presidential campaign**

*#:sicurezza, spionaggio, virus*

::: JennaMC_Laugh ::: NatashaBertrand

**(A ((Pretty OK) Lisp) Interpreter {in SETL})**

(per quando sarò vecchio)

*#:lisp(s)*

::: NeuralOutlet

**The domain name infrastructure is not the right place to fight extremism**

*#:Web, Internet*

::: EFF

**How To Search Google from the Command Line**

*#:Web, Internet*

::: lucaciavatta

**How Security Pros Look at Encryption Backdoors**

*#:sicurezza, spionaggio, virus*

::: Slashdot

**Oracle seeks to shift Java EE to the open source community**

*#:linguaggi di programmazione*

::: barton808

**Google now recognizes 119 languages for voice-to-text dictation**

suggeritami da Daniel Lemire, uno da seguire

*#:innovazioni, futuro*

::: The Verge

**Nimbus Data Unveils 50TB Flash Drive, on Path to 500TB**

anche questa

*#:hardware*

::: TOP500

**The next wave of computing**

*#:innovazioni, futuro*

::: Info_Activism

**yet another little reminder/explanation on how `handleEvent` as object listener method, instead of function, works**

*#:linguaggi di programmazione*

::: WebReflection

**US Military To Create Separate Unified Cyber Warfare Command**

*#:sicurezza, spionaggio, virus*

::: Slashdot

Archiviato in:Visto nel Web ]]>

**Ambiguità dei metodi**

It is possible to define a set of function methods such that there is no unique most specific method applicable to some combinations of arguments:

Here the call ** g(2.0, 3.0)** could be handled by either the

`g(Float64, Any)`

`g(Any, Float64)`

`MethodError`

It is recommended that the disambiguating method be defined first, since otherwise the ambiguity exists, if transiently, until the more specific method is defined.

In more complex cases, resolving method ambiguities involves a certain element of design; this topic is explored further below.

**Metodi Prametrici**

Method definitions can optionally have type parameters qualifying the signature:

The first method applies whenever both arguments are of the same concrete type, regardless of what type that is, while the second method acts as a catch-all, covering all other cases. Thus, overall, this defines a boolean function that checks whether its two arguments are of the same type:

Such definitions correspond to methods whose type signatures are ** UnionAll** types (see UnionAll Types [qui]).

This kind of definition of function behavior by dispatch is quite common – idiomatic, even – in Julia. Method type parameters are not restricted to being used as the types of arguments: they can be used anywhere a value would be in the signature of the function or body of the function. Here’s an example where the method type parameter ** T** is used as the type parameter to the parametric type

`Vector{T}`

As you can see, the type of the appended element must match the element type of the vector it is appended to, or else a ** MethodError** is raised. In the following example, the method type parameter

`T`

Just as you can put subtype constraints on type parameters in type declarations (see Parametric Types [qui]), you can also constrain type parameters of methods:

The ** same_type_numeric** function behaves much like the

`same_type`

Parametric methods allow the same syntax as ** where** expressions used to write types (see UnionAll Types [link indicato sopra]). If there is only a single parameter, the enclosing curly braces (in

`where {T}`

`where {T, S<:Real}`

`where`

`where S<:Real where T`

Archiviato in:Julia, Linguaggi ]]>

**Misura di oggetti**

Given an array of labeled objects, the properties of the individual objects can be measured. The ** find_objects** function can be used to generate a list of slices that for each object, give the smallest sub-array that fully contains the object:

The ** find_objects** function finds all objects in a labeled array and returns a list of slices that correspond to the smallest regions in the array that contains the object. For instance:

The function ** find_objects** returns slices for all objects, unless the

`max_label parameter`

`max_label`

`None`

The list of slices generated by ** find_objects** is useful to find the position and dimensions of the objects in the array, but can also be used to perform measurements on the individual objects. Say we want to find the sum of the intensities of an object in image:

Then we can calculate the sum of the elements in the second object:

That is however not particularly efficient, and may also be more complicated for other types of measurements. Therefore a few measurements functions are defined that accept the array of object labels and the index of the object to be measured. For instance calculating the sum of the intensities can be done by:

or large arrays and small objects it is more efficient to call the measurement functions after slicing the array:

Alternatively, we can do the measurements for a number of labels with a single function call, returning a list of results. For instance, to measure the sum of the values of the background and the second object in our example we give a list of labels:

The measurement functions described below all support the ** index parameter** to indicate which object(s) should be measured. The default value of

`index `

`None`

`index`

`index`

`index`

`index`

- The
function calculates the sum of the elements of the object with label(s) given by`sum`

, using the labels array for the object labels. If`index`

is`index`

, all elements with a non-zero label value are treated as a single object. If`None`

is`label`

, all elements of input are used in the calculation.`None`

- The
function calculates the mean of the elements of the object with label(s) given by`mean`

, using the labels array for the object labels. If`index`

is`index`

, all elements with a non-zero`None`

value are treated as a single object. If`label`

is`label`

, all elements of input are used in the calculation.`None`

- The
function calculates the variance of the elements of the object with label(s) given by`variance`

, using the labels array for the object labels. If`index`

is`index`

, all elements with a non-zero`None`

value are treated as a single object. If`label`

is`label`

, all elements of input are used in the calculation.`None`

- The
function calculates the standard deviation of the elements of the object with label(s) given by`standard_deviation`

, using the labels array for the object labels. If`index`

is`index`

, all elements with a non-zero`None`

value are treated as a single object. If`label`

is`label`

, all elements of input are used in the calculation.`None`

- The
function calculates the minimum of the elements of the object with label(s) given by`minimum`

, using the labels array for the object labels. If`index`

is`index`

, all elements with a non-zero label value are treated as a single object. If`None`

is`label`

, all elements of input are used in the calculation.`None`

- The
function calculates the maximum of the elements of the object with label(s) given by`maximum`

, using the labels array for the object labels. If`index`

is`index`

, all elements with a non-zero`None`

value are treated as a single object. If`label`

is`label`

, all elements of input are used in the calculation.`None`

- The
function calculates the position of the minimum of the elements of the object with label(s) given by index, using the labels array for the object labels. If`minimum_position`

is`index`

, all elements with a non-zero`None`

value are treated as a single object. If`label`

is`label`

, all elements of input are used in the calculation.`None`

- The
function calculates the position of the maximum of the elements of the object with label(s) given by index, using the labels array for the object labels. If`maximum_position`

is`index`

, all elements with a non-zero`None`

value are treated as a single object. If`label`

is`label`

, all elements of input are used in the calculation.`None`

- The
function calculates the minimum, the maximum, and their positions, of the elements of the object with label(s) given by`extrema`

, using the labels array for the object labels. If`index`

is`index`

, all elements with a non-zero`None`

value are treated as a single object. If`label`

is`label`

, all elements of input are used in the calculation. The result is a tuple giving the minimum, the maximum, the position of the minimum and the position of the maximum. The result is the same as a tuple formed by the results of the functions`None`

,`minimum`

,`maximum`

, and`minimum_position`

that are described above.`maximum_position`

- The
function calculates the center of mass of the of the object with label(s) given by`center_of_mass`

, using the labels array for the object labels. If`index`

is`index`

, all elements with a non-zero`None`

value are treated as a single object. If`label`

is`label`

, all elements of input are used in the calculation.`None`

- The
function calculates a histogram of the of the object with label(s) given by`histogram`

, using the labels array for the object labels. If`index`

is`index`

, all elements with a non-zero`None`

value are treated as a single object. If`label`

is`label`

, all elements of input are used in the calculation. Histograms are defined by their minimum (`None`

), maximum (`min`

) and the number of bins (`max`

). They are returned as one-dimensional arrays of type`bins`

.`Int32`

A questo punto c’è **Extending** `scipy.ndimage`

**in C** ma salto l’argomento e passo al capitolo successivo.

Avevo già provato in passato senza riuscirci. Adesso ho approfondito, ho consultato la documentazione ufficiale di Python, scoprendo il comando ** python3 setup.py** build, dove

`setup.py`

Archiviato in:Linguaggi, Python, SciPy ]]>

Recall from Functions [qui] that a function is an object that maps a tuple of arguments to a return value, or throws an exception if no appropriate value can be returned. It is common for the same conceptual function or operation to be implemented quite differently for different types of arguments: adding two integers is very different from adding two floating-point numbers, both of which are distinct from adding an integer to a floating-point number. Despite their implementation differences, these operations all fall under the general concept of “addition”. Accordingly, in Julia, these behaviors all belong to a single object: the ** +** function.

To facilitate using many different implementations of the same concept smoothly, functions need not be defined all at once, but can rather be defined piecewise by providing specific behaviors for certain combinations of argument types and counts. A definition of one possible behavior for a function is called a ** method**. Thus far, we have presented only examples of functions defined with a single method, applicable to all types of arguments. However, the signatures of method definitions can be annotated to indicate the types of arguments in addition to their number, and more than a single method definition may be provided. When a function is applied to a particular tuple of arguments, the most specific method applicable to those arguments is applied. Thus, the overall behavior of a function is a patchwork of the behaviors of its various method definitions. If the patchwork is well designed, even though the implementations of the methods may be quite different, the outward behavior of the function will appear seamless and consistent.

The choice of which method to execute when a function is applied is called dispatch. Julia allows the dispatch process to choose which of a function’s methods to call based on the number of arguments given, and on the types of all of the function’s arguments. This is different than traditional object-oriented languages, where dispatch occurs based only on the first argument, which often has a special argument syntax, and is sometimes implied rather than explicitly written as an argument. [vedi nota 1] Using all of a function’s arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch. Multiple dispatch is particularly useful for mathematical code, where it makes little sense to artificially deem the operations to “belong” to one argument more than any of the others: does the addition operation in ** x + y** belong to

`x`

`y`

[**1**]

In C++ or Java, for example, in a method call like ** obj.meth(arg1,arg2)**, the object

`obj`

`this`

`meth(arg1,arg2)`

**Definire metodi**

Until now, we have, in our examples, defined only functions with a single method having unconstrained argument types. Such functions behave just like they would in traditional dynamically typed languages. Nevertheless, we have used multiple dispatch and methods almost continually without being aware of it: all of Julia’s standard functions and operators, like the aforementioned ** +** function, have many methods defining their behavior over various possible combinations of argument type and count.

When defining a function, one can optionally constrain the types of parameters it is applicable to, using the ** ::** type-assertion operator, introduced in the section on Composite Types [qui]:

This function definition applies only to calls where ** x** and

`y`

`Float64`

Applying it to any other types of arguments will result in a ** MethodError**:

Nota lollosa: dillo a JavaScript

As you can see, the arguments must be precisely of type ** Float64**. Other numeric types, such as integers or 32-bit floating-point values, are not automatically converted to 64-bit floating-point, nor are strings parsed as numbers. Because

`Float64`

`Float64`

This method definition applies to any pair of arguments that are instances of ** Number**. They need not be of the same type, so long as they are each numeric values. The problem of handling disparate numeric types is delegated to the arithmetic operations in the expression

`2x - y`

To define a function with multiple methods, one simply defines the function multiple times, with different numbers and types of arguments. The first method definition for a function creates the function object, and subsequent method definitions add new methods to the existing function object. The most specific method definition matching the number and types of the arguments will be executed when the function is applied. Thus, the two method definitions above, taken together, define the behavior for ** f** over all pairs of instances of the abstract type

`Number`

`Float64`

`f(Float64,Float64)`

`(Number,Number)`

The ** 2x + y** definition is only used in the first case, while the

`2x - y`

For non-numeric values, and for fewer or more than two arguments, the function ** f** remains undefined, and applying it will still result in a

`MethodError`

You can easily see which methods exist for a function by entering the function object itself in an interactive session:

This output tells us that ** f** is a function object with two methods. To find out what the signatures of those methods are, use the

`methods()`

which shows that f has two methods, one taking two ** Float64** arguments and one taking arguments of type

`Number`

`none:1`

In the absence of a type declaration with ** ::**, the type of a method parameter is

`Any`

`Any`

`f`

This catch-all is less specific than any other possible method definition for a pair of parameter values, so it will only be called on pairs of arguments to which no other method definition applies.

Although it seems a simple concept, multiple dispatch on the types of values is perhaps the single most powerful and central feature of the Julia language. Core operations typically have dozens of methods:

Questo è solo l’inizio, ovviamente. Per vederli tutti il sistema più semplice, imho, è questo:

che crea il file `jlmet+`

Archiviato in:Julia, Linguaggi ]]>

**Segmentazione ed etichettatura**

Segmentation is the process of separating objects of interest from the background. The most simple approach is probably intensity thresholding, which is easily done with ** numpy** functions:

The result is a binary image, in which the individual objects still need to be identified and labeled. The function ** label** generates an array where each object is assigned a unique number:

The ** label** function generates an array where the objects in the input are labeled with an integer index. It returns a tuple consisting of the array of object labels and the number of objects found, unless the output parameter is given, in which case only the number of objects is returned. The connectivity of the objects is defined by a structuring element. For instance, in two dimensions using a four-connected structuring element gives:

These two objects are not connected because there is no way in which we can place the structuring element such that it overlaps with both objects. However, an 8-connected structuring element results in only a single object:

If no structuring element is provided, one is generated by calling ** generate_binary_structure** (see Binary morphology [qui]) using a connectivity of one (which in 2D is the 4-connected structure of the first example). The input can be of any type, any value not equal to zero is taken to be part of an object. This is useful if you need to ‘re-label’ an array of object indices, for instance after removing unwanted objects. Just apply the

`label`

* Note*: The structuring element used by label is assumed to be symmetric.

There is a large number of other approaches for segmentation, for instance from an estimation of the borders of the objects that can be obtained for instance by derivative filters. One such an approach is watershed segmentation. The function ** watershed_ift** generates an array where each object is assigned a unique label, from an array that localizes the object borders, generated for instance by a gradient magnitude filter. It uses an array containing initial markers for the objects:

The ** watershed_ift** function applies a watershed from markers algorithm, using an Iterative Forest Transform, as described in P. Felkel, R. Wegenkittl, and M. Bruckschwaiger, “Implementation and Complexity of the Watershed-from-Markers Algorithm Computed as a Minimal Cost Forest.”, Eurographics 2001, pp. C:26-35.

The inputs of this function are the array to which the transform is applied, and an array of markers that designate the objects by a unique label, where any non-zero value is a marker. For instance:

Here two markers were used to designate an object (** marker = 2**) and the background (

`marker = 1`

The result is that the object (** marker = 2**) is smaller because the second marker was processed earlier. This may not be the desired effect if the first marker was supposed to designate a background object. Therefore

`watershed_ift`

The connectivity of the objects is defined by a structuring element. If no structuring element is provided, one is generated by calling ** generate_binary_structure** (see Binary morphology [stesso link]) using a connectivity of one (which in 2D is a 4-connected structure.) For example, using an 8-connected structure with the last example yields a different object:

* Note*: The implementation of

`watershed_ift`

`UInt8`

`UInt16`

Archiviato in:Linguaggi, Python, SciPy ]]>