339
JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. [email protected]

JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. [email protected]

  • Upload
    vankiet

  • View
    241

  • Download
    0

Embed Size (px)

Citation preview

Page 1: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

JuliaPro v0.5.1.1 API Manual

March 8, 2017

Julia Computing [email protected]

Page 2: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Contents

1 PyPlot 1

2 QuantEcon 57

3 StatsBase 98

4 Distributions 121

5 Images 140

6 DataFrames 155

7 EzXML 169

8 ImageCore 183

9 SpecialFunctions 191

10 Knet 198

11 Combinatorics 204

12 Roots 209

13 Reactive 215

14 Documenter 220

15 CategoricalArrays 224

16 Gadfly 228

17 DataStructures 233

18 PyCall 239

19 ColorTypes 243

I

Page 3: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

II CONTENTS

20 Colors 247

21 Interact 251

22 FileIO 255

23 ShowItLikeYouBuildIt 259

24 CoordinateTransformations 262

25 Polynomials 264

26 Interpolations 267

27 PolynomialFactors 269

28 JavaCall 271

29 Libz 274

30 BusinessDays 277

31 AxisAlgorithms 279

32 LegacyStrings 281

33 NullableArrays 283

34 ImageMetadata 285

35 MbedTLS 287

36 Compose 289

37 JuliaWebAPI 291

38 Clustering 293

39 BufferedStreams 295

40 GLM 297

41 AxisArrays 299

42 ComputationalResources 301

43 DecisionTree 302

44 FixedSizeArrays 303

Page 4: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

CONTENTS III

45 AutoGrad 304

46 HypothesisTests 306

47 Blosc 308

48 HttpServer 310

49 ImageTransformations 312

50 MacroTools 313

51 NearestNeighbors 315

52 IJulia 316

53 MappedArrays 317

54 StaticArrays 318

55 Mustache 319

56 ImageAxes 320

57 HttpParser 321

58 TiledIteration 322

59 Juno 323

60 ObjFileBase 324

61 HttpCommon 325

62 Media 326

63 Rotations 327

64 Loess 328

65 Parameters 329

66 LineSearches 330

67 WoodburyMatrices 331

68 Requests 332

69 SimpleTraits 333

Page 5: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

IV CONTENTS

70 Iterators 334

Page 6: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 1

PyPlot

1.1 Base.step

Base.step — Method.Make a step plot.

1.1.1 Parameters

x : array like 1-D sequence, and it is assumed, but not checked, that it isuniformly increasing.

y : array like 1-D sequence, and it is assumed, but not checked, that it isuniformly increasing.

1.1.2 Returns

list List of lines that were added.

1.1.3 Other parameters

where : [ ‘pre’ | ‘post’ | ‘mid’ ] If ‘pre’ (the default), the interval from x[i] tox[i+1] has level y[i+1].

If ’post’, that interval has level y[i].

If ’mid’, the jumps in *y* occur half-way between the

*x*-values.

1.1.4 Notes

Additional parameters are the same as those for :func:~matplotlib.pyplot.plot... note:: In addition to the above described arguments, this function can

take a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

1

Page 7: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2 CHAPTER 1. PYPLOT

* All arguments with the following names: ’x’, ’y’.

1.2 PyPlot.Axes3D

PyPlot.Axes3D — Method.

3D axes object.

1.3 PyPlot.acorr

PyPlot.acorr — Method.Plot the autocorrelation of x.

1.3.1 Parameters

x : sequence of scalarhold : boolean, optional, deprecated, default: Truedetrend : callable, optional, default: mlab.detrend none x is detrended by

the detrend callable. Default is no normalization.normed : boolean, optional, default: True if True, input vectors are nor-

malised to unit length.usevlines : boolean, optional, default: True if True, Axes.vlines is used to

plot the vertical lines from the origin to the acorr. Otherwise, Axes.plot is used.maxlags : integer, optional, default: 10 number of lags to show. If None,

will return all 2 * len(x) - 1 lags.

1.3.2 Returns

(lags, c, line, b) : where:

• lags are a length 2‘maxlags+1 lag vector.

• c is the 2‘maxlags+1 auto correlation vectorI

• line is a ~matplotlib.lines.Line2D instance returned by plot.

• b is the x-axis.

1.3.3 Other parameters

linestyle : ~matplotlib.lines.Line2D prop, optional, default: None Only usedif usevlines is False.

marker : string, optional, default: ‘o’

1.3.4 Notes

The cross correlation is performed with :func:numpy.correlate with mode = 2.

Page 8: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.4. PYPLOT.ANNOTATE 3

1.3.5 Examples

~matplotlib.pyplot.xcorr is top graph, and ~matplotlib.pyplot.acorr isbottom graph.

.. plot:: mpl examples/pylab examples/xcorr demo.py

.. note:: In addition to the above described arguments, this function cantake a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All arguments with the following names: ’x’.

1.4 PyPlot.annotate

PyPlot.annotate — Method.Annotate the point xy with text s.Additional kwargs are passed to ~matplotlib.text.Text.

1.4.1 Parameters

s : str The text of the annotationxy : iterable Length 2 sequence specifying the (x,y) point to annotatexytext : iterable, optional Length 2 sequence specifying the (x,y) to place

the text at. If None, defaults to xy.xycoords : str, Artist, Transform, callable or tuple, optional

The coordinate system that ‘‘xy‘‘ is given in.

For a ‘str‘ the allowed values are:

================= ===============================================

Property Description

================= ===============================================

’figure points’ points from the lower left of the figure

’figure pixels’ pixels from the lower left of the figure

’figure fraction’ fraction of figure from lower left

’axes points’ points from lower left corner of axes

’axes pixels’ pixels from lower left corner of axes

’axes fraction’ fraction of axes from lower left

’data’ use the coordinate system of the object being

annotated (default)

’polar’ *(theta,r)* if not native ’data’ coordinates

================= ===============================================

If a ‘~matplotlib.artist.Artist‘ object is passed in the units are

fraction if it’s bounding box.

Page 9: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4 CHAPTER 1. PYPLOT

If a ‘~matplotlib.transforms.Transform‘ object is passed

in use that to transform ‘‘xy‘‘ to screen coordinates

If a callable it must take a

‘~matplotlib.backend_bases.RendererBase‘ object as input

and return a ‘~matplotlib.transforms.Transform‘ or

‘~matplotlib.transforms.Bbox‘ object

If a ‘tuple‘ must be length 2 tuple of str, ‘Artist‘,

‘Transform‘ or callable objects. The first transform is

used for the *x* coordinate and the second for *y*.

See :ref:‘plotting-guide-annotation‘ for more details.

Defaults to ‘‘’data’‘‘

textcoords : str, Artist, Transform, callable or tuple, optional The coordi-nate system that xytext is given, which may be different than the coordinatesystem used for xy.

All ‘‘xycoords‘‘ values are valid as well as the following

strings:

================= =========================================

Property Description

================= =========================================

’offset points’ offset (in points) from the *xy* value

’offset pixels’ offset (in pixels) from the *xy* value

================= =========================================

defaults to the input of ‘‘xycoords‘‘

arrowprops : dict, optional If not None, properties used to draw a ~matplotlib.patches.FancyArrowPatcharrow between xy and xytext.

If ‘arrowprops‘ does not contain the key ‘‘’arrowstyle’‘‘ the

allowed keys are:

========== ======================================================

Key Description

========== ======================================================

width the width of the arrow in points

headwidth the width of the base of the arrow head in points

headlength the length of the arrow head in points

shrink fraction of total length to ’shrink’ from both ends

? any key to :class:‘matplotlib.patches.FancyArrowPatch‘

========== ======================================================

Page 10: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.4. PYPLOT.ANNOTATE 5

If the ‘arrowprops‘ contains the key ‘‘’arrowstyle’‘‘ the

above keys are forbidden. The allowed values of

‘‘’arrowstyle’‘‘ are:

============ =============================================

Name Attrs

============ =============================================

‘‘’-’‘‘ None

‘‘’->’‘‘ head_length=0.4,head_width=0.2

‘‘’-[’‘‘ widthB=1.0,lengthB=0.2,angleB=None

‘‘’|-|’‘‘ widthA=1.0,widthB=1.0

‘‘’-|>’‘‘ head_length=0.4,head_width=0.2

‘‘’<-’‘‘ head_length=0.4,head_width=0.2

‘‘’<->’‘‘ head_length=0.4,head_width=0.2

‘‘’<|-’‘‘ head_length=0.4,head_width=0.2

‘‘’<|-|>’‘‘ head_length=0.4,head_width=0.2

‘‘’fancy’‘‘ head_length=0.4,head_width=0.4,tail_width=0.4

‘‘’simple’‘‘ head_length=0.5,head_width=0.5,tail_width=0.2

‘‘’wedge’‘‘ tail_width=0.3,shrink_factor=0.5

============ =============================================

Valid keys for ‘~matplotlib.patches.FancyArrowPatch‘ are:

=============== ==================================================

Key Description

=============== ==================================================

arrowstyle the arrow style

connectionstyle the connection style

relpos default is (0.5, 0.5)

patchA default is bounding box of the text

patchB default is None

shrinkA default is 2 points

shrinkB default is 2 points

mutation_scale default is text size (in points)

mutation_aspect default is 1.

? any key for :class:‘matplotlib.patches.PathPatch‘

=============== ==================================================

Defaults to None

annotation clip : bool, optional Controls the visibility of the annotationwhen it goes outside the axes area.

If ‘True‘, the annotation will only be drawn when the

‘‘xy‘‘ is inside the axes. If ‘False‘, the annotation will

Page 11: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

6 CHAPTER 1. PYPLOT

always be drawn regardless of its position.

The default is ‘None‘, which behave as ‘True‘ only if

*xycoords* is "data".

1.4.2 Returns

Annotation

1.5 PyPlot.arrow

PyPlot.arrow — Method.Add an arrow to the axes.Draws arrow on specified axis from (x, y) to (x + dx, y + dy). Uses Fanc-

yArrow patch to construct the arrow.

1.5.1 Parameters

x : float X-coordinate of the arrow base y : float Y-coordinate of the arrow basedx : float Length of arrow along x-coordinate dy : float Length of arrow alongy-coordinate

1.5.2 Returns

a : FancyArrow patches.FancyArrow object

1.5.3 Other Parameters

Optional kwargs (inherited from FancyArrow patch) control the arrow construc-tion and properties:

Constructor arguments width: float (default: 0.001) width of full arrow taillength includes head : [True | False] (default: False) True if head is to be

counted in calculating the length.head width: float or None (default: 3*width) total width of the full arrow

headhead length: float or None (default: 1.5 * head width) length of arrow headshape: [‘full’, ‘left’, ‘right’] (default: ‘full’) draw the left-half, right-half, or

full arrowoverhang : float (default: 0) fraction that the arrow is swept back (0 overhang

means triangular shape). Can be negative or greater than one.head starts at zero: [True | False] (default: False) if True, the head starts

being drawn at coordinate 0 instead of ending at coordinate 0.Other valid kwargs (inherited from :class:Patch) are: agg filter: unknown

alpha: float or None animated: [True | False] antialiased or aa: [True | False]or None for default axes: an :class:~matplotlib.axes.Axes instance capstyle:[‘butt’ | ‘round’ | ‘projecting’] clip box: a :class:matplotlib.transforms.Bbox

Page 12: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.6. PYPLOT.AUTOSCALE 7

instance clip on: [True | False] clip path: [ (:class:~matplotlib.path.Path,:class:~matplotlib.transforms.Transform) | :class:~matplotlib.patches.Patch| None ] color: matplotlib color spec contains: a callable function edgecolor or ec:mpl color spec, None, ‘none’, or ‘auto’ facecolor or fc: mpl color spec, or Nonefor default, or ‘none’ for no color figure: a :class:matplotlib.figure.Figureinstance fill: [True | False] gid: an id string hatch: [‘/’ | ‘\’ | ‘|’ | ‘-’ | ‘+’ | ‘x’ |‘o’ | ‘O’ | ‘.’ | ’*’] joinstyle: [‘miter’ | ‘round’ | ‘bevel’] label: string or anythingprintable with ‘%s’ conversion. linestyle or ls: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dot-ted’ | (offset, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or lw: floator None for default path effects: unknown picker: [None|float|boolean|callable]rasterized: [True | False | None] sketch params: unknown snap: unknown trans-form: :class:~matplotlib.transforms.Transform instance url: a url stringvisible: [True | False] zorder: any number

1.5.4 Notes

The resulting arrow is affected by the axes aspect ratio and limits. This mayproduce an arrow whose head is not square with its stem. To create an arrowwhose head is square with its stem, use :meth:annotate for example::

ax.annotate("", xy=(0.5, 0.5), xytext=(0, 0),

arrowprops=dict(arrowstyle="->"))

1.5.5 Examples

.. plot:: mpl examples/pylab examples/arrow demo.py

1.6 PyPlot.autoscale

PyPlot.autoscale — Method.

Autoscale the axis view to the data (toggle).

Convenience method for simple axis view autoscaling. It turns autoscalingon or off, and then, if autoscaling for either axis is on, it performs the autoscalingon the specified axis or axes.

enable: [True | False | None] True (default) turns autoscaling on, False turnsit off. None leaves the autoscaling state unchanged.

axis: [‘x’ | ‘y’ | ‘both’] which axis to operate on; default is ‘both’

tight : [True | False | None] If True, set view limits to data limits; if False,let the locator and margins expand the view limits; if None, use tight scaling ifthe only artist is an image, otherwise treat tight as False. The tight setting isretained for future autoscaling until it is explicitly changed.

Returns None.

Page 13: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

8 CHAPTER 1. PYPLOT

1.7 PyPlot.autumn

PyPlot.autumn — Method.

set the default colormap to autumn and apply to current image if any.

See help(colormaps) for more information

1.8 PyPlot.axes

PyPlot.axes — Method.

Add an axes to the figure.

The axes is added at position *rect* specified by:

- ‘‘axes()‘‘ by itself creates a default full ‘‘subplot(111)‘‘ window axis.

- ‘‘axes(rect, facecolor=’w’)‘‘ where *rect* = [left, bottom, width,

height] in normalized (0, 1) units. *facecolor* is the background

color for the axis, default white.

- ‘‘axes(h)‘‘ where *h* is an axes instance makes *h* the current

axis. An :class:‘~matplotlib.axes.Axes‘ instance is returned.

========= ============== ==============================================

kwarg Accepts Description

========= ============== ==============================================

facecolor color the axes background color

frameon [True|False] display the frame?

sharex otherax current axes shares xaxis attribute

with otherax

sharey otherax current axes shares yaxis attribute

with otherax

polar [True|False] use a polar axes?

aspect [str | num] [’equal’, ’auto’] or a number. If a number

the ratio of x-unit/y-unit in screen-space.

Also see

:meth:‘~matplotlib.axes.Axes.set_aspect‘.

========= ============== ==============================================

Examples:

* :file:‘examples/pylab_examples/axes_demo.py‘ places custom axes.

* :file:‘examples/pylab_examples/shared_axis_demo.py‘ uses

*sharex* and *sharey*.

Page 14: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.9. PYPLOT.AXHLINE 9

1.9 PyPlot.axhline

PyPlot.axhline — Method.Add a horizontal line across the axis.

1.9.1 Parameters

y : scalar, optional, default: 0 y position in data coordinates of the horizontalline.

xmin : scalar, optional, default: 0 Should be between 0 and 1, 0 being thefar left of the plot, 1 the far right of the plot.

xmax : scalar, optional, default: 1 Should be between 0 and 1, 0 being thefar left of the plot, 1 the far right of the plot.

1.9.2 Returns

[]@l@ class:~matplotlib.lines.Line2DNotesNoteskwargs are passed to :class:~matplotlib.lines.Line2Dand can be usedto control the line properties.

1.9.3 Examples

• draw a thick red hline at ‘y’ = 0 that spans the xrange::

axhline(linewidth=4, color=‘r’)

• draw a default hline at ‘y’ = 1 that spans the xrange::

axhline(y=1)

• draw a default hline at ‘y’ = .5 that spans the middle half of the xrange::

axhline(y=.5, xmin=0.25, xmax=0.75)

Valid kwargs are :class:~matplotlib.lines.Line2D properties, with the ex-ception of ‘transform’:

agg filter: unknown alpha: float (0.0 transparent through 1.0 opaque) ani-mated: [True | False] antialiased or aa: [True | False] axes: an :class:~matplotlib.axes.Axesinstance clip box: a :class:matplotlib.transforms.Bbox instance clip on: [True| False] clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] color or c: any matplotlib colorcontains: a callable function dash capstyle: [‘butt’ | ‘round’ | ‘projecting’]dash joinstyle: [‘miter’ | ‘round’ | ‘bevel’] dashes: sequence of on/off ink inpoints drawstyle: [‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’] fig-ure: a :class:matplotlib.figure.Figure instance fillstyle: [‘full’ | ‘left’ | ‘right’| ‘bottom’ | ‘top’ | ‘none’] gid: an id string label: string or anything printablewith ‘%s’ conversion. linestyle or ls: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (off-set, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or lw: float value in

Page 15: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

10 CHAPTER 1. PYPLOT

points marker: :mod:A valid marker style <matplotlib.markers> mark-eredgecolor or mec: any matplotlib color markeredgewidth or mew: float valuein points markerfacecolor or mfc: any matplotlib color markerfacecoloralt ormfcalt: any matplotlib color markersize or ms: float markevery: [None | int |length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]path effects: unknown picker: float distance in points or callable pick func-tion fn(artist, event) pickradius: float distance in points rasterized: [True| False | None] sketch params: unknown snap: unknown solid capstyle: [‘butt’| ‘round’ | ‘projecting’] solid joinstyle: [‘miter’ | ‘round’ | ‘bevel’] transform:a :class:matplotlib.transforms.Transform instance url: a url string visible:[True | False] xdata: 1D array ydata: 1D array zorder: any number

1.9.4 See also

axhspan : for example plot and source code

1.10 PyPlot.axhspan

PyPlot.axhspan — Method.Add a horizontal span (rectangle) across the axis.Draw a horizontal span (rectangle) from ymin to ymax. With the default

values of xmin = 0 and xmax = 1, this always spans the xrange, regardlessof the xlim settings, even if you change them, e.g., with the :meth:set xlim

command. That is, the horizontal extent is in axes coords: 0=left, 0.5=middle,1.0=right but the y location is in data coordinates.

1.10.1 Parameters

ymin : float Lower limit of the horizontal span in data units. ymax : floatUpper limit of the horizontal span in data units. xmin : float, optional, default:0 Lower limit of the vertical span in axes (relative 0-1) units. xmax : float,optional, default: 1 Upper limit of the vertical span in axes (relative 0-1) units.

1.10.2 Returns

Polygon : ~matplotlib.patches.Polygon

1.10.3 Other Parameters

kwargs : ~matplotlib.patches.Polygon properties.agg filter: unknown alpha: float or None animated: [True | False] antialiased

or aa: [True | False] or None for default axes: an :class:~matplotlib.axes.Axesinstance capstyle: [‘butt’ | ‘round’ | ‘projecting’] clip box: a :class:matplotlib.transforms.Bboxinstance clip on: [True | False] clip path: [ (:class:~matplotlib.path.Path,:class:~matplotlib.transforms.Transform) | :class:~matplotlib.patches.Patch| None ] color: matplotlib color spec contains: a callable function edgecolor or ec:

Page 16: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.11. PYPLOT.AXIS 11

mpl color spec, None, ‘none’, or ‘auto’ facecolor or fc: mpl color spec, or Nonefor default, or ‘none’ for no color figure: a :class:matplotlib.figure.Figureinstance fill: [True | False] gid: an id string hatch: [‘/’ | ‘\’ | ‘|’ | ‘-’ | ‘+’ | ‘x’ |‘o’ | ‘O’ | ‘.’ | ’*’] joinstyle: [‘miter’ | ‘round’ | ‘bevel’] label: string or anythingprintable with ‘%s’ conversion. linestyle or ls: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dot-ted’ | (offset, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or lw: floator None for default path effects: unknown picker: [None|float|boolean|callable]rasterized: [True | False | None] sketch params: unknown snap: unknown trans-form: :class:~matplotlib.transforms.Transform instance url: a url stringvisible: [True | False] zorder: any number

1.10.4 See Also

axvspan : Add a vertical span (rectangle) across the axes.

1.10.5 Examples

.. plot:: mpl examples/pylab examples/axhspan demo.py

1.11 PyPlot.axis

PyPlot.axis — Method.

Convenience method to get or set axis properties.

Calling with no arguments::

>>> axis()

returns the current axes limits ‘‘[xmin, xmax, ymin, ymax]‘‘.::

>>> axis(v)

sets the min and max of the x and y axes, with

‘‘v = [xmin, xmax, ymin, ymax]‘‘.::

>>> axis(’off’)

turns off the axis lines and labels.::

>>> axis(’equal’)

changes limits of *x* or *y* axis so that equal increments of *x*

and *y* have the same length; a circle is circular.::

>>> axis(’scaled’)

Page 17: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

12 CHAPTER 1. PYPLOT

achieves the same result by changing the dimensions of the plot box instead

of the axis data limits.::

>>> axis(’tight’)

changes *x* and *y* axis limits such that all data is shown. If

all data is already shown, it will move it to the center of the

figure without modifying (*xmax* - *xmin*) or (*ymax* -

*ymin*). Note this is slightly different than in MATLAB.::

>>> axis(’image’)

is ’scaled’ with the axis limits equal to the data limits.::

>>> axis(’auto’)

and::

>>> axis(’normal’)

are deprecated. They restore default behavior; axis limits are automatically

scaled to make the data fit comfortably within the plot box.

if ‘‘len(*v)==0‘‘, you can pass in *xmin*, *xmax*, *ymin*, *ymax*

as kwargs selectively to alter just those limits without changing

the others.

>>> axis(’square’)

changes the limit ranges (*xmax*-*xmin*) and (*ymax*-*ymin*) of

the *x* and *y* axes to be the same, and have the same scaling,

resulting in a square plot.

The xmin, xmax, ymin, ymax tuple is returned

.. seealso::

:func:‘xlim‘, :func:‘ylim‘

For setting the x- and y-limits individually.

1.12 PyPlot.axvline

PyPlot.axvline — Method.

Add a vertical line across the axes.

Page 18: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.12. PYPLOT.AXVLINE 13

1.12.1 Parameters

x : scalar, optional, default: 0 x position in data coordinates of the vertical line.ymin : scalar, optional, default: 0 Should be between 0 and 1, 0 being the

bottom of the plot, 1 the top of the plot.ymax : scalar, optional, default: 1 Should be between 0 and 1, 0 being the

bottom of the plot, 1 the top of the plot.

1.12.2 Returns

[]@l@ class:~matplotlib.lines.Line2DExamplesExamples* draw a thick redvline at x = 0 that spans the yrange::

>>> axvline(linewidth=4, color=’r’)

• draw a default vline at x = 1 that spans the yrange::

axvline(x=1)

• draw a default vline at x = .5 that spans the middle half of the yrange::

axvline(x=.5, ymin=0.25, ymax=0.75)

Valid kwargs are :class:~matplotlib.lines.Line2D properties, with the ex-ception of ‘transform’:

agg filter: unknown alpha: float (0.0 transparent through 1.0 opaque) ani-mated: [True | False] antialiased or aa: [True | False] axes: an :class:~matplotlib.axes.Axesinstance clip box: a :class:matplotlib.transforms.Bbox instance clip on: [True| False] clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] color or c: any matplotlib colorcontains: a callable function dash capstyle: [‘butt’ | ‘round’ | ‘projecting’]dash joinstyle: [‘miter’ | ‘round’ | ‘bevel’] dashes: sequence of on/off ink inpoints drawstyle: [‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’] fig-ure: a :class:matplotlib.figure.Figure instance fillstyle: [‘full’ | ‘left’ | ‘right’| ‘bottom’ | ‘top’ | ‘none’] gid: an id string label: string or anything printablewith ‘%s’ conversion. linestyle or ls: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (off-set, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or lw: float value inpoints marker: :mod:A valid marker style <matplotlib.markers> mark-eredgecolor or mec: any matplotlib color markeredgewidth or mew: float valuein points markerfacecolor or mfc: any matplotlib color markerfacecoloralt ormfcalt: any matplotlib color markersize or ms: float markevery: [None | int |length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]path effects: unknown picker: float distance in points or callable pick func-tion fn(artist, event) pickradius: float distance in points rasterized: [True| False | None] sketch params: unknown snap: unknown solid capstyle: [‘butt’| ‘round’ | ‘projecting’] solid joinstyle: [‘miter’ | ‘round’ | ‘bevel’] transform:a :class:matplotlib.transforms.Transform instance url: a url string visible:[True | False] xdata: 1D array ydata: 1D array zorder: any number

Page 19: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

14 CHAPTER 1. PYPLOT

1.12.3 See also

axhspan : for example plot and source code

1.13 PyPlot.axvspan

PyPlot.axvspan — Method.

Add a vertical span (rectangle) across the axes.

Draw a vertical span (rectangle) from xmin to xmax. With the default valuesof ymin = 0 and ymax = 1. This always spans the yrange, regardless of the ylimsettings, even if you change them, e.g., with the :meth:set ylim command.That is, the vertical extent is in axes coords: 0=bottom, 0.5=middle, 1.0=topbut the y location is in data coordinates.

1.13.1 Parameters

xmin : scalar Number indicating the first X-axis coordinate of the vertical spanrectangle in data units. xmax : scalar Number indicating the second X-axiscoordinate of the vertical span rectangle in data units. ymin : scalar, optionalNumber indicating the first Y-axis coordinate of the vertical span rectanglein relative Y-axis units (0-1). Default to 0. ymax : scalar, optional Numberindicating the second Y-axis coordinate of the vertical span rectangle in relativeY-axis units (0-1). Default to 1.

1.13.2 Returns

rectangle : matplotlib.patches.Polygon Vertical span (rectangle) from (xmin,ymin) to (xmax, ymax).

1.13.3 Other Parameters

**kwargs Optional parameters are properties of the class matplotlib.patches.Polygon.

1.13.4 See Also

axhspan

1.13.5 Examples

Draw a vertical, green, translucent rectangle from x = 1.25 to x = 1.55 thatspans the yrange of the axes.

axvspan(1.25, 1.55, facecolor=‘g’, alpha=0.5)

Page 20: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.14. PYPLOT.BAR 15

1.14 PyPlot.bar

PyPlot.bar — Method.

Make a bar plot.

Make a bar plot with rectangles bounded by:

left, left + width, bottom, bottom + height (left, right, bottom and topedges)

1.14.1 Parameters

left : sequence of scalars the x coordinates of the left sides of the bars

height : sequence of scalars the heights of the bars

width : scalar or array-like, optional the width(s) of the bars default: 0.8

bottom : scalar or array-like, optional the y coordinate(s) of the bars default:None

color : scalar or array-like, optional the colors of the bar faces

edgecolor : scalar or array-like, optional the colors of the bar edges

linewidth : scalar or array-like, optional width of bar edge(s). If None, usedefault linewidth; If 0, don’t draw edges. default: None

tick label : string or array-like, optional the tick labels of the bars default:None

xerr : scalar or array-like, optional if not None, will be used to generateerrorbar(s) on the bar chart default: None

yerr : scalar or array-like, optional if not None, will be used to generateerrorbar(s) on the bar chart default: None

ecolor : scalar or array-like, optional specifies the color of errorbar(s) default:None

capsize : scalar, optional determines the length in points of the error barcaps default: None, which will take the value from the errorbar.capsize

:data:rcParam<matplotlib.rcParams>.

error kw : dict, optional dictionary of kwargs to be passed to errorbarmethod. ecolor and capsize may be specified here rather than as independentkwargs.

align : {‘center’, ‘edge’}, optional If ‘edge’, aligns bars by their left edges(for vertical bars) and by their bottom edges (for horizontal bars). If ‘center’,interpret the left argument as the coordinates of the centers of the bars. Toalign on the align bars on the right edge pass a negative width.

orientation : {‘vertical’, ‘horizontal’}, optional The orientation of the bars.

log : boolean, optional If true, sets the axis to be log scale. default: False

1.14.2 Returns

bars : matplotlib.container.BarContainer Container with all of the bars + er-rorbars

Page 21: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

16 CHAPTER 1. PYPLOT

1.14.3 Notes

The optional arguments color, edgecolor, linewidth, xerr, and yerr can beeither scalars or sequences of length equal to the number of bars. This enablesyou to use bar as the basis for stacked bar charts, or candlestick plots. Detail:xerr and yerr are passed directly to :meth:errorbar, so they can also haveshape 2xN for independent specification of lower and upper errors.

Other optional kwargs:agg filter: unknown alpha: float or None animated: [True | False] antialiased

or aa: [True | False] or None for default axes: an :class:~matplotlib.axes.Axesinstance capstyle: [‘butt’ | ‘round’ | ‘projecting’] clip box: a :class:matplotlib.transforms.Bboxinstance clip on: [True | False] clip path: [ (:class:~matplotlib.path.Path,:class:~matplotlib.transforms.Transform) | :class:~matplotlib.patches.Patch| None ] color: matplotlib color spec contains: a callable function edgecolor or ec:mpl color spec, None, ‘none’, or ‘auto’ facecolor or fc: mpl color spec, or Nonefor default, or ‘none’ for no color figure: a :class:matplotlib.figure.Figureinstance fill: [True | False] gid: an id string hatch: [‘/’ | ‘\’ | ‘|’ | ‘-’ | ‘+’ | ‘x’ |‘o’ | ‘O’ | ‘.’ | ’*’] joinstyle: [‘miter’ | ‘round’ | ‘bevel’] label: string or anythingprintable with ‘%s’ conversion. linestyle or ls: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dot-ted’ | (offset, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or lw: floator None for default path effects: unknown picker: [None|float|boolean|callable]rasterized: [True | False | None] sketch params: unknown snap: unknown trans-form: :class:~matplotlib.transforms.Transform instance url: a url stringvisible: [True | False] zorder: any number

1.14.4 See also

barh: Plot a horizontal bar plot.

1.14.5 Examples

Example: A stacked bar chart... plot:: mpl examples/pylab examples/bar stacked.py.. note:: In addition to the above described arguments, this function can

take a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All arguments with the following names: ’bottom’, ’color’, ’ecolor’, ’edgecolor’, ’height’, ’left’, ’linewidth’, ’tick_label’, ’width’, ’xerr’, ’yerr’.

1.15 PyPlot.bar3D

PyPlot.bar3D — Method.

Generate a 3D bar, or multiple bars.

When generating multiple bars, x, y, z have to be arrays.

Page 22: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.16. PYPLOT.BARBS 17

dx, dy, dz can be arrays or scalars.

*color* can be:

- A single color value, to color all bars the same color.

- An array of colors of length N bars, to color each bar

independently.

- An array of colors of length 6, to color the faces of the

bars similarly.

- An array of colors of length 6 * N bars, to color each face

independently.

When coloring the faces of the boxes specifically, this is

the order of the coloring:

1. -Z (bottom of box)

2. +Z (top of box)

3. -Y

4. +Y

5. -X

6. +X

Keyword arguments are passed onto

:func:‘~mpl_toolkits.mplot3d.art3d.Poly3DCollection‘

1.16 PyPlot.barbs

PyPlot.barbs — Method.Plot a 2-D field of barbs.Call signatures::barb(U, V, kw) barb(U, V, C, kw) barb(X, Y, U, V, kw) barb(X, Y,

U, V, C, kw)Arguments:X, Y : The x and y coordinates of the barb locations (default is head of barb;

see pivot kwarg)U, V : Give the x and y components of the barb shaftC : An optional array used to map colors to the barbsAll arguments may be 1-D or 2-D arrays or sequences. If X and Y are

absent, they will be generated as a uniform grid. If U and V are 2-D arraysbut X and Y are 1-D, and if len(X) and len(Y) match the column and rowdimensions of U, then X and Y will be expanded with :func:numpy.meshgrid.

Page 23: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

18 CHAPTER 1. PYPLOT

U, V, C may be masked arrays, but masked X, Y are not supported atpresent.

Keyword arguments:

length: Length of the barb in points; the other parts of the barb are scaledagainst this. Default is 9

pivot : [ ‘tip’ | ‘middle’ ] The part of the arrow that is at the grid point; thearrow rotates about this point, hence the name pivot. Default is ‘tip’

barbcolor : [ color | color sequence ] Specifies the color all parts of the barbexcept any flags. This parameter is analagous to the edgecolor parameter forpolygons, which can be used instead. However this parameter will overridefacecolor.

flagcolor : [ color | color sequence ] Specifies the color of any flags on the barb.This parameter is analagous to the facecolor parameter for polygons, which canbe used instead. However this parameter will override facecolor. If this is notset (and C has not either) then flagcolor will be set to match barbcolor so thatthe barb has a uniform color. If C has been set, flagcolor has no effect.

sizes: A dictionary of coefficients specifying the ratio of a given feature tothe length of the barb. Only those values one wishes to override need to beincluded. These features include:

- ’spacing’ - space between features (flags, full/half barbs)

- ’height’ - height (distance from shaft to top) of a flag or

full barb

- ’width’ - width of a flag, twice the width of a full barb

- ’emptybarb’ - radius of the circle used for low magnitudes

fill empty : A flag on whether the empty barbs (circles) that are drawn shouldbe filled with the flag color. If they are not filled, they will be drawn such thatno color is applied to the center. Default is False

rounding : A flag to indicate whether the vector magnitude should be roundedwhen allocating barb components. If True, the magnitude is rounded to thenearest multiple of the half-barb increment. If False, the magnitude is simplytruncated to the next lowest multiple. Default is True

barb increments: A dictionary of increments specifying values to associatewith different parts of the barb. Only those values one wishes to override needto be included.

- ’half’ - half barbs (Default is 5)

- ’full’ - full barbs (Default is 10)

- ’flag’ - flags (default is 50)

Page 24: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.16. PYPLOT.BARBS 19

flip barb: Either a single boolean flag or an array of booleans. Single booleanindicates whether the lines and flags should point opposite to normal for allbarbs. An array (which should be the same size as the other data arrays)indicates whether to flip for each individual barb. Normal behavior is for thebarbs and lines to point right (comes from wind barbs having these featurespoint towards low pressure in the Northern Hemisphere.) Default is False

Barbs are traditionally used in meteorology as a way to plot the speed anddirection of wind observations, but can technically be used to plot any twodimensional vector quantity. As opposed to arrows, which give vector magnitudeby the length of the arrow, the barbs give more quantitative information aboutthe vector magnitude by putting slanted lines or a triangle for various incrementsin magnitude, as show schematically below::

//

.. note the double at the end of each line to make the figure .. rendercorrectly

The largest increment is given by a triangle (or “flag”). After those comefull lines (barbs). The smallest increment is a half line. There is only, of course,ever at most 1 half line. If the magnitude is small and only needs a single half-line and no full lines or triangles, the half-line is offset from the end of the barbso that it can be easily distinguished from barbs with a single full line. Themagnitude for the barb shown above would nominally be 65, using the standardincrements of 50, 10, and 5.

linewidths and edgecolors can be used to customize the barb. Additional:class:~matplotlib.collections.PolyCollection keyword arguments:

agg filter: unknown alpha: float or None animated: [True | False] an-tialiased or antialiaseds: Boolean or sequence of booleans array: unknown axes:an :class:~matplotlib.axes.Axes instance clim: a length 2 sequence of floatsclip box: a :class:matplotlib.transforms.Bbox instance clip on: [True | False]clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] cmap: a colormap or registeredcolormap name color: matplotlib color arg or sequence of rgba tuples contains:a callable function edgecolor or edgecolors: matplotlib color spec or sequence ofspecs facecolor or facecolors: matplotlib color spec or sequence of specs figure: a:class:matplotlib.figure.Figure instance gid: an id string hatch: [ ‘/’ | ‘\’ | ‘|’| ‘-’ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ’*’ ] label: string or anything printable with ‘%s’ con-version. linestyle or dashes or linestyles: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ |(offset, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or linewidths or lw:float or sequence of floats norm: unknown offset position: unknown offsets: floator sequence of floats path effects: unknown picker: [None|float|boolean|callable]pickradius: unknown rasterized: [True | False | None] sketch params: un-known snap: unknown transform: :class:~matplotlib.transforms.Transforminstance url: a url string urls: unknown visible: [True | False] zorder: anynumber

Page 25: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

20 CHAPTER 1. PYPLOT

Example:.. plot:: mpl examples/pylab examples/barb demo.py.. note:: In addition to the above described arguments, this function can

take a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All positional and all keyword arguments.

1.17 PyPlot.barh

PyPlot.barh — Method.Make a horizontal bar plot.Make a horizontal bar plot with rectangles bounded by:left, left + width, bottom, bottom + height (left, right, bottom and top

edges)bottom, width, height, and left can be either scalars or sequences

1.17.1 Parameters

bottom : scalar or array-like the y coordinate(s) of the barswidth : scalar or array-like the width(s) of the barsheight : sequence of scalars, optional, default: 0.8 the heights of the barsleft : sequence of scalars the x coordinates of the left sides of the bars

1.17.2 Returns

matplotlib.patches.Rectangle instances.

1.17.3 Other parameters

color : scalar or array-like, optional the colors of the barsedgecolor : scalar or array-like, optional the colors of the bar edgeslinewidth : scalar or array-like, optional, default: None width of bar edge(s).

If None, use default linewidth; If 0, don’t draw edges.tick label : string or array-like, optional, default: None the tick labels of the

barsxerr : scalar or array-like, optional, default: None if not None, will be used

to generate errorbar(s) on the bar chartyerr : scalar or array-like, optional, default: None if not None, will be used

to generate errorbar(s) on the bar chartecolor : scalar or array-like, optional, default: None specifies the color of

errorbar(s)capsize : scalar, optional determines the length in points of the error bar

caps default: None, which will take the value from the errorbar.capsize

:data:rcParam<matplotlib.rcParams>.

Page 26: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.18. PYPLOT.BONE 21

error kw : dictionary of kwargs to be passed to errorbar method. ecolor

and capsize may be specified here rather than as independent kwargs.

align : {‘center’, ‘edge’}, optional If ‘edge’, aligns bars by their left edges(for vertical bars) and by their bottom edges (for horizontal bars). If ‘center’,interpret the bottom argument as the coordinates of the centers of the bars. Toalign on the align bars on the top edge pass a negative ‘height’.

log : boolean, optional, default: False If true, sets the axis to be log scale

1.17.4 Notes

The optional arguments color, edgecolor, linewidth, xerr, and yerr can beeither scalars or sequences of length equal to the number of bars. This enablesyou to use bar as the basis for stacked bar charts, or candlestick plots. Detail:xerr and yerr are passed directly to :meth:errorbar, so they can also haveshape 2xN for independent specification of lower and upper errors.

Other optional kwargs:

agg filter: unknown alpha: float or None animated: [True | False] antialiasedor aa: [True | False] or None for default axes: an :class:~matplotlib.axes.Axesinstance capstyle: [‘butt’ | ‘round’ | ‘projecting’] clip box: a :class:matplotlib.transforms.Bboxinstance clip on: [True | False] clip path: [ (:class:~matplotlib.path.Path,:class:~matplotlib.transforms.Transform) | :class:~matplotlib.patches.Patch| None ] color: matplotlib color spec contains: a callable function edgecolor or ec:mpl color spec, None, ‘none’, or ‘auto’ facecolor or fc: mpl color spec, or Nonefor default, or ‘none’ for no color figure: a :class:matplotlib.figure.Figureinstance fill: [True | False] gid: an id string hatch: [‘/’ | ‘\’ | ‘|’ | ‘-’ | ‘+’ | ‘x’ |‘o’ | ‘O’ | ‘.’ | ’*’] joinstyle: [‘miter’ | ‘round’ | ‘bevel’] label: string or anythingprintable with ‘%s’ conversion. linestyle or ls: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dot-ted’ | (offset, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or lw: floator None for default path effects: unknown picker: [None|float|boolean|callable]rasterized: [True | False | None] sketch params: unknown snap: unknown trans-form: :class:~matplotlib.transforms.Transform instance url: a url stringvisible: [True | False] zorder: any number

1.17.5 See also

bar: Plot a vertical bar plot.

1.18 PyPlot.bone

PyPlot.bone — Method.

set the default colormap to bone and apply to current image if any.

See help(colormaps) for more information

Page 27: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

22 CHAPTER 1. PYPLOT

1.19 PyPlot.box

PyPlot.box — Method.

Turn the axes box on or off. *on* may be a boolean or a string,

’on’ or ’off’.

If *on* is *None*, toggle state.

1.20 PyPlot.boxplot

PyPlot.boxplot — Method.Make a box and whisker plot.Make a box and whisker plot for each column of x or each vector in sequence

x. The box extends from the lower to upper quartile values of the data, with aline at the median. The whiskers extend from the box to show the range of thedata. Flier points are those past the end of the whiskers.

1.20.1 Parameters

x : Array or a sequence of vectors. The input data.notch : bool, optional (False) If True, will produce a notched box plot. Oth-

erwise, a rectangular boxplot is produced. The notches represent the confidenceinterval (CI) around the median. See the entry for the bootstrap parameterfor information regarding how the locations of the notches are computed.

.. note::

In cases where the values of the CI are less than the

lower quartile or greater than the upper quartile, the

notches will extend beyond the box, giving it a

distinctive "flipped" appearance. This is expected

behavior and consistent with other statistical

visualization packages.

sym : str, optional The default symbol for flier points. Enter an emptystring (‘’) if you don’t want to show fliers. If None, then the fliers default to’b+’ If you want more control use the flierprops kwarg.

vert : bool, optional (True) If True (default), makes the boxes vertical. IfFalse, everything is drawn horizontally.

whis : float, sequence, or string (default = 1.5) As a float, determines thereach of the whiskers past the first and third quartiles (e.g., Q3 + whis*IQR,IQR = interquartile range, Q3-Q1). Beyond the whiskers, data are consideredoutliers and are plotted as individual points. Set this to an unreasonably highvalue to force the whiskers to show the min and max values. Alternatively, setthis to an ascending sequence of percentile (e.g., [5, 95]) to set the whiskers at

Page 28: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.20. PYPLOT.BOXPLOT 23

specific percentiles of the data. Finally, whis can be the string range to forcethe whiskers to the min and max of the data.

bootstrap : int, optional Specifies whether to bootstrap the confidence in-tervals around the median for notched boxplots. If bootstrap is None, nobootstrapping is performed, and notches are calculated using a Gaussian-basedasymptotic approximation (see McGill, R., Tukey, J.W., and Larsen, W.A.,1978, and Kendall and Stuart, 1967). Otherwise, bootstrap specifies the num-ber of times to bootstrap the median to determine its 95% confidence intervals.Values between 1000 and 10000 are recommended.

usermedians : array-like, optional An array or sequence whose first dimen-sion (or length) is compatible with x. This overrides the medians computed bymatplotlib for each element of usermedians that is not None. When an elementof usermedians is None, the median will be computed by matplotlib as normal.

conf intervals : array-like, optional Array or sequence whose first dimen-sion (or length) is compatible with x and whose second dimension is 2. Whenthe an element of conf intervals is not None, the notch locations computedby matplotlib are overridden (provided notch is True). When an element ofconf intervals is None, the notches are computed by the method specified bythe other kwargs (e.g., bootstrap).

positions : array-like, optional Sets the positions of the boxes. The ticks andlimits are automatically set to match the positions. Defaults to range(1, N+1)

where N is the number of boxes to be drawn.widths : scalar or array-like Sets the width of each box either with a scalar

or a sequence. The default is 0.5, or 0.15*(distance between extreme

positions), if that is smaller.patch artist : bool, optional (False) If False produces boxes with the Line2D

artist. Otherwise, boxes and drawn with Patch artists.labels : sequence, optional Labels for each dataset. Length must be com-

patible with dimensions of x.manage xticks : bool, optional (True) If the function should adjust the xlim

and xtick locations.autorange : bool, optional (False) When True and the data are distributed

such that the 25th and 75th percentiles are equal, whis is set to range suchthat the whisker ends are at the minimum and maximum of the data.

meanline : bool, optional (False) If True (and showmeans is True), willtry to render the mean as a line spanning the full width of the box accordingto meanprops (see below). Not recommended if shownotches is also True.Otherwise, means will be shown as points.

zorder : scalar, optional (None) Sets the zorder of the boxplot.

1.20.2 Other Parameters

showcaps : bool, optional (True) Show the caps on the ends of whiskers. show-box : bool, optional (True) Show the central box. showfliers : bool, optional(True) Show the outliers beyond the caps. showmeans : bool, optional (False)Show the arithmetic means. capprops : dict, optional (None) Specifies the style

Page 29: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

24 CHAPTER 1. PYPLOT

of the caps. boxprops : dict, optional (None) Specifies the style of the box.whiskerprops : dict, optional (None) Specifies the style of the whiskers. flier-props : dict, optional (None) Specifies the style of the fliers. medianprops : dict,optional (None) Specifies the style of the median. meanprops : dict, optional(None) Specifies the style of the mean.

1.20.3 Returns

result : dict A dictionary mapping each component of the boxplot to a list ofthe :class:matplotlib.lines.Line2D instances created. That dictionary hasthe following keys (assuming vertical boxplots):

• boxes: the main body of the boxplot showing the quartiles and the me-dian’s confidence intervals if enabled.

• medians: horizontal lines at the median of each box.

• whiskers: the vertical lines extending to the most extreme, non-outlierdata points.

• caps: the horizontal lines at the ends of the whiskers.

• fliers: points representing data that extend beyond the whiskers (fliers).

• means: points or lines representing the means.

1.20.4 Examples

.. plot:: mpl examples/statistics/boxplot demo.py.. note:: In addition to the above described arguments, this function can

take a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All positional and all keyword arguments.

1.21 PyPlot.broken barh

PyPlot.broken barh — Method.Plot horizontal bars.A collection of horizontal bars spanning yrange with a sequence of xranges.Required arguments:========= ============================== Argu-

ment Description ========= ==============================xranges sequence of (xmin, xwidth) yrange sequence of (ymin, ywidth) =======================================

kwargs are :class:matplotlib.collections.BrokenBarHCollection prop-erties:

Page 30: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.22. PYPLOT.CLA 25

agg filter: unknown alpha: float or None animated: [True | False] an-tialiased or antialiaseds: Boolean or sequence of booleans array: unknown axes:an :class:~matplotlib.axes.Axes instance clim: a length 2 sequence of floatsclip box: a :class:matplotlib.transforms.Bbox instance clip on: [True | False]clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] cmap: a colormap or registeredcolormap name color: matplotlib color arg or sequence of rgba tuples contains:a callable function edgecolor or edgecolors: matplotlib color spec or sequence ofspecs facecolor or facecolors: matplotlib color spec or sequence of specs figure: a:class:matplotlib.figure.Figure instance gid: an id string hatch: [ ‘/’ | ‘\’ | ‘|’| ‘-’ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ’*’ ] label: string or anything printable with ‘%s’ con-version. linestyle or dashes or linestyles: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ |(offset, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or linewidths or lw:float or sequence of floats norm: unknown offset position: unknown offsets: floator sequence of floats path effects: unknown picker: [None|float|boolean|callable]pickradius: unknown rasterized: [True | False | None] sketch params: un-known snap: unknown transform: :class:~matplotlib.transforms.Transforminstance url: a url string urls: unknown visible: [True | False] zorder: anynumber

these can either be a single argument, i.e.,::facecolors = ‘black’or a sequence of arguments for the various bars, i.e.,::facecolors = (‘black’, ‘red’, ‘green’)Example:.. plot:: mpl examples/pylab examples/broken barh.py.. note:: In addition to the above described arguments, this function can

take a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All positional and all keyword arguments.

1.22 PyPlot.cla

PyPlot.cla — Method.Clear the current axes.

1.23 PyPlot.clabel

PyPlot.clabel — Method.Label a contour plot.Call signature::clabel(cs, **kwargs)Adds labels to line contours in cs, where cs is a :class:~matplotlib.contour.ContourSet

object returned by contour.::

Page 31: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

26 CHAPTER 1. PYPLOT

clabel(cs, v, **kwargs)only labels contours listed in v.Optional keyword arguments:fontsize: size in points or relative size e.g., ‘smaller’, ‘x-large’colors: - if None, the color of each label matches the color of the correspond-

ing contour

- if one string color, e.g., *colors* = ’r’ or *colors* =

’red’, all labels will be plotted in this color

- if a tuple of matplotlib color args (string, float, rgb, etc),

different labels will be plotted in different colors in the order

specified

inline: controls whether the underlying contour is removed or not. Defaultis True.

inline spacing : space in pixels to leave on each side of label when placinginline. Defaults to 5. This spacing will be exact for labels at locations wherethe contour is straight, less so for labels on curved contours.

fmt : a format string for the label. Default is ‘%1.3f’ Alternatively, thiscan be a dictionary matching contour levels with arbitrary strings to use foreach contour level (i.e., fmt[level]=string), or it can be any callable, such asa :class:~matplotlib.ticker.Formatter instance, that returns a string whencalled with a numeric contour level.

manual : if True, contour labels will be placed manually using mouse clicks.Click the first button near a contour to add a label, click the second button(or potentially both mouse buttons at once) to finish adding labels. The thirdbutton can be used to remove the last label added, but only if labels are notinline. Alternatively, the keyboard can be used to select label locations (enterto end label placement, delete or backspace act like the third mouse button, andany other key will select a label location).

*manual* can be an iterable object of x,y tuples. Contour labels

will be created as if mouse is clicked at each x,y positions.

rightside up: if True (default), label rotations will always be plus or minus90 degrees from level.

use clabeltext : if True (default is False), ClabelText class (instead of mat-plotlib.Text) is used to create labels. ClabelText recalculates rotation angles oftexts during the drawing time, therefore this can be used if aspect of the axeschanges.

.. plot:: mpl examples/pylab examples/contour demo.py

1.24 PyPlot.clf

PyPlot.clf — Method.

Clear the current figure.

Page 32: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.25. PYPLOT.CLIM 27

1.25 PyPlot.clim

PyPlot.clim — Method.

Set the color limits of the current image.

To apply clim to all axes images do::

clim(0, 0.5)

If either *vmin* or *vmax* is None, the image min/max respectively

will be used for color scaling.

If you want to set the clim of multiple images,

use, for example::

for im in gca().get_images():

im.set_clim(0, 0.05)

1.26 PyPlot.cohere

PyPlot.cohere — Method.Plot the coherence between x and y.Plot the coherence between x and y. Coherence is the normalized cross

spectral density:.. math::C {xy} = —Pxy|2 PxxPyy

1.26.1 Parameters

Fs : scalar The sampling frequency (samples per time unit). It is used tocalculate the Fourier frequencies, freqs, in cycles per time unit. The defaultvalue is 2.

window : callable or ndarray A function or a vector of length NFFT. To cre-ate window vectors see :func:window hanning, :func:window none, :func:numpy.blackman,:func:numpy.hamming, :func:numpy.bartlett, :func:scipy.signal, :func:scipy.signal.get window,etc. The default is :func:window hanning. If a function is passed as the argu-ment, it must take a data segment as an argument and return the windowedversion of the segment.

sides : [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the spec-trum to return. Default gives the default behavior, which returns one-sided forreal data and both for complex data. ‘onesided’ forces the return of a one-sidedspectrum, while ‘twosided’ forces two-sided.

pad to : integer The number of points to which the data segment is paddedwhen performing the FFT. This can be different from NFFT, which specifiesthe number of data points used. While not increasing the actual resolution of

Page 33: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

28 CHAPTER 1. PYPLOT

the spectrum (the minimum distance between resolvable peaks), this can givemore points in the plot, allowing for more detail. This corresponds to the nparameter in the call to fft(). The default is None, which sets pad to equal toNFFT

NFFT : integer The number of data points used in each block for the FFT.A power 2 is most efficient. The default value is 256. This should NOT be usedto get zero padding, or the scaling of the result will be incorrect. Use pad to forthis instead.

detrend : {‘default’, ‘constant’, ‘mean’, ‘linear’, ‘none’} or callable The func-tion applied to each segment before fft-ing, designed to remove the mean orlinear trend. Unlike in MATLAB, where the detrend parameter is a vector,in matplotlib is it a function. The :mod:~matplotlib.pylab module defines:func:~matplotlib.pylab.detrend none, :func:~matplotlib.pylab.detrend mean,and :func:~matplotlib.pylab.detrend linear, but you can use a custom func-tion as well. You can also use a string to choose one of the functions. ‘default’,‘constant’, and ‘mean’ call :func:~matplotlib.pylab.detrend mean. ‘linear’calls :func:~matplotlib.pylab.detrend linear. ‘none’ calls :func:~matplotlib.pylab.detrend none.

scale by freq : boolean, optional Specifies whether the resulting density val-ues should be scaled by the scaling frequency, which gives density in units ofHzˆ-1. This allows for integration over the returned frequency values. Thedefault is True for MATLAB compatibility.

noverlap : integer The number of points of overlap between blocks. Thedefault value is 0 (no overlap).

Fc : integer The center frequency of x (defaults to 0), which offsets the xextents of the plot to reflect the frequency range used when a signal is acquiredand then filtered and downsampled to baseband.

**kwargs : Keyword arguments control the :class:~matplotlib.lines.Line2Dproperties of the coherence plot:

agg filter: unknown alpha: float (0.0 transparent through 1.0 opaque) ani-mated: [True | False] antialiased or aa: [True | False] axes: an :class:~matplotlib.axes.Axesinstance clip box: a :class:matplotlib.transforms.Bbox instance clip on: [True| False] clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] color or c: any matplotlib colorcontains: a callable function dash capstyle: [‘butt’ | ‘round’ | ‘projecting’]dash joinstyle: [‘miter’ | ‘round’ | ‘bevel’] dashes: sequence of on/off ink inpoints drawstyle: [‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’] fig-ure: a :class:matplotlib.figure.Figure instance fillstyle: [‘full’ | ‘left’ | ‘right’| ‘bottom’ | ‘top’ | ‘none’] gid: an id string label: string or anything printablewith ‘%s’ conversion. linestyle or ls: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (off-set, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or lw: float value inpoints marker: :mod:A valid marker style <matplotlib.markers> mark-eredgecolor or mec: any matplotlib color markeredgewidth or mew: float valuein points markerfacecolor or mfc: any matplotlib color markerfacecoloralt ormfcalt: any matplotlib color markersize or ms: float markevery: [None | int |length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]path effects: unknown picker: float distance in points or callable pick func-

Page 34: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.27. PYPLOT.COLORBAR 29

tion fn(artist, event) pickradius: float distance in points rasterized: [True| False | None] sketch params: unknown snap: unknown solid capstyle: [‘butt’| ‘round’ | ‘projecting’] solid joinstyle: [‘miter’ | ‘round’ | ‘bevel’] transform:a :class:matplotlib.transforms.Transform instance url: a url string visible:[True | False] xdata: 1D array ydata: 1D array zorder: any number

1.26.2 Returns

The return value is a tuple (Cxy, f ), where f are the frequencies of the coherencevector.

kwargs are applied to the lines.

1.26.3 References

Bendat & Piersol – Random Data: Analysis and Measurement Procedures, JohnWiley & Sons (1986)

1.26.4 Examples

.. plot:: mpl examples/pylab examples/cohere demo.py.. note:: In addition to the above described arguments, this function can

take a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All arguments with the following names: ’x’, ’y’.

1.27 PyPlot.colorbar

PyPlot.colorbar — Method.Add a colorbar to a plot.Function signatures for the :mod:~matplotlib.pyplot interface; all but the

first are also method signatures for the :meth:~matplotlib.figure.Figure.colorbarmethod::

colorbar(kwargs) colorbar(mappable, kwargs) colorbar(mappable, cax=cax,kwargs) colorbar(mappable, ax=ax, kwargs)

arguments:mappable the :class:~matplotlib.image.Image, :class:~matplotlib.contour.ContourSet,

etc. to which the colorbar applies; this argument is mandatory for the :meth:~matplotlib.figure.Figure.colorbarmethod but optional for the :func:~matplotlib.pyplot.colorbar function,which sets the default to the current image.

keyword arguments:cax None | axes object into which the colorbar will be drawn ax None |

parent axes object(s) from which space for a new colorbar axes will be stolen.If a list of axes is given they will all be resized to make room for the colorbaraxes. use gridspec False | If cax is None, a new cax is created as an instance of

Page 35: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

30 CHAPTER 1. PYPLOT

Axes. If ax is an instance of Subplot and use gridspec is True, cax is created asan instance of Subplot using the grid spec module.

Additional keyword arguments are of two kinds:axes properties:

============= ====================================================

Property Description

============= ====================================================

*orientation* vertical or horizontal

*fraction* 0.15; fraction of original axes to use for colorbar

*pad* 0.05 if vertical, 0.15 if horizontal; fraction

of original axes between colorbar and new image axes

*shrink* 1.0; fraction by which to shrink the colorbar

*aspect* 20; ratio of long to short dimensions

*anchor* (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal;

the anchor point of the colorbar axes

*panchor* (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal;

the anchor point of the colorbar parent axes. If

False, the parent axes’ anchor will be unchanged

============= ====================================================

colorbar properties:

============ ====================================================

Property Description

============ ====================================================

*extend* [ ’neither’ | ’both’ | ’min’ | ’max’ ]

If not ’neither’, make pointed end(s) for out-of-

range values. These are set for a given colormap

using the colormap set_under and set_over methods.

*extendfrac* [ *None* | ’auto’ | length | lengths ]

If set to *None*, both the minimum and maximum

triangular colorbar extensions with have a length of

5% of the interior colorbar length (this is the

default setting). If set to ’auto’, makes the

triangular colorbar extensions the same lengths as

the interior boxes (when *spacing* is set to

’uniform’) or the same lengths as the respective

adjacent interior boxes (when *spacing* is set to

’proportional’). If a scalar, indicates the length

of both the minimum and maximum triangular colorbar

extensions as a fraction of the interior colorbar

length. A two-element sequence of fractions may also

be given, indicating the lengths of the minimum and

maximum colorbar extensions respectively as a

fraction of the interior colorbar length.

Page 36: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.27. PYPLOT.COLORBAR 31

*extendrect* [ *False* | *True* ]

If *False* the minimum and maximum colorbar extensions

will be triangular (the default). If *True* the

extensions will be rectangular.

*spacing* [ ’uniform’ | ’proportional’ ]

Uniform spacing gives each discrete color the same

space; proportional makes the space proportional to

the data interval.

*ticks* [ None | list of ticks | Locator object ]

If None, ticks are determined automatically from the

input.

*format* [ None | format string | Formatter object ]

If None, the

:class:‘~matplotlib.ticker.ScalarFormatter‘ is used.

If a format string is given, e.g., ’%.3f’, that is

used. An alternative

:class:‘~matplotlib.ticker.Formatter‘ object may be

given instead.

*drawedges* [ False | True ] If true, draw lines at color

boundaries.

============ ====================================================

The following will probably be useful only in the context of

indexed colors (that is, when the mappable has norm=NoNorm()),

or other unusual circumstances.

============ ===================================================

Property Description

============ ===================================================

*boundaries* None or a sequence

*values* None or a sequence which must be of length 1 less

than the sequence of *boundaries*. For each region

delimited by adjacent entries in *boundaries*, the

color mapped to the corresponding value in values

will be used.

============ ===================================================

If mappable is a :class:~matplotlib.contours.ContourSet, its extend kwargis included automatically.

Note that the shrink kwarg provides a simple way to keep a vertical colorbar,for example, from being taller than the axes of the mappable to which thecolorbar is attached; but it is a manual method requiring some trial and error.If the colorbar is too tall (or a horizontal colorbar is too wide) use a smallervalue of shrink.

For more precise control, you can manually specify the positions of the axesobjects in which the mappable and the colorbar are drawn. In this case, do not

Page 37: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

32 CHAPTER 1. PYPLOT

use any of the axes properties kwargs.It is known that some vector graphics viewer (svg and pdf) renders white

gaps between segments of the colorbar. This is due to bugs in the viewers notmatplotlib. As a workaround the colorbar can be rendered with overlappingsegments::

cbar = colorbar()

cbar.solids.set_edgecolor("face")

draw()

However this has negative consequences in other circumstances. Particularlywith semi transparent images (alpha < 1) and colorbar extensions and is notenabled by default see (issue #1188).

returns: :class:~matplotlib.colorbar.Colorbar instance; see also its baseclass, :class:~matplotlib.colorbar.ColorbarBase. Call the :meth:~matplotlib.colorbar.ColorbarBase.set label

method to label the colorbar.

1.28 PyPlot.colors

PyPlot.colors — Method.

This is a do-nothing function to provide you with help on how

matplotlib handles colors.

Commands which take color arguments can use several formats to

specify the colors. For the basic built-in colors, you can use a

single letter

===== =======

Alias Color

===== =======

’b’ blue

’g’ green

’r’ red

’c’ cyan

’m’ magenta

’y’ yellow

’k’ black

’w’ white

===== =======

For a greater range of colors, you have two options. You can

specify the color using an html hex string, as in::

color = ’#eeefff’

Page 38: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.29. PYPLOT.CONTOUR 33

or you can pass an R,G,B tuple, where each of R,G,B are in the

range [0,1].

You can also use any legal html name for a color, for example::

color = ’red’

color = ’burlywood’

color = ’chartreuse’

The example below creates a subplot with a dark

slate gray background::

subplot(111, facecolor=(0.1843, 0.3098, 0.3098))

Here is an example that creates a pale turquoise title::

title(’Is this the best color?’, color=’#afeeee’)

1.29 PyPlot.contour

PyPlot.contour — Method.Plot contours.:func:~matplotlib.pyplot.contour and :func:~matplotlib.pyplot.contourf

draw contour lines and filled contours, respectively. Except as noted, functionsignatures and return values are the same for both versions.

:func:~matplotlib.pyplot.contourf differs from the MATLAB version inthat it does not draw the polygon edges. To draw edges, add line contours withcalls to :func:~matplotlib.pyplot.contour.

Call signatures::contour(Z)make a contour plot of an array Z. The level values are chosen automatically.::contour(X,Y,Z)X, Y specify the (x, y) coordinates of the surface::contour(Z,N) contour(X,Y,Z,N)contour up to N automatically-chosen levels.::contour(Z,V) contour(X,Y,Z,V)draw contour lines at the values specified in sequence V, which must be in

increasing order.::contourf(. . . , V)fill the len(V)-1 regions between the values in V, which must be in increasing

order.

Page 39: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

34 CHAPTER 1. PYPLOT

::contour(Z, **kwargs)Use keyword args to control colors, linewidth, origin, cmap . . . see below

for more details.X and Y must both be 2-D with the same shape as Z, or they must both be

1-D such that len(X) is the number of columns in Z and len(Y) is the numberof rows in Z.

C = contour(...) returns a :class:~matplotlib.contour.QuadContourSetobject.

Optional keyword arguments:corner mask : [ True | False | ‘legacy’ ] Enable/disable corner masking, which

only has an effect if Z is a masked array. If False, any quad touching a maskedpoint is masked out. If True, only the triangular corners of quads nearest thosepoints are always masked out, other triangular corners comprising three un-masked points are contoured as usual. If ‘legacy’, the old contouring algorithmis used, which is equivalent to False and is deprecated, only remaining whilstthe new algorithm is tested fully.

If not specified, the default is taken from

rcParams[’contour.corner_mask’], which is True unless it has

been modified.

colors: [ None | string | (mpl colors) ] If None, the colormap specified bycmap will be used.

If a string, like ’r’ or ’red’, all levels will be plotted in this

color.

If a tuple of matplotlib color args (string, float, rgb, etc),

different levels will be plotted in different colors in the order

specified.

alpha: float The alpha blending valuecmap: [ None | Colormap ] A cm :class:~matplotlib.colors.Colormap

instance or None. If cmap is None and colors is None, a default Colormap isused.

norm: [ None | Normalize ] A :class:matplotlib.colors.Normalize in-stance for scaling data values to colors. If norm is None and colors is None,the default linear scaling is used.

vmin, vmax : [ None | scalar ] If not None, either or both of these values willbe supplied to the :class:matplotlib.colors.Normalize instance, overridingthe default color scaling based on levels.

levels: [level0, level1, . . . , leveln] A list of floating point numbers indicatingthe level curves to draw, in increasing order; e.g., to draw just the zero contourpass levels=[0]

origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None, the first value of Z willcorrespond to the lower left corner, location (0,0). If ‘image’, the rc value forimage.origin will be used.

Page 40: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.29. PYPLOT.CONTOUR 35

This keyword is not active if *X* and *Y* are specified in

the call to contour.

extent : [ None | (x0,x1,y0,y1) ]

If *origin* is not *None*, then *extent* is interpreted as

in :func:‘matplotlib.pyplot.imshow‘: it gives the outer

pixel boundaries. In this case, the position of Z[0,0]

is the center of the pixel, not a corner. If *origin* is

*None*, then (*x0*, *y0*) is the position of Z[0,0], and

(*x1*, *y1*) is the position of Z[-1,-1].

This keyword is not active if *X* and *Y* are specified in

the call to contour.

locator : [ None | ticker.Locator subclass ] If locator is None, the default:class:~matplotlib.ticker.MaxNLocator is used. The locator is used to deter-mine the contour levels if they are not given explicitly via the V argument.

extend : [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’, con-tour levels are automatically added to one or both ends of the range so thatall data are included. These added ranges are then mapped to the special col-ormap values which default to the ends of the colormap range, but can be set via:meth:matplotlib.colors.Colormap.set under and :meth:matplotlib.colors.Colormap.set over

methods.xunits, yunits: [ None | registered units ] Override axis units by specifying

an instance of a :class:matplotlib.units.ConversionInterface.antialiased : [ True | False ] enable antialiasing, overriding the defaults.

For filled contours, the default is True. For line contours, it is taken fromrcParams[‘lines.antialiased’].

nchunk : [ 0 | integer ] If 0, no subdivision of the domain. Specify a positiveinteger to divide the domain into subdomains of nchunk by nchunk quads.Chunking reduces the maximum length of polygons generated by the contouringalgorithm which reduces the rendering workload passed on to the backend andalso requires slightly less RAM. It can however introduce rendering artifacts atchunk boundaries depending on the backend, the antialiased flag and value ofalpha.

contour-only keyword arguments:linewidths: [ None | number | tuple of numbers ] If linewidths is None, the

default width in lines.linewidth in matplotlibrc is used.

If a number, all levels will be plotted with this linewidth.

If a tuple, different levels will be plotted with different

linewidths in the order specified.

linestyles: [ None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles isNone, the default is ‘solid’ unless the lines are monochrome. In that case, nega-

Page 41: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

36 CHAPTER 1. PYPLOT

tive contours will take their linestyle from the matplotlibrc contour.negative linestyle

setting.

*linestyles* can also be an iterable of the above strings

specifying a set of linestyles to be used. If this

iterable is shorter than the number of contour levels

it will be repeated as necessary.

contourf-only keyword arguments:hatches: A list of cross hatch patterns to use on the filled areas. If None, no

hatching will be added to the contour. Hatching is supported in the PostScript,PDF, SVG and Agg backends only.

Note: contourf fills intervals that are closed at the top; that is, for boundariesz1 and z2, the filled region is::

z1 < z <= z2

There is one exception: if the lowest boundary coincides with the minimumvalue of the z array, then that minimum value will be included in the lowestinterval.

Examples:.. plot:: mpl examples/pylab examples/contour demo.py.. plot:: mpl examples/pylab examples/contourf demo.py.. plot:: mpl examples/pylab examples/contour corner mask.py

1.30 PyPlot.contour3D

PyPlot.contour3D — Method.

Create a 3D contour plot.

========== ================================================

Argument Description

========== ================================================

*X*, *Y*, Data values as numpy.arrays

*Z*

*extend3d* Whether to extend contour in 3D (default: False)

*stride* Stride (step size) for extending contour

*zdir* The direction to use: x, y or z (default)

*offset* If specified plot a projection of the contour

lines on this position in plane normal to zdir

========== ================================================

The positional and other keyword arguments are passed on to

:func:‘~matplotlib.axes.Axes.contour‘

Returns a :class:‘~matplotlib.axes.Axes.contour‘

Page 42: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.31. PYPLOT.CONTOURF 37

1.31 PyPlot.contourf

PyPlot.contourf — Method.Plot contours.:func:~matplotlib.pyplot.contour and :func:~matplotlib.pyplot.contourf

draw contour lines and filled contours, respectively. Except as noted, functionsignatures and return values are the same for both versions.

:func:~matplotlib.pyplot.contourf differs from the MATLAB version inthat it does not draw the polygon edges. To draw edges, add line contours withcalls to :func:~matplotlib.pyplot.contour.

Call signatures::contour(Z)make a contour plot of an array Z. The level values are chosen automatically.::contour(X,Y,Z)X, Y specify the (x, y) coordinates of the surface::contour(Z,N) contour(X,Y,Z,N)contour up to N automatically-chosen levels.::contour(Z,V) contour(X,Y,Z,V)draw contour lines at the values specified in sequence V, which must be in

increasing order.::contourf(. . . , V)fill the len(V)-1 regions between the values in V, which must be in increasing

order.::contour(Z, **kwargs)Use keyword args to control colors, linewidth, origin, cmap . . . see below

for more details.X and Y must both be 2-D with the same shape as Z, or they must both be

1-D such that len(X) is the number of columns in Z and len(Y) is the numberof rows in Z.

C = contour(...) returns a :class:~matplotlib.contour.QuadContourSetobject.

Optional keyword arguments:corner mask : [ True | False | ‘legacy’ ] Enable/disable corner masking, which

only has an effect if Z is a masked array. If False, any quad touching a maskedpoint is masked out. If True, only the triangular corners of quads nearest thosepoints are always masked out, other triangular corners comprising three un-masked points are contoured as usual. If ‘legacy’, the old contouring algorithmis used, which is equivalent to False and is deprecated, only remaining whilstthe new algorithm is tested fully.

If not specified, the default is taken from

Page 43: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

38 CHAPTER 1. PYPLOT

rcParams[’contour.corner_mask’], which is True unless it has

been modified.

colors: [ None | string | (mpl colors) ] If None, the colormap specified bycmap will be used.

If a string, like ’r’ or ’red’, all levels will be plotted in this

color.

If a tuple of matplotlib color args (string, float, rgb, etc),

different levels will be plotted in different colors in the order

specified.

alpha: float The alpha blending valuecmap: [ None | Colormap ] A cm :class:~matplotlib.colors.Colormap

instance or None. If cmap is None and colors is None, a default Colormap isused.

norm: [ None | Normalize ] A :class:matplotlib.colors.Normalize in-stance for scaling data values to colors. If norm is None and colors is None,the default linear scaling is used.

vmin, vmax : [ None | scalar ] If not None, either or both of these values willbe supplied to the :class:matplotlib.colors.Normalize instance, overridingthe default color scaling based on levels.

levels: [level0, level1, . . . , leveln] A list of floating point numbers indicatingthe level curves to draw, in increasing order; e.g., to draw just the zero contourpass levels=[0]

origin: [ None | ‘upper’ | ‘lower’ | ‘image’ ] If None, the first value of Z willcorrespond to the lower left corner, location (0,0). If ‘image’, the rc value forimage.origin will be used.

This keyword is not active if *X* and *Y* are specified in

the call to contour.

extent : [ None | (x0,x1,y0,y1) ]

If *origin* is not *None*, then *extent* is interpreted as

in :func:‘matplotlib.pyplot.imshow‘: it gives the outer

pixel boundaries. In this case, the position of Z[0,0]

is the center of the pixel, not a corner. If *origin* is

*None*, then (*x0*, *y0*) is the position of Z[0,0], and

(*x1*, *y1*) is the position of Z[-1,-1].

This keyword is not active if *X* and *Y* are specified in

the call to contour.

locator : [ None | ticker.Locator subclass ] If locator is None, the default:class:~matplotlib.ticker.MaxNLocator is used. The locator is used to deter-mine the contour levels if they are not given explicitly via the V argument.

Page 44: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.31. PYPLOT.CONTOURF 39

extend : [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’, con-tour levels are automatically added to one or both ends of the range so thatall data are included. These added ranges are then mapped to the special col-ormap values which default to the ends of the colormap range, but can be set via:meth:matplotlib.colors.Colormap.set under and :meth:matplotlib.colors.Colormap.set over

methods.

xunits, yunits: [ None | registered units ] Override axis units by specifyingan instance of a :class:matplotlib.units.ConversionInterface.

antialiased : [ True | False ] enable antialiasing, overriding the defaults.For filled contours, the default is True. For line contours, it is taken fromrcParams[‘lines.antialiased’].

nchunk : [ 0 | integer ] If 0, no subdivision of the domain. Specify a positiveinteger to divide the domain into subdomains of nchunk by nchunk quads.Chunking reduces the maximum length of polygons generated by the contouringalgorithm which reduces the rendering workload passed on to the backend andalso requires slightly less RAM. It can however introduce rendering artifacts atchunk boundaries depending on the backend, the antialiased flag and value ofalpha.

contour-only keyword arguments:

linewidths: [ None | number | tuple of numbers ] If linewidths is None, thedefault width in lines.linewidth in matplotlibrc is used.

If a number, all levels will be plotted with this linewidth.

If a tuple, different levels will be plotted with different

linewidths in the order specified.

linestyles: [ None | ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] If linestyles isNone, the default is ‘solid’ unless the lines are monochrome. In that case, nega-tive contours will take their linestyle from the matplotlibrc contour.negative linestyle

setting.

*linestyles* can also be an iterable of the above strings

specifying a set of linestyles to be used. If this

iterable is shorter than the number of contour levels

it will be repeated as necessary.

contourf-only keyword arguments:

hatches: A list of cross hatch patterns to use on the filled areas. If None, nohatching will be added to the contour. Hatching is supported in the PostScript,PDF, SVG and Agg backends only.

Note: contourf fills intervals that are closed at the top; that is, for boundariesz1 and z2, the filled region is::

z1 < z <= z2

Page 45: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

40 CHAPTER 1. PYPLOT

There is one exception: if the lowest boundary coincides with the minimumvalue of the z array, then that minimum value will be included in the lowestinterval.

Examples:.. plot:: mpl examples/pylab examples/contour demo.py.. plot:: mpl examples/pylab examples/contourf demo.py.. plot:: mpl examples/pylab examples/contour corner mask.py

1.32 PyPlot.contourf3D

PyPlot.contourf3D — Method.

Create a 3D contourf plot.

========== ================================================

Argument Description

========== ================================================

*X*, *Y*, Data values as numpy.arrays

*Z*

*zdir* The direction to use: x, y or z (default)

*offset* If specified plot a projection of the filled contour

on this position in plane normal to zdir

========== ================================================

The positional and keyword arguments are passed on to

:func:‘~matplotlib.axes.Axes.contourf‘

Returns a :class:‘~matplotlib.axes.Axes.contourf‘

.. versionchanged :: 1.1.0

The *zdir* and *offset* kwargs were added.

1.33 PyPlot.cool

PyPlot.cool — Method.

set the default colormap to cool and apply to current image if any.

See help(colormaps) for more information

1.34 PyPlot.copper

PyPlot.copper — Method.

set the default colormap to copper and apply to current image if any.

See help(colormaps) for more information

Page 46: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.35. PYPLOT.CSD 41

1.35 PyPlot.csd

PyPlot.csd — Method.Plot the cross-spectral density.Call signature::csd(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend none, window=mlab.window hanning,

noverlap=0, pad to=None, sides=‘default’, scale by freq=None, return line=None,**kwargs)

The cross spectral density :math:P {xy} by Welch’s average periodogrammethod. The vectors x and y are divided into NFFT length segments. Eachsegment is detrended by function detrend and windowed by function window.noverlap gives the length of the overlap between segments. The product of thedirect FFTs of x and y are averaged over each segment to compute :math:P {xy},with a scaling to correct for power loss due to windowing.

If len(x ) < NFFT or len(y) < NFFT, they will be zero padded to NFFT.

1.35.1 Parameters

x, y : 1-D arrays or sequences Arrays or sequences containing the dataFs : scalar The sampling frequency (samples per time unit). It is used to

calculate the Fourier frequencies, freqs, in cycles per time unit. The defaultvalue is 2.

window : callable or ndarray A function or a vector of length NFFT. To cre-ate window vectors see :func:window hanning, :func:window none, :func:numpy.blackman,:func:numpy.hamming, :func:numpy.bartlett, :func:scipy.signal, :func:scipy.signal.get window,etc. The default is :func:window hanning. If a function is passed as the argu-ment, it must take a data segment as an argument and return the windowedversion of the segment.

sides : [ ‘default’ | ‘onesided’ | ‘twosided’ ] Specifies which sides of the spec-trum to return. Default gives the default behavior, which returns one-sided forreal data and both for complex data. ‘onesided’ forces the return of a one-sidedspectrum, while ‘twosided’ forces two-sided.

pad to : integer The number of points to which the data segment is paddedwhen performing the FFT. This can be different from NFFT, which specifiesthe number of data points used. While not increasing the actual resolution ofthe spectrum (the minimum distance between resolvable peaks), this can givemore points in the plot, allowing for more detail. This corresponds to the nparameter in the call to fft(). The default is None, which sets pad to equal toNFFT

NFFT : integer The number of data points used in each block for the FFT.A power 2 is most efficient. The default value is 256. This should NOT be usedto get zero padding, or the scaling of the result will be incorrect. Use pad to forthis instead.

detrend : {‘default’, ‘constant’, ‘mean’, ‘linear’, ‘none’} or callable The func-tion applied to each segment before fft-ing, designed to remove the mean orlinear trend. Unlike in MATLAB, where the detrend parameter is a vector,

Page 47: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

42 CHAPTER 1. PYPLOT

in matplotlib is it a function. The :mod:~matplotlib.pylab module defines:func:~matplotlib.pylab.detrend none, :func:~matplotlib.pylab.detrend mean,and :func:~matplotlib.pylab.detrend linear, but you can use a custom func-tion as well. You can also use a string to choose one of the functions. ‘default’,‘constant’, and ‘mean’ call :func:~matplotlib.pylab.detrend mean. ‘linear’calls :func:~matplotlib.pylab.detrend linear. ‘none’ calls :func:~matplotlib.pylab.detrend none.

scale by freq : boolean, optional Specifies whether the resulting density val-ues should be scaled by the scaling frequency, which gives density in units ofHzˆ-1. This allows for integration over the returned frequency values. Thedefault is True for MATLAB compatibility.

noverlap : integer The number of points of overlap between segments. Thedefault value is 0 (no overlap).

Fc : integer The center frequency of x (defaults to 0), which offsets the xextents of the plot to reflect the frequency range used when a signal is acquiredand then filtered and downsampled to baseband.

return line : bool Whether to include the line object plotted in the returnedvalues. Default is False.

**kwargs : Keyword arguments control the :class:~matplotlib.lines.Line2Dproperties:

agg filter: unknown alpha: float (0.0 transparent through 1.0 opaque) ani-mated: [True | False] antialiased or aa: [True | False] axes: an :class:~matplotlib.axes.Axesinstance clip box: a :class:matplotlib.transforms.Bbox instance clip on: [True| False] clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] color or c: any matplotlib colorcontains: a callable function dash capstyle: [‘butt’ | ‘round’ | ‘projecting’]dash joinstyle: [‘miter’ | ‘round’ | ‘bevel’] dashes: sequence of on/off ink inpoints drawstyle: [‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’] fig-ure: a :class:matplotlib.figure.Figure instance fillstyle: [‘full’ | ‘left’ | ‘right’| ‘bottom’ | ‘top’ | ‘none’] gid: an id string label: string or anything printablewith ‘%s’ conversion. linestyle or ls: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (off-set, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or lw: float value inpoints marker: :mod:A valid marker style <matplotlib.markers> mark-eredgecolor or mec: any matplotlib color markeredgewidth or mew: float valuein points markerfacecolor or mfc: any matplotlib color markerfacecoloralt ormfcalt: any matplotlib color markersize or ms: float markevery: [None | int |length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]path effects: unknown picker: float distance in points or callable pick func-tion fn(artist, event) pickradius: float distance in points rasterized: [True| False | None] sketch params: unknown snap: unknown solid capstyle: [‘butt’| ‘round’ | ‘projecting’] solid joinstyle: [‘miter’ | ‘round’ | ‘bevel’] transform:a :class:matplotlib.transforms.Transform instance url: a url string visible:[True | False] xdata: 1D array ydata: 1D array zorder: any number

Page 48: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.36. PYPLOT.DELAXES 43

1.35.2 Returns

Pxy : 1-D array The values for the cross spectrum P {xy} before scaling (com-plex valued)

freqs : 1-D array The frequencies corresponding to the elements in Pxyline : a :class:~matplotlib.lines.Line2D instance The line created by this

function. Only returned if return line is True.

1.35.3 Notes

For plotting, the power is plotted as :math:10\log {10}(P {xy}) for decibels,though P {xy} itself is returned.

1.35.4 References

Bendat & Piersol – Random Data: Analysis and Measurement Procedures, JohnWiley & Sons (1986)

1.35.5 Examples

.. plot:: mpl examples/pylab examples/csd demo.py

1.35.6 See Also

:func:psd :func:psd is the equivalent to setting y=x... note:: In addition to the above described arguments, this function can

take a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All arguments with the following names: ’x’, ’y’.

1.36 PyPlot.delaxes

PyPlot.delaxes — Method.

Remove an axes from the current figure. If *ax*

doesn’t exist, an error will be raised.

‘‘delaxes()‘‘: delete the current axes

1.37 PyPlot.disconnect

PyPlot.disconnect — Method.Disconnect callback id cidExample usage::

Page 49: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

44 CHAPTER 1. PYPLOT

cid = canvas.mpl_connect(’button_press_event’, on_press)

#...later

canvas.mpl_disconnect(cid)

1.38 PyPlot.draw

PyPlot.draw — Method.Redraw the current figure.

This is used to update a figure that has been altered, but not

automatically re-drawn. If interactive mode is on (:func:‘.ion()‘), this

should be only rarely needed, but there may be ways to modify the state of

a figure without marking it as ‘stale‘. Please report these cases as

bugs.

A more object-oriented alternative, given any

:class:‘~matplotlib.figure.Figure‘ instance, :attr:‘fig‘, that

was created using a :mod:‘~matplotlib.pyplot‘ function, is::

fig.canvas.draw_idle()

1.39 PyPlot.errorbar

PyPlot.errorbar — Method.Plot an errorbar graph.Plot x versus y with error deltas in yerr and xerr. Vertical errorbars are

plotted if yerr is not None. Horizontal errorbars are plotted if xerr is not None.x, y, xerr, and yerr can all be scalars, which plots a single error bar at x, y.

1.39.1 Parameters

x : scalar y : scalarxerr/yerr : scalar or array-like, shape(n,1) or shape(2,n), optional If a scalar

number, len(N) array-like object, or an Nx1 array-like object, errorbars aredrawn at +/-value relative to the data. Default is None.

If a sequence of shape 2xN, errorbars are drawn at -row1

and +row2 relative to the data.

fmt : plot format string, optional, default: None The plot format symbol. Iffmt is ‘none’ (case-insensitive), only the errorbars are plotted. This is used foradding errorbars to a bar plot, for example. Default is ”, an empty plot formatstring; properties are then identical to the defaults for :meth:plot.

ecolor : mpl color, optional, default: None A matplotlib color arg whichgives the color the errorbar lines; if None, use the color of the line connectingthe markers.

Page 50: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.39. PYPLOT.ERRORBAR 45

elinewidth : scalar, optional, default: None The linewidth of the errorbarlines. If None, use the linewidth.

capsize : scalar, optional, default: None The length of the error bar caps inpoints; if None, it will take the value from errorbar.capsize :data:rcParam<matplotlib.rcParams>.

capthick : scalar, optional, default: None An alias kwarg to markeredgewidth(a.k.a. - mew). This setting is a more sensible name for the property that con-trols the thickness of the error bar cap in points. For backwards compatibility,if mew or markeredgewidth are given, then they will over-ride capthick. Thismay change in future releases.

barsabove : bool, optional, default: False if True , will plot the errorbarsabove the plot symbols. Default is below.

lolims / uplims / xlolims / xuplims : bool, optional, default:None Thesearguments can be used to indicate that a value gives only upper/lower limits.In that case a caret symbol is used to indicate this. lims-arguments may be of thesame type as xerr and yerr. To use limits with inverted axes, :meth:set xlim

or :meth:set ylim must be called before :meth:errorbar.errorevery : positive integer, optional, default:1 subsamples the errorbars.

e.g., if errorevery=5, errorbars for every 5-th datapoint will be plotted. Thedata plot itself still shows all data points.

1.39.2 Returns

plotline : :class:~matplotlib.lines.Line2D instance x, y plot markers and/orline caplines : list of :class:~matplotlib.lines.Line2D instances error bar capbarlinecols : list of :class:~matplotlib.collections.LineCollection horizon-tal and vertical error ranges.

1.39.3 Other Parameters

kwargs : All other keyword arguments are passed on to the plot command forthe markers. For example, this code makes big red squares with thick greenedges::

x,y,yerr = rand(3,10)

errorbar(x, y, yerr, marker=’s’, mfc=’red’,

mec=’green’, ms=20, mew=4)

where mfc, mec, ms and mew are aliases for the longer

property names, markerfacecolor, markeredgecolor, markersize

and markeredgewidth.

valid kwargs for the marker properties are

agg_filter: unknown

alpha: float (0.0 transparent through 1.0 opaque) animated: [True | False]antialiased or aa: [True | False] axes: an :class:~matplotlib.axes.Axes in-

Page 51: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

46 CHAPTER 1. PYPLOT

stance clip box: a :class:matplotlib.transforms.Bbox instance clip on: [True| False] clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] color or c: any matplotlib colorcontains: a callable function dash capstyle: [‘butt’ | ‘round’ | ‘projecting’]dash joinstyle: [‘miter’ | ‘round’ | ‘bevel’] dashes: sequence of on/off ink inpoints drawstyle: [‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’] fig-ure: a :class:matplotlib.figure.Figure instance fillstyle: [‘full’ | ‘left’ | ‘right’| ‘bottom’ | ‘top’ | ‘none’] gid: an id string label: string or anything printablewith ‘%s’ conversion. linestyle or ls: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (off-set, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or lw: float value inpoints marker: :mod:A valid marker style <matplotlib.markers> mark-eredgecolor or mec: any matplotlib color markeredgewidth or mew: float valuein points markerfacecolor or mfc: any matplotlib color markerfacecoloralt ormfcalt: any matplotlib color markersize or ms: float markevery: [None | int |length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]path effects: unknown picker: float distance in points or callable pick func-tion fn(artist, event) pickradius: float distance in points rasterized: [True| False | None] sketch params: unknown snap: unknown solid capstyle: [‘butt’| ‘round’ | ‘projecting’] solid joinstyle: [‘miter’ | ‘round’ | ‘bevel’] transform:a :class:matplotlib.transforms.Transform instance url: a url string visible:[True | False] xdata: 1D array ydata: 1D array zorder: any number

1.39.4 Examples

.. plot:: mpl examples/statistics/errorbar demo.py.. note:: In addition to the above described arguments, this function can

take a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All arguments with the following names: ’x’, ’xerr’, ’y’, ’yerr’.

1.40 PyPlot.eventplot

PyPlot.eventplot — Method.Plot identical parallel lines at specific positions.Plot parallel lines at the given positions. positions should be a 1D or 2D

array-like object, with each row corresponding to a row or column of lines.This type of plot is commonly used in neuroscience for representing neural

events, where it is commonly called a spike raster, dot raster, or raster plot.However, it is useful in any situation where you wish to show the timing or

position of multiple sets of discrete events, such as the arrival times of peopleto a business on each day of the month or the date of hurricanes each year ofthe last century.

orientation : [ ‘horizonal’ | ‘vertical’ ] ‘horizonal’ : the lines will be verticaland arranged in rows “vertical’ : lines will be horizontal and arranged in columns

Page 52: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.41. PYPLOT.FIGASPECT 47

lineoffsets : A float or array-like containing floats.linelengths : A float or array-like containing floats.linewidths : A float or array-like containing floats.colors must be a sequence of RGBA tuples (e.g., arbitrary color strings, etc,

not allowed) or a list of such sequenceslinestyles : [ ‘solid’ | ‘dashed’ | ‘dashdot’ | ‘dotted’ ] or an array of these

valuesFor linelengths, linewidths, colors, and linestyles, if only a single value is

given, that value is applied to all lines. If an array-like is given, it must havethe same length as positions, and each value will be applied to the correspondingrow or column in positions.

Returns a list of :class:matplotlib.collections.EventCollection objectsthat were added.

kwargs are :class:~matplotlib.collections.LineCollection properties:agg filter: unknown alpha: float or None animated: [True | False] an-

tialiased or antialiaseds: Boolean or sequence of booleans array: unknown axes:an :class:~matplotlib.axes.Axes instance clim: a length 2 sequence of floatsclip box: a :class:matplotlib.transforms.Bbox instance clip on: [True | False]clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] cmap: a colormap or registeredcolormap name color: matplotlib color arg or sequence of rgba tuples contains:a callable function edgecolor or edgecolors: matplotlib color spec or sequenceof specs facecolor or facecolors: matplotlib color spec or sequence of specs fig-ure: a :class:matplotlib.figure.Figure instance gid: an id string hatch: [ ‘/’| ‘\’ | ‘|’ | ‘-’ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ’*’ ] label: string or anything print-able with ‘%s’ conversion. linestyle or dashes or linestyles: [‘solid’ | ‘dashed’,‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) | - | -- | -. | : | None | | ]linewidth or linewidths or lw: float or sequence of floats norm: unknown off-set position: unknown offsets: float or sequence of floats path effects: unknownpaths: unknown picker: [None|float|boolean|callable] pickradius: unknown ras-terized: [True | False | None] segments: unknown sketch params: unknown snap:unknown transform: :class:~matplotlib.transforms.Transform instance url:a url string urls: unknown verts: unknown visible: [True | False] zorder: anynumber

Example:.. plot:: mpl examples/pylab examples/eventplot demo.py.. note:: In addition to the above described arguments, this function can

take a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All arguments with the following names: ’colors’, ’linelengths’, ’lineoffsets’, ’linestyles’, ’linewidths’, ’positions’.

1.41 PyPlot.figaspect

PyPlot.figaspect — Method.

Page 53: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

48 CHAPTER 1. PYPLOT

Create a figure with specified aspect ratio. If *arg* is a number,

use that aspect ratio. If *arg* is an array, figaspect will

determine the width and height for a figure that would fit array

preserving aspect ratio. The figure width, height in inches are

returned. Be sure to create an axes with equal with and height,

e.g.,

Example usage::

# make a figure twice as tall as it is wide

w, h = figaspect(2.)

fig = Figure(figsize=(w,h))

ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

ax.imshow(A, **kwargs)

# make a figure with the proper aspect for an array

A = rand(5,3)

w, h = figaspect(A)

fig = Figure(figsize=(w,h))

ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

ax.imshow(A, **kwargs)

Thanks to Fernando Perez for this function

1.42 PyPlot.figimage

PyPlot.figimage — Method.Adds a non-resampled image to the figure.call signatures::figimage(X, **kwargs)adds a non-resampled array X to the figure.::figimage(X, xo, yo)with pixel offsets xo, yo,X must be a float array:

• If X is MxN, assume luminance (grayscale)

• If X is MxNx3, assume RGB

• If X is MxNx4, assume RGBA

Optional keyword arguments:========= =========================================================

Keyword Description ========= =========================================================

Page 54: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.43. PYPLOT.FIGLEGEND 49

resize a boolean, True or False. If “True”, then re-size the Figure to match thegiven image size. xo or yo An integer, the x and y image offset in pixels cmapa :class:matplotlib.colors.Colormap instance, e.g., cm.jet. If None, defaultto the rc image.cmap value norm a :class:matplotlib.colors.Normalize in-stance. The default is normalization(). This scales luminance -> 0-1 vmin|vmaxare used to scale a luminance image to 0-1. If either is None, the min and maxof the luminance values will be used. Note if you pass a norm instance, the set-tings for vmin and vmax will be ignored. alpha the alpha blending value, defaultis None origin [ ‘upper’ | ‘lower’ ] Indicates where the [0,0] index of the arrayis in the upper left or lower left corner of the axes. Defaults to the rc image.originvalue ========= =========================================================

figimage complements the axes image (:meth:~matplotlib.axes.Axes.imshow)which will be resampled to fit the current axes. If you want a resampled imageto fill the entire figure, you can define an :class:~matplotlib.axes.Axes withextent [0,0,1,1].

An :class:matplotlib.image.FigureImage instance is returned... plot:: mpl examples/pylab examples/figimage demo.pyAdditional kwargs are Artist kwargs passed on to :class:~matplotlib.image.FigureImage

1.43 PyPlot.figlegend

PyPlot.figlegend — Method.

Place a legend in the figure.

*labels*

a sequence of strings

*handles*

a sequence of :class:‘~matplotlib.lines.Line2D‘ or

:class:‘~matplotlib.patches.Patch‘ instances

*loc*

can be a string or an integer specifying the legend

location

A :class:‘matplotlib.legend.Legend‘ instance is returned.

Example::

figlegend( (line1, line2, line3),

(’label1’, ’label2’, ’label3’),

’upper right’ )

.. seealso::

Page 55: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

50 CHAPTER 1. PYPLOT

:func:‘~matplotlib.pyplot.legend‘

1.44 PyPlot.figtext

PyPlot.figtext — Method.Add text to figure.Call signature::text(x, y, s, fontdict=None, **kwargs)Add text to figure at location x, y (relative 0-1 coords). See :func:~matplotlib.pyplot.text

for the meaning of the other arguments.kwargs control the :class:~matplotlib.text.Text properties:agg filter: unknown alpha: float (0.0 transparent through 1.0 opaque) an-

imated: [True | False] axes: an :class:~matplotlib.axes.Axes instance back-groundcolor: any matplotlib color bbox: FancyBboxPatch prop dict clip box: a:class:matplotlib.transforms.Bbox instance clip on: [True | False] clip path: [(:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] color: any matplotlib color con-tains: a callable function family or fontfamily or fontname or name: [FONT-NAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] figure: a:class:matplotlib.figure.Figure instance fontproperties or font properties: a:class:matplotlib.font manager.FontProperties instance gid: an id stringhorizontalalignment or ha: [ ‘center’ | ‘right’ | ‘left’ ] label: string or anythingprintable with ‘%s’ conversion. linespacing: float (multiple of font size) multi-alignment: [‘left’ | ‘right’ | ‘center’ ] path effects: unknown picker: [None|float|boolean|callable]position: (x,y) rasterized: [True | False | None] rotation: [ angle in degrees| ‘vertical’ | ‘horizontal’ ] rotation mode: unknown size or fontsize: [size inpoints | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ | ‘xx-large’] sketch params: unknown snap: unknown stretch or fontstretch: [a numericvalue in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘condensed’ | ‘semi-condensed’ | ‘normal’ | ‘semi-expanded’ | ‘expanded’ | ‘extra-expanded’ | ‘ultra-expanded’ ] style or fontstyle: [ ‘normal’ | ‘italic’ | ‘oblique’] text: string or any-thing printable with ‘%s’ conversion. transform: :class:~matplotlib.transforms.Transforminstance url: a url string usetex: unknown variant or fontvariant: [ ‘normal’ |‘small-caps’ ] verticalalignment or ma or va: [ ‘center’ | ‘top’ | ‘bottom’ | ‘base-line’ ] visible: [True | False] weight or fontweight: [a numeric value in range0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | ‘book’ | ‘medium’ | ‘roman’ |‘semibold’ | ‘demibold’ | ‘demi’ | ‘bold’ | ‘heavy’ | ‘extra bold’ | ‘black’ ] wrap:unknown x: float y: float zorder: any number

1.45 PyPlot.figure

PyPlot.figure — Method.

Creates a new figure.

Page 56: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.45. PYPLOT.FIGURE 51

Parameters

----------

num : integer or string, optional, default: none

If not provided, a new figure will be created, and the figure number

will be incremented. The figure objects holds this number in a ‘number‘

attribute.

If num is provided, and a figure with this id already exists, make

it active, and returns a reference to it. If this figure does not

exists, create it and returns it.

If num is a string, the window title will be set to this figure’s

‘num‘.

figsize : tuple of integers, optional, default: None

width, height in inches. If not provided, defaults to rc

figure.figsize.

dpi : integer, optional, default: None

resolution of the figure. If not provided, defaults to rc figure.dpi.

facecolor :

the background color. If not provided, defaults to rc figure.facecolor

edgecolor :

the border color. If not provided, defaults to rc figure.edgecolor

Returns

-------

figure : Figure

The Figure instance returned will also be passed to new_figure_manager

in the backends, which allows to hook custom Figure classes into the

pylab interface. Additional kwargs will be passed to the figure init

function.

Notes

-----

If you are creating many figures, make sure you explicitly call "close"

on the figures you are not using, because this will enable pylab

to properly clean up the memory.

rcParams defines the default values, which can be modified in the

matplotlibrc file

Page 57: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

52 CHAPTER 1. PYPLOT

1.46 PyPlot.fill between

PyPlot.fill between — Method.

Make filled polygons between two curves.

Create a :class:~matplotlib.collections.PolyCollection filling the re-gions between y1 and y2 where where==True

1.46.1 Parameters

x : array An N-length array of the x data

y1 : array An N-length array (or scalar) of the y data

y2 : array An N-length array (or scalar) of the y data

where : array, optional If None, default to fill between everywhere. If notNone, it is an N-length numpy boolean array and the fill will only happen overthe regions where where==True.

interpolate : bool, optional If True, interpolate between the two lines tofind the precise point of intersection. Otherwise, the start and end points of thefilled region will only occur on explicit values in the x array.

step : {‘pre’, ‘post’, ‘mid’}, optional If not None, fill with step logic.

1.46.2 Notes

Additional Keyword args passed on to the :class:~matplotlib.collections.PolyCollection.

kwargs control the :class:~matplotlib.patches.Polygon properties:

agg filter: unknown alpha: float or None animated: [True | False] an-tialiased or antialiaseds: Boolean or sequence of booleans array: unknown axes:an :class:~matplotlib.axes.Axes instance clim: a length 2 sequence of floatsclip box: a :class:matplotlib.transforms.Bbox instance clip on: [True | False]clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] cmap: a colormap or registeredcolormap name color: matplotlib color arg or sequence of rgba tuples contains:a callable function edgecolor or edgecolors: matplotlib color spec or sequence ofspecs facecolor or facecolors: matplotlib color spec or sequence of specs figure: a:class:matplotlib.figure.Figure instance gid: an id string hatch: [ ‘/’ | ‘\’ | ‘|’| ‘-’ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ’*’ ] label: string or anything printable with ‘%s’ con-version. linestyle or dashes or linestyles: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ |(offset, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or linewidths or lw:float or sequence of floats norm: unknown offset position: unknown offsets: floator sequence of floats path effects: unknown picker: [None|float|boolean|callable]pickradius: unknown rasterized: [True | False | None] sketch params: un-known snap: unknown transform: :class:~matplotlib.transforms.Transforminstance url: a url string urls: unknown visible: [True | False] zorder: anynumber

Page 58: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.47. PYPLOT.FILL BETWEENX 53

1.46.3 Examples

.. plot:: mpl examples/pylab examples/fill between demo.py

1.46.4 See Also

:meth:‘fill_betweenx‘

for filling between two sets of x-values

.. note:: In addition to the above described arguments, this function cantake a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All arguments with the following names: ’where’, ’x’, ’y1’, ’y2’.

1.47 PyPlot.fill betweenx

PyPlot.fill betweenx — Method.Make filled polygons between two horizontal curves.Create a :class:~matplotlib.collections.PolyCollection filling the re-

gions between x1 and x2 where where==True

1.47.1 Parameters

y : array An N-length array of the y datax1 : array An N-length array (or scalar) of the x datax2 : array, optional An N-length array (or scalar) of the x datawhere : array, optional If None, default to fill between everywhere. If not

None, it is a N length numpy boolean array and the fill will only happen overthe regions where where==True

step : {‘pre’, ‘post’, ‘mid’}, optional If not None, fill with step logic.

1.47.2 Notes

keyword args passed on to the :class:~matplotlib.collections.PolyCollectionkwargs control the :class:~matplotlib.patches.Polygon properties:agg filter: unknown alpha: float or None animated: [True | False] an-

tialiased or antialiaseds: Boolean or sequence of booleans array: unknown axes:an :class:~matplotlib.axes.Axes instance clim: a length 2 sequence of floatsclip box: a :class:matplotlib.transforms.Bbox instance clip on: [True | False]clip path: [ (:class:~matplotlib.path.Path, :class:~matplotlib.transforms.Transform)| :class:~matplotlib.patches.Patch | None ] cmap: a colormap or registeredcolormap name color: matplotlib color arg or sequence of rgba tuples contains:a callable function edgecolor or edgecolors: matplotlib color spec or sequence ofspecs facecolor or facecolors: matplotlib color spec or sequence of specs figure: a:class:matplotlib.figure.Figure instance gid: an id string hatch: [ ‘/’ | ‘\’ | ‘|’

Page 59: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

54 CHAPTER 1. PYPLOT

| ‘-’ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ’*’ ] label: string or anything printable with ‘%s’ con-version. linestyle or dashes or linestyles: [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ |(offset, on-off-dash-seq) | - | -- | -. | : | None | | ] linewidth or linewidths or lw:float or sequence of floats norm: unknown offset position: unknown offsets: floator sequence of floats path effects: unknown picker: [None|float|boolean|callable]pickradius: unknown rasterized: [True | False | None] sketch params: un-known snap: unknown transform: :class:~matplotlib.transforms.Transforminstance url: a url string urls: unknown visible: [True | False] zorder: anynumber

1.47.3 Examples

.. plot:: mpl examples/pylab examples/fill betweenx demo.py

1.47.4 See Also

:meth:‘fill_between‘

for filling between two sets of y-values

.. note:: In addition to the above described arguments, this function cantake a data keyword argument. If such a data argument is given, the followingarguments are replaced by data[]:

* All arguments with the following names: ’where’, ’x1’, ’x2’, ’y’.

1.48 PyPlot.findobj

PyPlot.findobj — Method.Find artist objects.Recursively find all :class:~matplotlib.artist.Artist instances contained

in self.match can be

• None: return all objects contained in artist.

• function with signature boolean = match(artist) used to filter matches

• class instance: e.g., Line2D. Only return artists of class type.

If include self is True (default), include self in the list to be checked for amatch.

1.49 PyPlot.flag

PyPlot.flag — Method.

set the default colormap to flag and apply to current image if any.

See help(colormaps) for more information

Page 60: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

1.50. PYPLOT.GCA 55

1.50 PyPlot.gca

PyPlot.gca — Method.

Get the current :class:‘~matplotlib.axes.Axes‘ instance on the

current figure matching the given keyword args, or create one.

Examples

--------

To get the current polar axes on the current figure::

plt.gca(projection=’polar’)

If the current axes doesn’t exist, or isn’t a polar one, the appropriate

axes will be created and then returned.

See Also

--------

matplotlib.figure.Figure.gca : The figure’s gca method.

1.51 PyPlot.gcf

PyPlot.gcf — Method.Get a reference to the current figure.

1.52 PyPlot.gci

PyPlot.gci — Method.

Get the current colorable artist. Specifically, returns the

current :class:‘~matplotlib.cm.ScalarMappable‘ instance (image or

patch collection), or *None* if no images or patch collections

have been defined. The commands :func:‘~matplotlib.pyplot.imshow‘

and :func:‘~matplotlib.pyplot.figimage‘ create

:class:‘~matplotlib.image.Image‘ instances, and the commands

:func:‘~matplotlib.pyplot.pcolor‘ and

:func:‘~matplotlib.pyplot.scatter‘ create

:class:‘~matplotlib.collections.Collection‘ instances. The

current image is an attribute of the current axes, or the nearest

earlier axes in the current figure that contains an image.

1.53 PyPlot.get cmap

PyPlot.get cmap — Method.

Page 61: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

56 CHAPTER 1. PYPLOT

Get a colormap instance, defaulting to rc values if *name* is None.

Colormaps added with :func:‘register_cmap‘ take precedence over

built-in colormaps.

If *name* is a :class:‘matplotlib.colors.Colormap‘ instance, it will be

returned.

If *lut* is not None it must be an integer giving the number of

entries desired in the lookup table, and *name* must be a standard

mpl colormap name.

1.54 PyPlot.get current fig manager

PyPlot.get current fig manager — Method.

Page 62: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 2

QuantEcon

2.1 LightGraphs.period

LightGraphs.period — Method.Return the period of the Markov chain mc.Arguments

• mc::MarkovChain : MarkovChain instance.

Returns

• ::Int : Period of mc.

2.2 QuantEcon.F to K

QuantEcon.F to K — Method.Compute agent 2’s best cost-minimizing response K, given F.Arguments

• rlq::RBLQ: Instance of RBLQ type

• F::Matrix{Float64}: A k x n array representing agent 1’s policy

Returns

• K::Matrix{Float64} : Agent’s best cost minimizing response correspond-ing to

F

• P::Matrix{Float64} : The value function corresponding to F

57

Page 63: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

58 CHAPTER 2. QUANTECON

2.3 QuantEcon.K to F

QuantEcon.K to F — Method.

Compute agent 1’s best cost-minimizing response K, given F.

Arguments

• rlq::RBLQ: Instance of RBLQ type

• K::Matrix{Float64}: A k x n array representing the worst case matrix

Returns

• F::Matrix{Float64} : Agent’s best cost minimizing response correspond-ing to

K

• P::Matrix{Float64} : The value function corresponding to K

2.4 QuantEcon.RQ sigma

QuantEcon.RQ sigma — Method.

Method of RQ sigma that extracts sigma from a DPSolveResult

See other docstring for details

2.5 QuantEcon.RQ sigma

QuantEcon.RQ sigma — Method.

Given a policy sigma, return the reward vector R sigma and the transitionprobability matrix Q sigma.

Parameters

• ddp::DiscreteDP : Object that contains the model parameters

• sigma::Vector{Int}: policy rule vector

Returns

• R sigma::Array{Float64}: Reward vector for sigma, of length n.

• Q sigma::Array{Float64}: Transition probability matrix for sigma, ofshape (n, n).

Page 64: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.6. QUANTECON.AR PERIODOGRAM 59

2.6 QuantEcon.ar periodogram

QuantEcon.ar periodogram — Function.Compute periodogram from data x, using prewhitening, smoothing and re-

coloring. The data is fitted to an AR(1) model for prewhitening, and the resid-uals are used to compute a first-pass periodogram with smoothing. The fittedcoefficients are then used for recoloring.

Arguments

• x::Array: An array containing the data to smooth

• window len::Int(7): An odd integer giving the length of the window

• window::AbstractString("hanning"): A string giving the window type.Possible values

are flat, hanning, hamming, bartlett, or blackmanReturns

• w::Array{Float64}: Fourier frequencies at which the periodogram isevaluated

• I w::Array{Float64}: The periodogram at frequences w

2.7 QuantEcon.autocovariance

QuantEcon.autocovariance — Method.Compute the autocovariance function from the ARMA parameters over the

integers range(num autocov) using the spectral density and the inverse Fouriertransform.

Arguments

• arma::ARMA: Instance of ARMA type

• ;num autocov::Integer(16) : The number of autocovariances to calcu-late

2.8 QuantEcon.b operator

QuantEcon.b operator — Method.The D operator, mapping P into

B(P) := R - beta^2 A’PB(Q + beta B’PB)^{-1}B’PA + beta A’PA

and also returning

F := (Q + beta B’PB)^{-1} beta B’PA

Page 65: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

60 CHAPTER 2. QUANTECON

Arguments

• rlq::RBLQ: Instance of RBLQ type

• P::Matrix{Float64} : size is n x n

Returns

• F::Matrix{Float64} : The F matrix as defined above

• new p::Matrix{Float64} : The matrix P after applying the B operator

2.9 QuantEcon.bellman operator!

QuantEcon.bellman operator! — Method.The Bellman operator, which computes and returns the updated value func-

tion Tv for a value function v.Parameters

• ddp::DiscreteDP : Object that contains the model parameters

• v::Vector{T<:AbstractFloat}: The current guess of the value function

• Tv::Vector{T<:AbstractFloat}: A buffer array to hold the updatedvalue function. Initial value not used and will be overwritten

• sigma::Vector: A buffer array to hold the policy function. Initial valuesnot used and will be overwritten

Returns

• Tv::Vector : Updated value function vector

• sigma::Vector : Updated policiy function vector

2.10 QuantEcon.bellman operator!

QuantEcon.bellman operator! — Method.The Bellman operator, which computes and returns the updated value func-

tion Tv for a given value function v.This function will fill the input v with Tv and the input sigma with the

corresponding policy ruleParameters

• ddp::DiscreteDP: The ddp model

• v::Vector{T<:AbstractFloat}: The current guess of the value function.This array will be overwritten

Page 66: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.11. QUANTECON.BELLMAN OPERATOR! 61

• sigma::Vector: A buffer array to hold the policy function. Initial valuesnot used and will be overwritten

Returns

• Tv::Vector: Updated value function vector

• sigma::Vector{T<:Integer}: Policy rule

2.11 QuantEcon.bellman operator!

QuantEcon.bellman operator! — Method.Apply the Bellman operator using v=ddpr.v, Tv=ddpr.Tv, and sigma=ddpr.sigma

NotesUpdates ddpr.Tv and ddpr.sigma inplace

2.12 QuantEcon.bellman operator

QuantEcon.bellman operator — Method.The Bellman operator, which computes and returns the updated value func-

tion Tv for a given value function v.Parameters

• ddp::DiscreteDP: The ddp model

• v::Vector: The current guess of the value function

Returns

• Tv::Vector : Updated value function vector

2.13 QuantEcon.bisect

QuantEcon.bisect — Method.Find the root of the f on the bracketing inverval [x1, x2] via bisectionArguments

• f::Function: The function you want to bracket

• x1::T: Lower border for search interval

• x2::T: Upper border for search interval

• ;maxiter::Int(500): Maximum number of bisection iterations

• ;xtol::Float64(1e-12): The routine converges when a root is known tolie

Page 67: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

62 CHAPTER 2. QUANTECON

within xtol of the value return. Should be >= 0. The routine modifies thisto take into account the relative precision of doubles.

• ;rtol::Float64(2*eps()):The routine converges when a root is knownto lie

within rtol times the value returned of the value returned. Should be 0Returns

• x::T: The found root

Exceptions

• Throws an ArgumentError if [x1, x2] does not form a bracketing interval

• Throws a ConvergenceError if the maximum number of iterations is ex-ceeded

ReferencesMatches bisect function from scipy/scipy/optimize/Zeros/bisect.c

2.14 QuantEcon.brent

QuantEcon.brent — Method.Find the root of the f on the bracketing inverval [x1, x2] via brent’s algoArguments

• f::Function: The function you want to bracket

• x1::T: Lower border for search interval

• x2::T: Upper border for search interval

• ;maxiter::Int(500): Maximum number of bisection iterations

• ;xtol::Float64(1e-12): The routine converges when a root is known tolie

within xtol of the value return. Should be >= 0. The routine modifies thisto take into account the relative precision of doubles.

• ;rtol::Float64(2*eps()):The routine converges when a root is knownto lie

within rtol times the value returned of the value returned. Should be 0Returns

• x::T: The found root

Exceptions

Page 68: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.15. QUANTECON.BRENTH 63

• Throws an ArgumentError if [x1, x2] does not form a bracketing interval

• Throws a ConvergenceError if the maximum number of iterations is ex-ceeded

ReferencesMatches brentq function from scipy/scipy/optimize/Zeros/bisectq.c

2.15 QuantEcon.brenth

QuantEcon.brenth — Method.Find a root of the f on the bracketing inverval [x1, x2] via modified brentThis routine uses a hyperbolic extrapolation formula instead of the standard

inverse quadratic formula. Otherwise it is the original Brent’s algorithm, asimplemented in the brent function.

Arguments

• f::Function: The function you want to bracket

• x1::T: Lower border for search interval

• x2::T: Upper border for search interval

• ;maxiter::Int(500): Maximum number of bisection iterations

• ;xtol::Float64(1e-12): The routine converges when a root is known tolie

within xtol of the value return. Should be >= 0. The routine modifies thisto take into account the relative precision of doubles.

• ;rtol::Float64(2*eps()):The routine converges when a root is knownto lie

within rtol times the value returned of the value returned. Should be 0Returns

• x::T: The found root

Exceptions

• Throws an ArgumentError if [x1, x2] does not form a bracketing interval

• Throws a ConvergenceError if the maximum number of iterations is ex-ceeded

ReferencesMatches brenth function from scipy/scipy/optimize/Zeros/bisecth.c

Page 69: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

64 CHAPTER 2. QUANTECON

2.16 QuantEcon.ckron

QuantEcon.ckron — Function.

ckron(arrays::AbstractArray...)

Repeatedly apply kronecker products to the arrays. Equilvalent to reduce(kron,arrays)

2.17 QuantEcon.communication classes

QuantEcon.communication classes — Method.

Find the communication classes of the Markov chain mc.

Arguments

• mc::MarkovChain : MarkovChain instance.

Returns

• ::Vector{Vector{Int}} : Vector of vectors that describe the communi-cation

classes of mc.

2.18 QuantEcon.compute deterministic entropy

QuantEcon.compute deterministic entropy — Method.

Given K and F, compute the value of deterministic entropy, which is sum tbetaˆt x t’ K’K x t with x {t+1} = (A - BF + CK) x t.

Arguments

• rlq::RBLQ: Instance of RBLQ type

• F::Matrix{Float64} The policy function, a k x n array

• K::Matrix{Float64} The worst case matrix, a j x n array

• x0::Vector{Float64} : The initial condition for state

Returns

• e::Float64 The deterministic entropy

Page 70: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.19. QUANTECON.COMPUTE FIXED POINT 65

2.19 QuantEcon.compute fixed point

QuantEcon.compute fixed point — Method.Repeatedly apply a function to search for a fixed pointApproximates T^ v, where T is an operator (function) and v is an initial

guess for the fixed point. Will terminate either when T^{k+1}(v) - T^k v <err tol or max iter iterations has been exceeded.

Provided that T is a contraction mapping or similar, the return value will bean approximation to the fixed point of T.

Arguments

• T: A function representing the operator T

• v::TV: The initial condition. An object of type TV

• ;err tol(1e-3): Stopping tolerance for iterations

• ;max iter(50): Maximum number of iterations

• ;verbose(2): Level of feedback (0 for no output, 1 for warnings only, 2for warning and convergence messages during iteration)

• ;print skip(10) : if verbose == 2, how many iterations to apply be-tween print messages

Returns

• ‘::TV’: The fixed point of the operator T. Has type TV

Example[] using QuantEcon T(x, ) = 4.0 * * x * (1.0 - x) xstar = computef ixedpoint(x− >

T (x, 0.3),0.4)(4− 1)/(4)

2.20 QuantEcon.compute greedy!

QuantEcon.compute greedy! — Method.Compute the v-greedy policyParameters

• ddp::DiscreteDP : Object that contains the model parameters

• ddpr::DPSolveResult : Object that contains result variables

Returns

• sigma::Vector{Int} : Array containing v-greedy policy rule

Notesmodifies ddpr.sigma and ddpr.Tv in place

Page 71: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

66 CHAPTER 2. QUANTECON

2.21 QuantEcon.compute greedy

QuantEcon.compute greedy — Method.

Compute the v-greedy policy.

Arguments

• v::Vector Value function vector of length n

• ddp::DiscreteDP Object that contains the model parameters

Returns

• sigma:: v-greedy policy vector, of lengthn‘

2.22 QuantEcon.compute sequence

QuantEcon.compute sequence — Function.

Compute and return the optimal state and control sequence, assuming in-novation N(0,1)

Arguments

• lq::LQ : instance of LQ type

• x0::ScalarOrArray: initial state

• ts length::Integer(100) : maximum number of periods for which toreturn

process. If lq instance is finite horizon type, the sequenes are returned onlyfor min(ts length, lq.capT)

Returns

• x path::Matrix{Float64} : An n x T+1 matrix, where the t-th column

represents x t

• u path::Matrix{Float64} : A k x T matrix, where the t-th column rep-resents

u t

• w path::Matrix{Float64} : A n x T+1 matrix, where the t-th columnrepresents

lq.C*N(0,1)

Page 72: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.23. QUANTECON.D OPERATOR 67

2.23 QuantEcon.d operator

QuantEcon.d operator — Method.

The D operator, mapping P into

D(P) := P + PC(theta I - C’PC)^{-1} C’P.

Arguments

• rlq::RBLQ: Instance of RBLQ type

• P::Matrix{Float64} : size is n x n

Returns

• dP::Matrix{Float64} : The matrix P after applying the D operator

2.24 QuantEcon.divide bracket

QuantEcon.divide bracket — Function.

Given a function f defined on the interval [x1, x2], subdivide the intervalinto n equally spaced segments, and search for zero crossings of the function.nroot will be set to the number of bracketing pairs found. If it is positive, thearrays xb1[1..nroot] and xb2[1..nroot] will be filled sequentially with anybracketing pairs that are found.

Arguments

• f::Function: The function you want to bracket

• x1::T: Lower border for search interval

• x2::T: Upper border for search interval

• n::Int(50): The number of sub-intervals to divide [x1, x2] into

Returns

• x1b::Vector{T}: Vector of lower borders of bracketing intervals

• x2b::Vector{T}: Vector of upper borders of bracketing intervals

References

This is zbrack from Numerical Recepies Recepies in C++

Page 73: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

68 CHAPTER 2. QUANTECON

2.25 QuantEcon.do quad

QuantEcon.do quad — Method.Approximate the integral of f, given quadrature nodes and weights

Arguments

• f::Function: A callable function that is to be approximated over thedomain

spanned by nodes.

• nodes::Array: Quadrature nodes

• weights::Array: Quadrature nodes

• args...(Void): additional positional arguments to pass to f

• ;kwargs...(Void): additional keyword arguments to pass to f

Returns

• out::Float64 : The scalar that approximates integral of f on the hyper-cube

formed by [a, b]

2.26 QuantEcon.draw

QuantEcon.draw — Method.Make multiple draws from the discrete distribution represented by a DiscreteRV

instanceArguments

• d::DiscreteRV: The DiscreteRV type representing the distribution

• k::Int:

Returns

• out::Vector{Int}: k draws from d

2.27 QuantEcon.draw

QuantEcon.draw — Method.Make a single draw from the discrete distributionArguments

• d::DiscreteRV: The DiscreteRV type represetning the distribution

Returns

• out::Int: One draw from the discrete distribution

Page 74: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.28. QUANTECON.ECDF 69

2.28 QuantEcon.ecdf

QuantEcon.ecdf — Function.Evaluate the empirical cdf at one or more pointsArguments

• e::ECDF: The ECDF instance

• x::Union{Real, Array}: The point(s) at which to evaluate the ECDF

2.29 QuantEcon.evaluate F

QuantEcon.evaluate F — Method.Given a fixed policy F, with the interpretation u = -F x, this function com-

putes the matrix P F and constant d F associated with discounted cost J F(x)= x’ P F x + d F.

Arguments

• rlq::RBLQ: Instance of RBLQ type

• F::Matrix{Float64} : The policy function, a k x n array

Returns

• P F::Matrix{Float64} : Matrix for discounted cost

• d F::Float64 : Constant for discounted cost

• K F::Matrix{Float64} : Worst case policy

• O F::Matrix{Float64} : Matrix for discounted entropy

• o F::Float64 : Constant for discounted entropy

2.30 QuantEcon.evaluate policy

QuantEcon.evaluate policy — Method.Compute the value of a policy.Parameters

• ddp::DiscreteDP : Object that contains the model parameters

• sigma::Vector{T<:Integer} : Policy rule vector

Returns

• v sigma::Array{Float64} : Value vector of sigma, of length n.

Page 75: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

70 CHAPTER 2. QUANTECON

2.31 QuantEcon.evaluate policy

QuantEcon.evaluate policy — Method.Method of evaluate policy that extracts sigma from a DPSolveResult

See other docstring for details

2.32 QuantEcon.expand bracket

QuantEcon.expand bracket — Method.Given a function f and an initial guessed range x1 to x2, the routine expands

the range geometrically until a root is bracketed by the returned values x1 andx2 (in which case zbrac returns true) or until the range becomes unacceptablylarge (in which case a ConvergenceError is thrown).

Arguments

• f::Function: The function you want to bracket

• x1::T: Initial guess for lower border of bracket

• x2::T: Initial guess ofr upper border of bracket

• ;ntry::Int(50): The maximum number of expansion iterations

• ;fac::Float64(1.6): Expansion factor (higher larger interval size jumps)

Returns

• x1::T: The lower end of an actual bracketing interval

• x2::T: The upper end of an actual bracketing interval

ReferencesThis method is zbrac from numerical recipies in C++Exceptions

• Throws a ConvergenceError if the maximum number of iterations is ex-ceeded

2.33 QuantEcon.filtered to forecast!

QuantEcon.filtered to forecast! — Method.Updates the moments of the time t filtering distribution to the moments of

the predictive distribution, which becomes the time t+1 priorArguments

• k::Kalman An instance of the Kalman filter

Page 76: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.34. QUANTECON.GRIDMAKE 71

2.34 QuantEcon.gridmake

QuantEcon.gridmake — Function.gridmake(arrays::AbstractVector...)

Expand one or more vectors into a matrix where rows span the cartesianproduct of combinations of the input vectors. Each input array will correspondto one column of the output matrix. The first array varies the fastest (seeexample)

Example

julia> x = [1, 2, 3]; y = [10, 20]; z = [100, 200];

julia> gridmake(x, y, z)

12x3 Array{Int64,2}:

1 10 100

2 10 100

3 10 100

1 20 100

2 20 100

3 20 100

1 10 200

2 10 200

3 10 200

1 20 200

2 20 200

3 20 200

2.35 QuantEcon.gridmake!

QuantEcon.gridmake! — Method.gridmake!(out::AbstractMatrix, arrays::AbstractVector...)

Like gridmake, but fills a pre-populated array. out must have size prod(map(length,arrays), length(arrays))

2.36 QuantEcon.gth solve

QuantEcon.gth solve — Method.This routine computes the stationary distribution of an irreducible Markov

transition matrix (stochastic matrix) or transition rate matrix (generator ma-trix) A.

More generally, given a Metzler matrix (square matrix whose off-diagonalentries are all nonnegative) A, this routine solves for a nonzero solution x tox (A - D) = 0, where D is the diagonal matrix for which the rows of A - D

sum to zero (i.e., D {ii} = sum j A {ij} for all i). One (and only one, up tonormalization) nonzero solution exists corresponding to each reccurent class of

Page 77: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

72 CHAPTER 2. QUANTECON

A, and in particular, if A is irreducible, there is a unique solution; when thereare more than one solution, the routine returns the solution that contains inits support the first index i such that no path connects i to any index largerthan i. The solution is normalized so that its 1-norm equals one. This rou-tine implements the Grassmann-Taksar-Heyman (GTH) algorithm (Grassmann,Taksar, and Heyman 1985), a numerically stable variant of Gaussian elimina-tion, where only the off-diagonal entries of A are used as the input data. For anice exposition of the algorithm, see Stewart (2009), Chapter 10.

Arguments

• A::Matrix{T} : Stochastic matrix or generator matrix. Must be of shapen x n.

Returns

• x::Vector{T} : Stationary distribution of A.

References

• W. K. Grassmann, M. I. Taksar and D. P. Heyman, “Regenerative Anal-ysis and

Steady State Distributions for Markov Chains, ” Operations Research (1985),1107-1116.

• W. J. Stewart, Probability, Markov Chains, Queues, and Simulation,Princeton

University Press, 2009.

2.37 QuantEcon.impulse response

QuantEcon.impulse response — Method.Get the impulse response corresponding to our model.Arguments

• arma::ARMA: Instance of ARMA type

• ;impulse length::Integer(30): Length of horizon for calucluating im-pulse

reponse. Must be at least as long as the p fields of armaReturns

• psi::Vector{Float64}: psi[j] is the response at lag j of the impulse

response. We take psi[1] as unity.

Page 78: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.38. QUANTECON.INTERP 73

2.38 QuantEcon.interp

QuantEcon.interp — Method.

interp(grid::AbstractVector, function_vals::AbstractVector)

Linear interpolation in one dimensionExamples[] breaks = cumsum(0.1 .* rand(20)) vals = 0.1 .* sin.(breaks) li = in-

terp(breaks, vals)Do interpolation by treating ‘li‘ as a function you can pass scalars to li(0.2)use broadcasting to evaluate at multiple points li.([0.1, 0.2, 0.3])

2.39 QuantEcon.is aperiodic

QuantEcon.is aperiodic — Method.Indicate whether the Markov chain mc is aperiodic.Arguments

• mc::MarkovChain : MarkovChain instance.

Returns

• ::Bool

2.40 QuantEcon.is irreducible

QuantEcon.is irreducible — Method.Indicate whether the Markov chain mc is irreducible.Arguments

• mc::MarkovChain : MarkovChain instance.

Returns

• ::Bool

2.41 QuantEcon.lae est

QuantEcon.lae est — Method.A vectorized function that returns the value of the look ahead estimate at

the values in the array y.Arguments

• l::LAE: Instance of LAE type

• y::Array: Array that becomes the y in l.p(l.x, y)

Returns

• psi vals::Vector: Density at (x, y)

Page 79: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

74 CHAPTER 2. QUANTECON

2.42 QuantEcon.m quadratic sum

QuantEcon.m quadratic sum — Method.

Computes the quadratic sum

V = sum_{j=0}^{infty} A^j B A^{j’}

V is computed by solving the corresponding discrete lyapunov equation usingthe doubling algorithm. See the documentation of solve discrete lyapunov

for more information.

Arguments

• A::Matrix{Float64} : An n x n matrix as described above. We assumein order

for convergence that the eigenvalues of A have moduli bounded by unity

• B::Matrix{Float64} : An n x n matrix as described above. We assumein order

for convergence that the eigenvalues of B have moduli bounded by unity

• max it::Int(50) : Maximum number of iterations

Returns

• gamma1::Matrix{Float64} : Represents the value V

2.43 QuantEcon.moment sequence

QuantEcon.moment sequence — Method.

Create a generator to calculate the population mean and variance-convariancematrix for both x t and y t, starting at the initial condition (self.mu 0, self.Sigma 0).Each iteration produces a 4-tuple of items (mu x, mu y, Sigma x, Sigma y) forthe next period.

Arguments

• lss::LSS An instance of the Gaussian linear state space model

2.44 QuantEcon.n states

QuantEcon.n states — Method.

Number of states in the Markov chain mc

Page 80: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.45. QUANTECON.NNASH 75

2.45 QuantEcon.nnash

QuantEcon.nnash — Method.Compute the limit of a Nash linear quadratic dynamic game.Player i minimizes

sum_{t=1}^{inf}(x_t’ r_i x_t + 2 x_t’ w_i

u_{it} +u_{it}’ q_i u_{it} + u_{jt}’ s_i u_{jt} + 2 u_{jt}’

m_i u_{it})

subject to the law of motion

x_{t+1} = A x_t + b_1 u_{1t} + b_2 u_{2t}

and a perceived control law :math:u j(t) = - f j x t for the other player.The solution computed in this routine is the f i and p i of the associated

double optimal linear regulator problem.Arguments

• A : Corresponds to the above equation, should be of size (n, n)

• B1 : As above, size (n, k 1)

• B2 : As above, size (n, k 2)

• R1 : As above, size (n, n)

• R2 : As above, size (n, n)

• Q1 : As above, size (k 1, k 1)

• Q2 : As above, size (k 2, k 2)

• S1 : As above, size (k 1, k 1)

• S2 : As above, size (k 2, k 2)

• W1 : As above, size (n, k 1)

• W2 : As above, size (n, k 2)

• M1 : As above, size (k 2, k 1)

• M2 : As above, size (k 1, k 2)

• ;beta::Float64(1.0) Discount rate

• ;tol::Float64(1e-8) : Tolerance level for convergence

• ;max iter::Int(1000) : Maximum number of iterations allowed

Returns

Page 81: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

76 CHAPTER 2. QUANTECON

• F1::Matrix{Float64}: (k 1, n) matrix representing feedback law foragent 1

• F2::Matrix{Float64}: (k 2, n) matrix representing feedback law foragent 2

• P1::Matrix{Float64}: (n, n) matrix representing the steady-state solu-tion to the associated discrete matrix ticcati equation for agent 1

• P2::Matrix{Float64}: (n, n) matrix representing the steady-state solu-tion to the associated discrete matrix riccati equation for agent 2

2.46 QuantEcon.periodogram

QuantEcon.periodogram — Function.Computes the periodogram

I(w) = (1 / n) | sum_{t=0}^{n-1} x_t e^{itw} |^2

at the Fourier frequences w j := 2 pi j / n, j = 0, . . . , n - 1, using the fastFourier transform. Only the frequences w j in [0, pi] and corresponding valuesI(w j) are returned. If a window type is given then smoothing is performed.

Arguments

• x::Array: An array containing the data to smooth

• window len::Int(7): An odd integer giving the length of the window

• window::AbstractString("hanning"): A string giving the window type.Possible values

are flat, hanning, hamming, bartlett, or blackmanReturns

• w::Array{Float64}: Fourier frequencies at which the periodogram isevaluated

• I w::Array{Float64}: The periodogram at frequences w

2.47 QuantEcon.prior to filtered!

QuantEcon.prior to filtered! — Method.Updates the moments (cur x hat, cur sigma) of the time t prior to the time t

filtering distribution, using current measurement y t. The updates are accordingto x {hat}ˆF = x {hat} + Sigma G’ (G Sigma G’ + R)ˆ{-1} (y - G x {hat})SigmaˆF = Sigma - Sigma G’ (G Sigma G’ + R)ˆ{-1} G Sigma

Arguments

• k::Kalman An instance of the Kalman filter

• y The current measurement

Page 82: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.48. QUANTECON.QNWBETA 77

2.48 QuantEcon.qnwbeta

QuantEcon.qnwbeta — Method.Computes nodes and weights for beta distributionArguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• a::Union{Real, Vector{Real}} : First parameter of the beta distribu-tion,

along each dimension

• b::Union{Real, Vector{Real}} : Second parameter of the beta distri-bution,

along each dimensionReturns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

NotesIf any of the parameters to this function are scalars while others are Vectors

of length n, the the scalar parameter is repeated n times.ReferencesMiranda, Mario J, and Paul L Fackler. Applied Computational Economics

and Finance, MIT Press, 2002.

2.49 QuantEcon.qnwcheb

QuantEcon.qnwcheb — Method.Computes multivariate Guass-Checbychev quadrature nodes and weights.Arguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• a::Union{Real, Vector{Real}} : Lower endpoint along each dimension

• b::Union{Real, Vector{Real}} : Upper endpoint along each dimension

Returns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

Page 83: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

78 CHAPTER 2. QUANTECON

Notes

If any of the parameters to this function are scalars while others are Vectorsof length n, the the scalar parameter is repeated n times.

References

Miranda, Mario J, and Paul L Fackler. Applied Computational Economicsand Finance, MIT Press, 2002.

2.50 QuantEcon.qnwequi

QuantEcon.qnwequi — Function.

Generates equidistributed sequences with property that averages value ofintegrable function evaluated over the sequence converges to the integral as ngoes to infinity.

Arguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• a::Union{Real, Vector{Real}} : Lower endpoint along each dimension

• b::Union{Real, Vector{Real}} : Upper endpoint along each dimension

• kind::AbstractString("N"): One of the following:

– N - Neiderreiter (default)

– W - Weyl

– H - Haber

– R - pseudo Random

Returns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

Notes

If any of the parameters to this function are scalars while others are Vectorsof length n, the the scalar parameter is repeated n times.

References

Miranda, Mario J, and Paul L Fackler. Applied Computational Economicsand Finance, MIT Press, 2002.

Page 84: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.51. QUANTECON.QNWGAMMA 79

2.51 QuantEcon.qnwgamma

QuantEcon.qnwgamma — Function.Computes nodes and weights for beta distributionArguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• a::Union{Real, Vector{Real}} : First parameter of the gamma distri-bution,

along each dimension

• b::Union{Real, Vector{Real}} : Second parameter of the gamma dis-tribution,

along each dimensionReturns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

NotesIf any of the parameters to this function are scalars while others are Vectors

of length n, the the scalar parameter is repeated n times.ReferencesMiranda, Mario J, and Paul L Fackler. Applied Computational Economics

and Finance, MIT Press, 2002.

2.52 QuantEcon.qnwlege

QuantEcon.qnwlege — Method.Computes multivariate Guass-Legendre quadrature nodes and weights.Arguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• a::Union{Real, Vector{Real}} : Lower endpoint along each dimension

• b::Union{Real, Vector{Real}} : Upper endpoint along each dimension

Returns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

Page 85: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

80 CHAPTER 2. QUANTECON

NotesIf any of the parameters to this function are scalars while others are Vectors

of length n, the the scalar parameter is repeated n times.ReferencesMiranda, Mario J, and Paul L Fackler. Applied Computational Economics

and Finance, MIT Press, 2002.

2.53 QuantEcon.qnwlogn

QuantEcon.qnwlogn — Method.Computes quadrature nodes and weights for multivariate uniform distribu-

tionArguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• mu::Union{Real, Vector{Real}} : Mean along each dimension

• sig2::Union{Real, Vector{Real}, Matrix{Real}}(eye(length(n))) :Covariance

structureReturns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

NotesSee also the documentation for qnwnormReferencesMiranda, Mario J, and Paul L Fackler. Applied Computational Economics

and Finance, MIT Press, 2002.

2.54 QuantEcon.qnwnorm

QuantEcon.qnwnorm — Method.Computes nodes and weights for multivariate normal distributionArguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• mu::Union{Real, Vector{Real}} : Mean along each dimension

• sig2::Union{Real, Vector{Real}, Matrix{Real}}(eye(length(n))) :Covariance

Page 86: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.55. QUANTECON.QNWSIMP 81

structureReturns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

NotesThis function has many methods. I try to describe them here.n or mu can be a vector or a scalar. If just one is a scalar the other is repeated

to match the length of the other. If both are scalars, then the number of repeatsis inferred from sig2.

sig2 can be a matrix, vector or scalar. If it is a matrix, it is treated as thecovariance matrix. If it is a vector, it is considered the diagonal of a diagonalcovariance matrix. If it is a scalar it is repeated along the diagonal as manytimes as necessary, where the number of repeats is determined by the length ofeither n and/or mu (which ever is a vector).

If all 3 are scalars, then 1d nodes are computed. mu and sig2 are treated asthe mean and variance of a 1d normal distribution

ReferencesMiranda, Mario J, and Paul L Fackler. Applied Computational Economics

and Finance, MIT Press, 2002.

2.55 QuantEcon.qnwsimp

QuantEcon.qnwsimp — Method.Computes multivariate Simpson quadrature nodes and weights.Arguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• a::Union{Real, Vector{Real}} : Lower endpoint along each dimension

• b::Union{Real, Vector{Real}} : Upper endpoint along each dimension

Returns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

NotesIf any of the parameters to this function are scalars while others are Vectors

of length n, the the scalar parameter is repeated n times.ReferencesMiranda, Mario J, and Paul L Fackler. Applied Computational Economics

and Finance, MIT Press, 2002.

Page 87: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

82 CHAPTER 2. QUANTECON

2.56 QuantEcon.qnwtrap

QuantEcon.qnwtrap — Method.Computes multivariate trapezoid quadrature nodes and weights.Arguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• a::Union{Real, Vector{Real}} : Lower endpoint along each dimension

• b::Union{Real, Vector{Real}} : Upper endpoint along each dimension

Returns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

NotesIf any of the parameters to this function are scalars while others are Vectors

of length n, the the scalar parameter is repeated n times.ReferencesMiranda, Mario J, and Paul L Fackler. Applied Computational Economics

and Finance, MIT Press, 2002.

2.57 QuantEcon.qnwunif

QuantEcon.qnwunif — Method.Computes quadrature nodes and weights for multivariate uniform distribu-

tionArguments

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• a::Union{Real, Vector{Real}} : Lower endpoint along each dimension

• b::Union{Real, Vector{Real}} : Upper endpoint along each dimension

Returns

• nodes::Array{Float64} : An array of quadrature nodes

• weights::Array{Float64} : An array of corresponding quadrature weights

NotesIf any of the parameters to this function are scalars while others are Vectors

of length n, the the scalar parameter is repeated n times.ReferencesMiranda, Mario J, and Paul L Fackler. Applied Computational Economics

and Finance, MIT Press, 2002.

Page 88: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.58. QUANTECON.QUADRECT 83

2.58 QuantEcon.quadrect

QuantEcon.quadrect — Function.Integrate the d-dimensional function f on a rectangle with lower and upper

bound for dimension i defined by a[i] and b[i], respectively; using n[i] points.Arguments

• f::Function The function to integrate over. This should be a functionthat

accepts as its first argument a matrix representing points along each dimen-sion (each dimension is a column). Other arguments that need to be passed tothe function are caught by args... and ‘kwargs. . . “

• n::Union{Int, Vector{Int}} : Number of desired nodes along each di-mension

• a::Union{Real, Vector{Real}} : Lower endpoint along each dimension

• b::Union{Real, Vector{Real}} : Upper endpoint along each dimension

• kind::AbstractString("lege") Specifies which type of integration toperform. Valid

values are: - "lege" : Gauss-Legendre - "cheb" : Gauss-Chebyshev - "trap": trapezoid rule - "simp" : Simpson rule - "N" : Neiderreiter equidistributedsequence - "W" : Weyl equidistributed sequence - "H" : Haber equidistributedsequence - "R" : Monte Carlo - args...(Void): additional positional argumentsto pass to f - ;kwargs...(Void): additional keyword arguments to pass to f

Returns

• out::Float64 : The scalar that approximates integral of f on the hyper-cube

formed by [a, b]

ReferencesMiranda, Mario J, and Paul L Fackler. Applied Computational Economics

and Finance, MIT Press, 2002.

2.59 QuantEcon.random discrete dp

QuantEcon.random discrete dp — Function.Generate a DiscreteDP randomly. The reward values are drawn from the

normal distribution with mean 0 and standard deviation scale.Arguments

• num states::Integer : Number of states.

Page 89: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

84 CHAPTER 2. QUANTECON

• num actions::Integer : Number of actions.

• beta::Union{Float64, Void}(nothing) : Discount factor. Randomlychosen from

[0, 1) if not specified.

• ;k::Union{Integer, Void}(nothing) : Number of possible next statesfor each

state-action pair. Equal to num states if not specified.

• scale::Real(1) : Standard deviation of the normal distribution for the

reward values.Returns

• ddp::DiscreteDP : An instance of DiscreteDP.

2.60 QuantEcon.random markov chain

QuantEcon.random markov chain — Method.Return a randomly sampled MarkovChain instance with n states, where each

state has k states with positive transition probability.Arguments

• n::Integer : Number of states.

Returns

• mc::MarkovChain : MarkovChain instance.

Examples[] julia¿ using QuantEconjulia¿ mc = randommarkovchain(3,2)DiscreteMarkovChainstochasticmatrix :3x3Array{Float64,2} :0.3691240.00.6308760.5190350.4809650.00.00.7446140.255386

2.61 QuantEcon.random markov chain

QuantEcon.random markov chain — Method.Return a randomly sampled MarkovChain instance with n states.Arguments

• n::Integer : Number of states.

Returns

• mc::MarkovChain : MarkovChain instance.

Examples[] julia¿ using QuantEconjulia¿ mc = randommarkovchain(3)DiscreteMarkovChainstochasticmatrix :3x3Array{Float64,2} :0.2811880.617990.1008220.1444610.8481790.00735940.3601150.3239730.315912

Page 90: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.62. QUANTECON.RANDOM STOCHASTIC MATRIX 85

2.62 QuantEcon.random stochastic matrix

QuantEcon.random stochastic matrix — Function.Return a randomly sampled n x n stochastic matrix with k nonzero entries

for each row.Arguments

• n::Integer : Number of states.

• k::Union{Integer, Void}(nothing) : Number of nonzero entries ineach

column of the matrix. Set to n if note specified.Returns

• p::Array : Stochastic matrix.

2.63 QuantEcon.recurrent classes

QuantEcon.recurrent classes — Method.Find the recurrent classes of the Markov chain mc.Arguments

• mc::MarkovChain : MarkovChain instance.

Returns

• ::Vector{Vector{Int}} : Vector of vectors that describe the recurrent

classes of mc.

2.64 QuantEcon.replicate

QuantEcon.replicate — Function.Simulate num reps observations of x T and y T given x 0 ˜ N(mu 0, Sigma 0).Arguments

• lss::LSS An instance of the Gaussian linear state space model.

• t::Int = 10 The period that we want to replicate values for.

• num reps::Int = 100 The number of replications we want

Returns

• x::Matrix An n x num reps matrix, where the j-th column is the j thobservation of x T

• y::Matrix An k x num reps matrix, where the j-th column is the j thobservation of y T

Page 91: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

86 CHAPTER 2. QUANTECON

2.65 QuantEcon.ridder

QuantEcon.ridder — Method.Find a root of the f on the bracketing inverval [x1, x2] via ridder algoArguments

• f::Function: The function you want to bracket

• x1::T: Lower border for search interval

• x2::T: Upper border for search interval

• ;maxiter::Int(500): Maximum number of bisection iterations

• ;xtol::Float64(1e-12): The routine converges when a root is known tolie

within xtol of the value return. Should be >= 0. The routine modifies thisto take into account the relative precision of doubles.

• ;rtol::Float64(2*eps()):The routine converges when a root is knownto lie

within rtol times the value returned of the value returned. Should be 0Returns

• x::T: The found root

Exceptions

• Throws an ArgumentError if [x1, x2] does not form a bracketing interval

• Throws a ConvergenceError if the maximum number of iterations is ex-ceeded

ReferencesMatches ridder function from scipy/scipy/optimize/Zeros/ridder.c

2.66 QuantEcon.robust rule

QuantEcon.robust rule — Method.Solves the robust control problem.The algorithm here tricks the problem into a stacked LQ problem, as de-

scribed in chapter 2 of Hansen- Sargent’s text “Robustness.” The optimal con-trol with observed state is

u_t = - F x_t

And the value function is -x’PxArguments

Page 92: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.67. QUANTECON.ROBUST RULE SIMPLE 87

• rlq::RBLQ: Instance of RBLQ type

Returns

• F::Matrix{Float64} : The optimal control matrix from above

• P::Matrix{Float64} : The positive semi-definite matrix defining thevalue

function

• K::Matrix{Float64} : the worst-case shock matrix K, where

w {t+1} = K x t is the worst case shock

2.67 QuantEcon.robust rule simple

QuantEcon.robust rule simple — Function.Solve the robust LQ problemA simple algorithm for computing the robust policy F and the correspond-

ing value function P, based around straightforward iteration with the robustBellman operator. This function is easier to understand but one or two or-ders of magnitude slower than self.robust rule(). For more information see thedocstring of that method.

Arguments

• rlq::RBLQ: Instance of RBLQ type

• P init::Matrix{Float64}(zeros(rlq.n, rlq.n)) : The initial guessfor the

value function matrix

• ;max iter::Int(80): Maximum number of iterations that are allowed

• ;tol::Real(1e-8) The tolerance for convergence

Returns

• F::Matrix{Float64} : The optimal control matrix from above

• P::Matrix{Float64} : The positive semi-definite matrix defining thevalue

function

• K::Matrix{Float64} : the worst-case shock matrix K, where

w {t+1} = K x t is the worst case shock

Page 93: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

88 CHAPTER 2. QUANTECON

2.68 QuantEcon.rouwenhorst

QuantEcon.rouwenhorst — Function.Rouwenhorst’s method to approximate AR(1) processes.The process follows

y_t = + y_{t-1} + _t,

where t ˜ N (0, ˆ2)Arguments

• N::Integer : Number of points in markov process

• ::Real : Persistence parameter in AR(1) process

• ::Real : Standard deviation of random component of AR(1) process

• ::Real(0.0) : Mean of AR(1) process

Returns

• mc::MarkovChain{Float64} : Markov chain holding the state values and

transition matrix

2.69 QuantEcon.simulate!

QuantEcon.simulate! — Method.Fill X with sample paths of the Markov chain mc as columns. The resulting

matrix has the state values of mc as elements.Arguments

• X::Matrix : Preallocated matrix to be filled with sample paths

of the Markov chain mc. The element types in X should be the same as thetype of the state values of mc

• mc::MarkovChain : MarkovChain instance.

• ;init=rand(1:n states(mc)) : Can be one of the following

– blank: random initial condition for each chain

– scalar: same initial condition for each chain

– vector: cycle through the elements, applying each as an initial con-dition until all columns have an initial condition (allows for morecolumns than initial conditions)

Page 94: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.70. QUANTECON.SIMULATE 89

2.70 QuantEcon.simulate

QuantEcon.simulate — Method.Simulate one sample path of the Markov chain mc. The resulting vector has

the state values of mc as elements.Arguments

• mc::MarkovChain : MarkovChain instance.

• ts length::Int : Length of simulation

• ;init::Int=rand(1:n states(mc)) : Initial state

Returns

• X::Vector : Vector containing the sample path, with length

ts length

2.71 QuantEcon.simulate indices!

QuantEcon.simulate indices! — Method.Fill X with sample paths of the Markov chain mc as columns. The resulting

matrix has the indices of the state values of mc as elements.Arguments

• X::Matrix{Int} : Preallocated matrix to be filled with indices

of the sample paths of the Markov chain mc.

• mc::MarkovChain : MarkovChain instance.

• ;init=rand(1:n states(mc)) : Can be one of the following

– blank: random initial condition for each chain

– scalar: same initial condition for each chain

– vector: cycle through the elements, applying each as an initial con-dition until all columns have an initial condition (allows for morecolumns than initial conditions)

2.72 QuantEcon.simulate indices

QuantEcon.simulate indices — Method.Simulate one sample path of the Markov chain mc. The resulting vector has

the indices of the state values of mc as elements.Arguments

Page 95: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

90 CHAPTER 2. QUANTECON

• mc::MarkovChain : MarkovChain instance.

• ts length::Int : Length of simulation

• ;init::Int=rand(1:n states(mc)) : Initial state

Returns

• X::Vector{Int} : Vector containing the sample path, with length

ts length

2.73 QuantEcon.simulation

QuantEcon.simulation — Method.Compute a simulated sample path assuming Gaussian shocks.Arguments

• arma::ARMA: Instance of ARMA type

• ;ts length::Integer(90): Length of simulation

• ;impulse length::Integer(30): Horizon for calculating impulse response

(see also docstring for impulse response)Returns

• X::Vector{Float64}: Simulation of the ARMA model arma

2.74 QuantEcon.smooth

QuantEcon.smooth — Function.Smooth the data in x using convolution with a window of requested size and

type.Arguments

• x::Array: An array containing the data to smooth

• window len::Int(7): An odd integer giving the length of the window

• window::AbstractString("hanning"): A string giving the window type.Possible values

are flat, hanning, hamming, bartlett, or blackmanReturns

• out::Array: The array of smoothed data

Page 96: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.75. QUANTECON.SMOOTH 91

2.75 QuantEcon.smooth

QuantEcon.smooth — Method.Version of smooth where window len and window are keyword arguments

2.76 QuantEcon.solve

QuantEcon.solve — Function.Solve the dynamic programming problem.Parameters

• ddp::DiscreteDP : Object that contains the Model Parameters

• method::Type{T<Algo}(VFI): Type name specifying solution method.Acceptable

arguments are VFI for value function iteration or PFI for policy functioniteration or MPFI for modified policy function iteration

• ;max iter::Int(250) : Maximum number of iterations

• ;epsilon::Float64(1e-3) : Value for epsilon-optimality. Only used if

method is VFI

• ;k::Int(20) : Number of iterations for partial policy evaluation in mod-ified

policy iteration (irrelevant for other methods).Returns

• ddpr::DPSolveResult{Algo} : Optimization result represented as a

DPSolveResult. See DPSolveResult for details.

2.77 QuantEcon.solve discrete lyapunov

QuantEcon.solve discrete lyapunov — Function.Solves the discrete lyapunov equation.The problem is given by

AXA’ - X + B = 0

X is computed by using a doubling algorithm. In particular, we iterate toconvergence on X j with the following recursions for j = 1, 2,. . . starting fromX 0 = B, a 0 = A:

Page 97: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

92 CHAPTER 2. QUANTECON

a_j = a_{j-1} a_{j-1}

X_j = X_{j-1} + a_{j-1} X_{j-1} a_{j-1}’

Arguments

• A::Matrix{Float64} : An n x n matrix as described above. We assumein order

for convergence that the eigenvalues of A have moduli bounded by unity

• B::Matrix{Float64} : An n x n matrix as described above. We assumein order

for convergence that the eigenvalues of B have moduli bounded by unity

• max it::Int(50) : Maximum number of iterations

Returns

• gamma1::Matrix{Float64} Represents the value X

2.78 QuantEcon.solve discrete riccati

QuantEcon.solve discrete riccati — Function.Solves the discrete-time algebraic Riccati equationThe prolem is defined as

X = A’XA - (N + B’XA)’(B’XB + R)^{-1}(N + B’XA) + Q

via a modified structured doubling algorithm. An explanation of the algo-rithm can be found in the reference below.

Arguments

• A : k x k array.

• B : k x n array

• R : n x n, should be symmetric and positive definite

• Q : k x k, should be symmetric and non-negative definite

• N::Matrix{Float64}(zeros(size(R, 1), size(Q, 1))) : n x k array

• tolerance::Float64(1e-10) Tolerance level for convergence

• max iter::Int(50) : The maximum number of iterations allowed

Note that A, B, R, Q can either be real (i.e. k, n = 1) or matrices.Returns

Page 98: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.79. QUANTECON.SPECTRAL DENSITY 93

• X::Matrix{Float64} The fixed point of the Riccati equation; a k x karray

representing the approximate solutionReferencesChiang, Chun-Yueh, Hung-Yuan Fan, and Wen-Wei Lin. “STRUCTURED

DOUBLING ALGORITHM FOR DISCRETE-TIME ALGEBRAIC RICCATIEQUATIONS WITH SINGULAR CONTROL WEIGHTING MATRICES.” Tai-wanese Journal of Mathematics 14, no. 3A (2010): pp-935.

2.79 QuantEcon.spectral density

QuantEcon.spectral density — Method.Compute the spectral density function.The spectral density is the discrete time Fourier transform of the autoco-

variance function. In particular,

f(w) = sum_k gamma(k) exp(-ikw)

where gamma is the autocovariance function and the sum is over the set ofall integers.

Arguments

• arma::ARMA: Instance of ARMA type

• ;two pi::Bool(true): Compute the spectral density function over [0, pi]if false and [0, 2 pi] otherwise.

• ;res(1200) : If res is a scalar then the spectral density is computed at

res frequencies evenly spaced around the unit circle, but if res is an arraythen the function computes the response at the frequencies given by the array

Returns

• w::Vector{Float64}: The normalized frequencies at which h was com-puted, in radians/sample

• spect::Vector{Float64} : The frequency response

2.80 QuantEcon.stationary distributions

QuantEcon.stationary distributions — Function.Compute stationary distributions of the Markov chain mc, one for each re-

current class.Arguments

• mc::MarkovChain{T} : MarkovChain instance.

Page 99: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

94 CHAPTER 2. QUANTECON

Returns

• stationary dists::Vector{Vector{T1}} : Vector of vectors that repre-sent stationary distributions, where the element type T1 is Rational if Tis Int (and equal to T otherwise).

2.81 QuantEcon.stationary distributions

QuantEcon.stationary distributions — Method.Compute the moments of the stationary distributions of x t and y t if pos-

sible. Computation is by iteration, starting from the initial conditions lss.mu 0and lss.Sigma 0

Arguments

• lss::LSS An instance of the Guassian linear state space model

• ;max iter::Int = 200 The maximum number of iterations allowed

• ;tol::Float64 = 1e-5 The tolerance level one wishes to achieve

Returns

• mu x::Vector Represents the stationary mean of x t

• mu y::VectorRepresents the stationary mean of y t

• Sigma x::Matrix Represents the var-cov matrix

• Sigma y::Matrix Represents the var-cov matrix

2.82 QuantEcon.stationary values!

QuantEcon.stationary values! — Method.Computes value and policy functions in infinite horizon modelArguments

• lq::LQ : instance of LQ type

Returns

• P::ScalarOrArray : n x n matrix in value function representation

V(x) = x’Px + d

• d::Real : Constant in value function representation

• F::ScalarOrArray : Policy rule that specifies optimal control in eachperiod

NotesThis function updates the P, d, and F fields on the lq instance in addition

to returning them

Page 100: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.83. QUANTECON.STATIONARY VALUES 95

2.83 QuantEcon.stationary values

QuantEcon.stationary values — Method.Non-mutating routine for solving for P, d, and F in infinite horizon modelSee docstring for stationary values! for more explanation

2.84 QuantEcon.tauchen

QuantEcon.tauchen — Function.Tauchen’s (1996) method for approximating AR(1) process with finite markov

chainThe process follows

y_t = + y_{t-1} + _t,

where t ˜ N (0, ˆ2)Arguments

• N::Integer: Number of points in markov process

• ::Real : Persistence parameter in AR(1) process

• ::Real : Standard deviation of random component of AR(1) process

• ::Real(0.0) : Mean of AR(1) process

• n std::Integer(3) : The number of standard deviations to each side theprocess

should spanReturns

• mc::MarkovChain{Float64} : Markov chain holding the state values and

transition matrix

2.85 QuantEcon.update!

QuantEcon.update! — Method.Updates cur x hat and cur sigma given array y of length k. The full update,

from one period to the nextArguments

• k::Kalman An instance of the Kalman filter

• y An array representing the current measurement

Page 101: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

96 CHAPTER 2. QUANTECON

2.86 QuantEcon.update values!

QuantEcon.update values! — Method.Update P and d from the value function representation in finite horizon caseArguments

• lq::LQ : instance of LQ type

Returns

• P::ScalarOrArray : n x n matrix in value function representation

V(x) = x’Px + d

• d::Real : Constant in value function representation

NotesThis function updates the P and d fields on the lq instance in addition to

returning them

2.87 QuantEcon.var quadratic sum

QuantEcon.var quadratic sum — Method.Computes the expected discounted quadratic sum

q(x_0) = E sum_{t=0}^{infty} beta^t x_t’ H x_t

Here {x t} is the VAR process x {t+1} = A x t + C w t with {w t} standardnormal and x 0 the initial condition.

Arguments

• A::Union{Float64, Matrix{Float64}} The n x n matrix described above(scalar)

if n = 1

• C::Union{Float64, Matrix{Float64}} The n x n matrix described above(scalar)

if n = 1

• H::Union{Float64, Matrix{Float64}} The n x n matrix described above(scalar)

if n = 1

• beta::Float64: Discount factor in (0, 1)

• x 0::Union{Float64, Vector{Float64}} The initial condtion. A con-formable

Page 102: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

2.87. QUANTECON.VAR QUADRATIC SUM 97

array (of length n) or a scalar if n=1Returns

• q0::Float64 : Represents the value q(x 0)

NotesThe formula for computing q(x 0) is q(x 0) = x 0’ Q x 0 + v where

• Q is the solution to Q = H + beta A’ Q A and

• v = race(C’ Q C) eta / (1 - eta)

Page 103: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 3

StatsBase

3.1 Base.stdm

Base.stdm — Method.

stdm(v, wv::WeightVec, m, [dim])

Return the standard deviation of a real-valued array v with a known meanm, optionally over a dimension dim. The weighting vector wv specifies frequencyweights (also called case weights) for the estimate.

3.2 Base.varm

Base.varm — Method.

varm(x, wv::WeightVec, m, [dim])

Return the variance of a real-valued array x with a known mean m, optionallyover a dimension dim. The weighting vector wv specifies frequency weights (alsocalled case weights) for the result.

This function differs from its counterpart in Base in that Bessel’s correction isnot used. That is, here the denominator for the variance is sum(wv), whereas it’slength(x)-1 in Base.varm. The impact is that this is not a weighted estimateof the population variance based on the sample; it’s the weighted variance ofthe sample.

3.3 StatsBase.L1dist

StatsBase.L1dist — Method.

L1dist(a, b)

Compute the L1 distance between two arrays: sumabs(a - b).

98

Page 104: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.4. STATSBASE.L2DIST 99

3.4 StatsBase.L2dist

StatsBase.L2dist — Method.

L2dist(a, b)

Compute the L2 distance between two arrays: sqrt(sumabs2(a - b)).

3.5 StatsBase.Linfdist

StatsBase.Linfdist — Method.

Linfdist(a, b)

Compute the L distance, also called the Chebyshev distance, between twoarrays: maxabs(a - b).

3.6 StatsBase.addcounts!

StatsBase.addcounts! — Method.

addcounts!(r, x, levels, [wv])

Add the number of occurrences in x of each value in levels to an existingarray r. If a weighting vector wv is specified, the sum of weights is used ratherthan the raw counts.

3.7 StatsBase.adjr2

StatsBase.adjr2 — Method.

adjr2(obj::StatisticalModel, variant::Symbol)

adjr(obj::StatisticalModel, variant::Symbol)

Adjusted coefficient of determination (adjusted R-squared).For linear models, the adjusted R is defined as 1 - (1 - (1-R)(n-1)/(n-p)),

with R the coefficient of determination, n the number of observations, and p thenumber of coefficients (including the intercept). This definition is generallyknown as the Wherry Formula I.

For other models, one of the several pseudo R definitions must be chosenvia variant. The only currently supported variant is :MacFadden, defined as1 - (log L - k)/log L0. In this formula, L is the likelihood of the model,L0 that of the null model (the model including only the intercept). These twoquantities are taken to be minus half deviance of the corresponding models.k is the number of consumed degrees of freedom of the model (as returned bydof).

Page 105: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

100 CHAPTER 3. STATSBASE

3.8 StatsBase.aic

StatsBase.aic — Method.

aic(obj::StatisticalModel)

Akaike’s Information Criterion, defined as -2 log L + 2k, with L the like-lihood of the model, and k its number of consumed degrees of freedom (asreturned by dof).

3.9 StatsBase.aicc

StatsBase.aicc — Method.

aicc(obj::StatisticalModel)

Corrected Akaike’s Information Criterion for small sample sizes (Hurvich andTsai 1989), defined as -2 log L + 2k + 2k(k-1)/(n-k-1), with L the likeli-hood of the model, k its number of consumed degrees of freedom (as returnedby dof), and n the number of observations (as returned by nobs).

3.10 StatsBase.autocor!

StatsBase.autocor! — Method.

autocor!(r, x, lags; demean=true)

Compute the autocorrelation function (ACF) of a vector or matrix x atlags and store the result in r. demean denotes whether the mean of x shouldbe subtracted from x before computing the ACF.

3.11 StatsBase.autocor

StatsBase.autocor — Method.

autocor(x, [lags]; demean=true)

Compute the autocorrelation function (ACF) of a vector or matrix x, op-tionally specifying the lags. demean denotes whether the mean of x should besubtracted from x before computing the ACF.

When left unspecified, the lags used are the integers from 0 to min(size(x,1)-1,10*log10(size(x,1))).

Page 106: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.12. STATSBASE.AUTOCOV! 101

3.12 StatsBase.autocov!

StatsBase.autocov! — Method.

autocov!(r, x, lags; demean=true)

Compute the autocovariance of a vector or matrix x at lags and store theresult in r. demean denotes whether the mean of x should be subtracted fromx before computing the autocovariance.

3.13 StatsBase.autocov

StatsBase.autocov — Method.

autocov(x, [lags]; demean=true)

Compute the autocovariance of a vector or matrix x, optionally specifyingthe lags at which to compute the autocovariance. demean denotes whether themean of x should be subtracted from x before computing the autocovariance.

When left unspecified, the lags used are the integers from 0 to min(size(x,1)-1,10*log10(size(x,1))).

3.14 StatsBase.bic

StatsBase.bic — Method.

bic(obj::StatisticalModel)

Bayesian Information Criterion, defined as -2 log L + k log n, with L

the likelihood of the model, k its number of consumed degrees of freedom (asreturned by dof), and n the number of observations (as returned by nobs).

3.15 StatsBase.competerank

StatsBase.competerank — Method.

competerank(x)

Return the standard competition ranking (“1224” ranking) of a real-valuedarray. Items that compare equal are given the same rank, then a gap is left inthe rankings the size of the number of tied items - 1.

Page 107: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

102 CHAPTER 3. STATSBASE

3.16 StatsBase.corkendall

StatsBase.corkendall — Method.

corkendall(x, y=x)

Compute Kendall’s rank correlation coefficient, . x and y must both be eithermatrices or vectors.

3.17 StatsBase.corspearman

StatsBase.corspearman — Method.

corspearman(x, y=x)

Compute Spearman’s rank correlation coefficient. If x and y are vectors,the output is a float, otherwise it’s a matrix corresponding to the pairwisecorrelations of the columns of x and y.

3.18 StatsBase.counteq

StatsBase.counteq — Method.

counteq(a, b)

Count the number of indices at which the elements of the arrays a and b areequal.

3.19 StatsBase.countmap

StatsBase.countmap — Method.

countmap(x)

Return a dictionary mapping each unique value in x to its number of occur-rences.

3.20 StatsBase.countne

StatsBase.countne — Method.

countne(a, b)

Count the number of indices at which the elements of the arrays a and b arenot equal.

Page 108: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.21. STATSBASE.COUNTS 103

3.21 StatsBase.counts

StatsBase.counts — Method.

counts(x, k::Integer, [wv::WeightVec])

Count the number of times integers in the range 1 to k occur in x.

3.22 StatsBase.counts

StatsBase.counts — Method.

counts(x, levels=span(x), [wv::WeightVec])

Count the number of times that values in the range levels occur in x.The output is a vector of length length(levels). If a weighting vector wv isspecified, the sum of the weights is used rather than the raw counts.

3.23 StatsBase.crosscor!

StatsBase.crosscor! — Method.

crosscor!(r, x, y, lags; demean=true)

Compute the cross correlation between real-valued vectors or matrices x

and y at lags and store the result in r. demean specifies whether the respectivemeans of x and y should be subtracted from them before computing their crosscorrelation.

3.24 StatsBase.crosscor

StatsBase.crosscor — Method.

crosscor(x, y, [lags]; demean=true)

Compute the cross correlation between real-valued vectors or matrices x

and y, optionally specifying the lags. demean specifies whether the respectivemeans of x and y should be subtracted from them before computing their crosscorrelation.

When left unspecified, the lags used are the integers from -min(size(x,1)-1,

10*log10(size(x,1))) to min(size(x,1), 10*log10(size(x,1))).

Page 109: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

104 CHAPTER 3. STATSBASE

3.25 StatsBase.crosscov!

StatsBase.crosscov! — Method.

crosscov!(r, x, y, lags; demean=true)

Compute the cross covariance function (CCF) between real-valued vectors ormatrices x and y at lags and store the result in r. demean specifies whether therespective means of x and y should be subtracted from them before computingtheir CCF.

3.26 StatsBase.crosscov

StatsBase.crosscov — Method.

crosscov(x, y, [lags]; demean=true)

Compute the cross covariance function (CCF) between real-valued vectors ormatrices x and y, optionally specifying the lags. demean specifies whether therespective means of x and y should be subtracted from them before computingtheir CCF.

When left unspecified, the lags used are the integers from -min(size(x,1)-1,

10*log10(size(x,1))) to min(size(x,1), 10*log10(size(x,1))).

3.27 StatsBase.crossentropy

StatsBase.crossentropy — Method.

crossentropy(p, q, [b])

Compute the cross entropy between p and q, optionally specifying a realnumber b such that the result is scaled by 1/log(b).

3.28 StatsBase.denserank

StatsBase.denserank — Method.

denserank(x)

Return the dense ranking (“1223” ranking) of a real-valued array. Itemsthat compare equal receive the same ranking, and the next subsequent rank isassigned with no gap.

Page 110: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.29. STATSBASE.DESCRIBE 105

3.29 StatsBase.describe

StatsBase.describe — Method.

describe(a)

Pretty-print the summary statistics provided by summarystats: the mean,minimum, 25th percentile, median, 75th percentile, and maximum.

3.30 StatsBase.deviance

StatsBase.deviance — Method.

deviance(obj::StatisticalModel)

Returns the deviance of the model relative to a reference, which is usuallywhen applicable the saturated model. It is equal, up to a constant, to -2 log

L, with L the likelihood of the model.

3.31 StatsBase.dof

StatsBase.dof — Method.

dof(obj::StatisticalModel)

Returns the number of degrees of freedom consumed in the model, includingwhen applicable the intercept and the distribution’s dispersion parameter.

3.32 StatsBase.ecdf

StatsBase.ecdf — Method.

ecdf(X)

Compute the empirical cumulative distribution function (ECDF) of a real-valued vector.

3.33 StatsBase.entropy

StatsBase.entropy — Method.

entropy(p, [b])

Compute the entropy of an array p, optionally specifying a real number b

such that the entropy is scaled by 1/log(b).

Page 111: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

106 CHAPTER 3. STATSBASE

3.34 StatsBase.findat

StatsBase.findat — Method.

findat(a, b)

For each element in b, find its first index in a. If the value does not occurin a, the corresponding index is 0.

3.35 StatsBase.genmean

StatsBase.genmean — Method.

genmean(a, p)

Return the generalized/power mean with exponent p of a real-valued array,i.e. left(

rac1n sumni=1a

pi ight)

rac1p, where n = length(a). It is taken to be the geometric mean when p

== 0.

3.36 StatsBase.geomean

StatsBase.geomean — Method.

geomean(a)

Return the geometric mean of a real-valued array.

3.37 StatsBase.gkldiv

StatsBase.gkldiv — Method.

gkldiv(a, b)

Compute the generalized Kullback-Leibler divergence between two arrays:sum(a*log(a/b)-a+b).

3.38 StatsBase.harmmean

StatsBase.harmmean — Method.

harmmean(a)

Return the harmonic mean of a real-valued array.

Page 112: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.39. STATSBASE.INDEXMAP 107

3.39 StatsBase.indexmap

StatsBase.indexmap — Method.

indexmap(a)

Construct a dictionary that maps each unique value in a to the index of itsfirst occurrence in a.

3.40 StatsBase.indicatormat

StatsBase.indicatormat — Method.

indicatormat(x, c=sort(unique(x)); sparse=false)

Construct a boolean matrix I of size (length(c), length(x)). Let ci bethe index of x[i] in c. Then I[ci, i] = true and all other elements arefalse.

3.41 StatsBase.indicatormat

StatsBase.indicatormat — Method.

indicatormat(x, k::Integer; sparse=false)

Construct a boolean matrix I of size (k, length(x)) such that I[x[i], i]

= true and all other elements are set to false. If sparse is true, the outputwill be a sparse matrix, otherwise it will be dense (default).

3.42 StatsBase.inverse rle

StatsBase.inverse rle — Method.

inverse_rle(vals, lens)

Reconstruct a vector from its run-length encoding. vals is a vector of thevalues and lens is a vector of the corresponding run lengths.

3.43 StatsBase.iqr

StatsBase.iqr — Method.

iqr(v)

Compute the interquartile range (IQR) of an array, i.e. the 75th percentileminus the 25th percentile.

Page 113: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

108 CHAPTER 3. STATSBASE

3.44 StatsBase.kldivergence

StatsBase.kldivergence — Method.

kldivergence(p, q, [b])

Compute the Kullback-Leibler divergence of q from p, optionally specifyinga real number b such that the divergence is scaled by 1/log(b).

3.45 StatsBase.kurtosis

StatsBase.kurtosis — Method.

kurtosis(v, [wv::WeightVec], m=mean(v))

Compute the excess kurtosis of a real-valued array v, optionally specifyinga weighting vector wv and a center m.

3.46 StatsBase.levelsmap

StatsBase.levelsmap — Method.

levelsmap(a)

Construct a dictionary that maps each of the n unique values in a to anumber between 1 and n.

3.47 StatsBase.mad

StatsBase.mad — Method.

mad(v)

Compute the median absolute deviation of v.

3.48 StatsBase.maxad

StatsBase.maxad — Method.

maxad(a, b)

Return the maximum absolute deviation between two arrays: maxabs(a -

b).

Page 114: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.49. STATSBASE.MEAN AND COV 109

3.49 StatsBase.mean and cov

StatsBase.mean and cov — Function.

mean_and_cov(x, [wv::WeightVec]; vardim=1) -> (mean, cov)

Return the mean and covariance matrix as a tuple. A weighting vector wv

can be specified. vardim that designates whether the variables are columns inthe matrix (1) or rows (2).

3.50 StatsBase.mean and std

StatsBase.mean and std — Method.

mean_and_std(x, [wv::WeightVec], [dim]) -> (mean, std)

Return the mean and standard deviation of a real-valued array x, optionallyover a dimension dim, as a tuple. A weighting vector wv can be specified toweight the estimates. The weights are assumed to be frequency weights, alsocalled case weights.

3.51 StatsBase.mean and var

StatsBase.mean and var — Method.

mean_and_var(x, [wv::WeightVec], [dim]) -> (mean, var)

Return the mean and variance of a real-valued array x, optionally over adimension dim, as a tuple. A weighting vector wv can be specified to weight theestimates. The weights are assumed to be frequency weights, also called caseweights.

3.52 StatsBase.meanad

StatsBase.meanad — Method.

meanad(a, b)

Return the mean absolute deviation between two arrays: mean(abs(a -

b)).

3.53 StatsBase.mode

StatsBase.mode — Method.

mode(a, [r])

Return the first mode (most common number) of an array, optionally overa specified range r.

Page 115: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

110 CHAPTER 3. STATSBASE

3.54 StatsBase.modes

StatsBase.modes — Method.

modes(a, [r])::Vector

Return all modes (most common numbers) of an array, optionally over aspecified range r.

3.55 StatsBase.moment

StatsBase.moment — Method.

moment(v, k, [wv::WeightVec], m=mean(v))

Return the kth order central moment of a real-valued array v, optionallyspecifying a weighting vector wv and a center m.

3.56 StatsBase.msd

StatsBase.msd — Method.

msd(a, b)

Return the mean squared deviation between two arrays: mean(abs2(a -

b)).

3.57 StatsBase.nobs

StatsBase.nobs — Method.

nobs(obj::StatisticalModel)

Returns the number of independent observations on which the model wasfitted. Be careful when using this information, as the definition of an indepen-dent observation may vary depending on the model, on the format used to passthe data, on the sampling plan (if specified), etc.

3.58 StatsBase.nquantile

StatsBase.nquantile — Method.

nquantile(v, n)

Return the n-quantiles of a real-valued array, i.e. the values which partitionv into n subsets of nearly equal size.

Page 116: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.59. STATSBASE.NULLDEVIANCE 111

3.59 StatsBase.nulldeviance

StatsBase.nulldeviance — Method.

nulldeviance(obj::StatisticalModel)

Returns the deviance of the null model, that is the one including only theintercept.

3.60 StatsBase.ordinalrank

StatsBase.ordinalrank — Method.

ordinalrank(x)

Return the ordinal ranking (“1234” ranking) of a real-valued array. All itemsin x are given distinct, successive ranks based on their position in sort(x).

3.61 StatsBase.pacf!

StatsBase.pacf! — Method.

pacf!(r, X, lags; method=:regression)

Compute the partial autocorrelation function (PACF) of a matrix X at lagsand store the result in r. method designates the estimation method. Rec-ognized values are :regression, which computes the partial autocorrelationsvia successive regression models, and :yulewalker, which computes the partialautocorrelations using the Yule-Walker equations.

3.62 StatsBase.pacf

StatsBase.pacf — Method.

pacf(X, lags; method=:regression)

Compute the partial autocorrelation function (PACF) of a real-valued vectoror matrix X at lags. method designates the estimation method. Recognized val-ues are :regression, which computes the partial autocorrelations via successiveregression models, and :yulewalker, which computes the partial autocorrela-tions using the Yule-Walker equations.

3.63 StatsBase.percentile

StatsBase.percentile — Method.

percentile(v, p)

Return the pth percentile of a real-valued array v.

Page 117: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

112 CHAPTER 3. STATSBASE

3.64 StatsBase.predict

StatsBase.predict — Method.

predict(obj::RegressionModel, [newX])

Form the predicted response of model obj. An object with new covariatevalues newX can be supplied, which should have the same type and structure asthat used to fit obj; e.g. for a GLM it would generally be a DataFrame with thesame variable names as the original predictors.

3.65 StatsBase.proportionmap

StatsBase.proportionmap — Method.

proportionmap(x)

Return a dictionary mapping each unique value in x to its proportion in x.

3.66 StatsBase.proportions

StatsBase.proportions — Method.

proportions(x, k::Integer, [wv::WeightVec])

Return the proportion of integers in 1 to k that occur in x.

3.67 StatsBase.proportions

StatsBase.proportions — Method.

proportions(x, levels=span(x), [wv::WeightVec])

Return the proportion of values in the range levels that occur in x. Equiva-lent to counts(x, levels) / length(x). If a weighting vector wv is specified,the sum of the weights is used rather than the raw counts.

3.68 StatsBase.psnr

StatsBase.psnr — Method.

psnr(a, b, maxv)

Compute the peak signal-to-noise ratio between two arrays a and b. maxv isthe maximum possible value either array can take. The PSNR is computed as10 * log10(maxv^2 / msd(a, b)).

Page 118: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.69. STATSBASE.R2 113

3.69 StatsBase.r2

StatsBase.r2 — Method.

r2(obj::StatisticalModel, variant::Symbol)

r(obj::StatisticalModel, variant::Symbol)

Coefficient of determination (R-squared).For a linear model, the R is defined as ESS/TSS, with ESS the explained sum

of squares and TSS the total sum of squares, and variant can be omitted.For other models, one of several pseudo R definitions must be chosen via

variant. Supported variants are:

• :MacFadden (a.k.a. likelihood ratio index), defined as 1 - log L/log L0.

• :CoxSnell, defined as 1 - (L0/L)^(2/n)

• :Nagelkerke, defined as (1 - (L0/L)^(2/n))/(1 - L0^(2/n)), with n

the number

of observations (as returned by nobs).In the above formulas, L is the likelihood of the model, L0 that of the null

model (the model including only the intercept). These two quantities are takento be minus half deviance of the corresponding models.

3.70 StatsBase.renyientropy

StatsBase.renyientropy — Method.

renyientropy(p, )

Compute the Rnyi (generalized) entropy of order of an array p.

3.71 StatsBase.rle

StatsBase.rle — Method.

rle(v) -> (vals, lens)

Return the run-length encoding of a vector as a tuple. The first elementof the tuple is a vector of values of the input and the second is the number ofconsecutive occurrences of each element.

3.72 StatsBase.rmsd

StatsBase.rmsd — Method.

rmsd(a, b; normalize=false)

Return the root mean squared deviation between two optionally normalizedarrays. The root mean squared deviation is computed as sqrt(msd(a, b)).

Page 119: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

114 CHAPTER 3. STATSBASE

3.73 StatsBase.sample!

StatsBase.sample! — Method.

sample!(a, [wv::WeightVec], x; replace=true, ordered=false)

Draw a random sample of length(x) elements from an array a and store theresult in x. A polyalgorithm is used for sampling. Sampling probabilities areproportional to the weights given in wv, if provided. replace dictates whethersampling is performed with replacement and order dictates whether an orderedsample, also called a sequential sample, should be taken.

3.74 StatsBase.sample

StatsBase.sample — Method.

sample(a, [wv::WeightVec], n::Integer; replace=true, ordered=false)

Select a random, optionally weighted sample of size n from an array a usinga polyalgorithm. Sampling probabilities are proportional to the weights given inwv, if provided. replace dictates whether sampling is performed with replace-ment and order dictates whether an ordered sample, also called a sequentialsample, should be taken.

3.75 StatsBase.sample

StatsBase.sample — Method.

sample(a, [wv::WeightVec], dims::Dims; replace=true, ordered=false)

Select a random, optionally weighted sample from an array a specifying thedimensions dims of the output array. Sampling probabilities are proportionalto the weights given in wv, if provided. replace dictates whether sampling isperformed with replacement and order dictates whether an ordered sample,also called a sequential sample, should be taken.

3.76 StatsBase.sample

StatsBase.sample — Method.

sample(a, [wv::WeightVec])

Select a single random element of a. Sampling probabilities are proportionalto the weights given in wv, if provided.

Page 120: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.77. STATSBASE.SAMPLE 115

3.77 StatsBase.sample

StatsBase.sample — Method.

sample(wv::WeightVec)

Select a single random integer in 1:length(wv) with probabilities propor-tional to the weights given in wv.

3.78 StatsBase.samplepair

StatsBase.samplepair — Method.

samplepair(a)

Draw a pair of distinct elements from the array a without replacement.

3.79 StatsBase.samplepair

StatsBase.samplepair — Method.

samplepair(n)

Draw a pair of distinct integers between 1 and n without replacement.

3.80 StatsBase.scattermat

StatsBase.scattermat — Function.

scattermat(X, [wv::WeightVec]; mean=nothing, vardim=1)

Compute the scatter matrix, which is an unnormalized covariance matrix.A weighting vector wv can be specified to weight the estimate.

Arguments

• mean=nothing: a known mean value. nothing indicates that the mean is

unknown, and the function will compute the mean. Specifying mean=0 in-dicates that the data are centered and hence there’s no need to subtract themean.

• vardim=1: the dimension along which the variables are organized.

When vardim = 1, the variables are considered columns with observationsin rows; when vardim = 2, variables are in rows with observations in columns.

Page 121: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

116 CHAPTER 3. STATSBASE

3.81 StatsBase.sem

StatsBase.sem — Method.

sem(a)

Return the standard error of the mean of a, i.e. sqrt(var(a) / length(a)).

3.82 StatsBase.skewness

StatsBase.skewness — Method.

skewness(v, [wv::WeightVec], m=mean(v))

Compute the standardized skewness of a real-valued array v, optionally spec-ifying a weighting vector wv and a center m.

3.83 StatsBase.span

StatsBase.span — Method.

span(x)

Return the span of an integer array, i.e. the range minimum(x):maximum(x).

3.84 StatsBase.sqL2dist

StatsBase.sqL2dist — Method.

sqL2dist(a, b)

Compute the squared L2 distance between two arrays: sumabs2(a - b).

3.85 StatsBase.summarystats

StatsBase.summarystats — Method.

summarystats(a)

Compute summary statistics for a real-valued array a. Returns a SummaryStatsobject containing the mean, minimum, 25th percentile, median, 75th percentile,and maxmimum.

Page 122: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.86. STATSBASE.TIEDRANK 117

3.86 StatsBase.tiedrank

StatsBase.tiedrank — Method.

tiedrank(x)

Return the tied ranking, also called fractional or “1 2.5 2.5 4” ranking, of areal-valued array. Items that compare equal receive the mean of the rankingsthey would have been assigned under ordinal ranking.

3.87 StatsBase.trimmean

StatsBase.trimmean — Method.

trimmean(x, p)

Compute the trimmed mean of x, i.e. the mean after removing a proportionp of its highest- and lowest-valued elements.

3.88 StatsBase.variation

StatsBase.variation — Method.

variation(x, m=mean(x))

Return the coefficient of variation of an array x, optionally specifying aprecomputed mean m. The coefficient of variation is the ratio of the standarddeviation to the mean.

3.89 StatsBase.weights

StatsBase.weights — Method.

weights(vs)

Construct a WeightVec from a given array.

3.90 StatsBase.wmean

StatsBase.wmean — Method.

wmean(v, w::AbstractVector)

Compute the weighted mean of an array v with weights w.

Page 123: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

118 CHAPTER 3. STATSBASE

3.91 StatsBase.wmedian

StatsBase.wmedian — Method.

wmedian(v, w)

Compute the weighted median of an array v with weights w, given as eithera vector or WeightVec.

3.92 StatsBase.wquantile

StatsBase.wquantile — Method.

wquantile(v, w, p)

Compute the pth quantile(s) of v with weights w, given as either a vector ora WeightVec.

3.93 StatsBase.wsample!

StatsBase.wsample! — Method.

wsample!(a, w, x; replace=true, ordered=false)

Select a weighted sample from an array a and store the result in x. Sam-pling probabilities are proportional to the weights given in w. replace dictateswhether sampling is performed with replacement and order dictates whetheran ordered sample, also called a sequential sample, should be taken.

3.94 StatsBase.wsample

StatsBase.wsample — Method.

wsample([a], w, n::Integer; replace=true, ordered=false)

Select a weighted random sample of size n from a with probabilities pro-portional to the weights given in w if a is present, otherwise select a randomsample of size n of the weights given in w. replace dictates whether samplingis performed with replacement and order dictates whether an ordered sample,also called a sequential sample, should be taken.

Page 124: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

3.95. STATSBASE.WSAMPLE 119

3.95 StatsBase.wsample

StatsBase.wsample — Method.

wsample([a], w, dims::Dims; replace=true, ordered=false)

Select a weighted random sample from a with probabilities proportional tothe weights given in w if a is present, otherwise select a random sample of sizen of the weights given in w. The dimensions of the output are given by dims.

3.96 StatsBase.wsample

StatsBase.wsample — Method.

wsample([a], w)

Select a weighted random sample of size 1 from a with probabilities propor-tional to the weights given in w. If a is not present, select a random weight fromw.

3.97 StatsBase.wsum!

StatsBase.wsum! — Method.

wsum!(R, A, w, dim; init=true)

Compute the weighted sum of A with weights w over the dimension dim andstore the result in R. If init=false, the sum is added to R rather than startingfrom zero.

3.98 StatsBase.wsum

StatsBase.wsum — Method.

wsum(v, w::AbstractVector, [dim])

Compute the weighted sum of an array v with weights w, optionally over thedimension dim.

3.99 StatsBase.zscore!

StatsBase.zscore! — Method.

zscore!([Z], X, , )

Compute the z-scores of an array X with mean and standard deviation .z-scores are the signed number of standard deviations above the mean that anobservation lies. If a destination array Z is provided, the scores are stored in Z,otherwise X is overwritten.

Page 125: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

120 CHAPTER 3. STATSBASE

3.100 StatsBase.zscore

StatsBase.zscore — Method.

zscore(X, [, ])

Compute the z-scores of X, optionally specifying a precomputed mean andstandard deviation . z-scores are the signed number of standard deviations abovethe mean that an observation lies. The mean and standard deviation can bereal numbers or arrays of real numbers.

Page 126: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 4

Distributions

4.1 Distributions.Arcsine

Distributions.Arcsine — Type.

Arcsine(a,b)

The Arcsine distribution has probability density function

f(x) =1

π√

(x− a)(b− x), x ∈ [a, b]

[] Arcsine() Arcsine distribution with support [0, 1] Arcsine(b) Arcsinedistribution with support [0, b] Arcsine(a, b) Arcsine distribution with support[a, b]

params(d) Get the parameters, i.e. (a, b) minimum(d) Get the lowerbound, i.e. a maximum(d) Get the upper bound, i.e. b location(d) Get theleft bound, i.e. a scale(d) Get the span of the support, i.e. b - a

External links

• Arcsine distribution on Wikipedia

4.2 Distributions.Bernoulli

Distributions.Bernoulli — Type.

Bernoulli(p)

A Bernoulli distribution is parameterized by a success rate p, which takesvalue 1 with probability p and 0 with probability 1-p.

P (X = k) =

{1− p for k = 0,

p for k = 1.

121

Page 127: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

122 CHAPTER 4. DISTRIBUTIONS

[] Bernoulli() Bernoulli distribution with p = 0.5 Bernoulli(p) Bernoullidistribution with success rate p

params(d) Get the parameters, i.e. (p,) succprob(d) Get the success rate,i.e. p failprob(d) Get the failure rate, i.e. 1 - p

External links:

• Bernoulli distribution on Wikipedia

4.3 Distributions.Beta

Distributions.Beta — Type.

Beta(,)

The Beta distribution has probability density function

f(x;α, β) =1

B(α, β)xα−1(1− x)β−1, x ∈ [0, 1]

The Beta distribution is related to the Gamma distribution via the propertythat if X ∼ Gamma(α) and Y ∼ Gamma(β) independently, then X/(X +Y ) ∼Beta(α, β).

[] Beta() equivalent to Beta(1, 1) Beta(a) equivalent to Beta(a, a) Beta(a,b) Beta distribution with shape parameters a and b

params(d) Get the parameters, i.e. (a, b)External links

• Beta distribution on Wikipedia

4.4 Distributions.BetaBinomial

Distributions.BetaBinomial — Type.

BetaBinomial(n,,)

A Beta-binomial distribution is the compound distribution of the Binomial

distribution where the probability of success p is distributed according to theBeta. It has three parameters: n, the number of trials and two shape parameters,

P (X = k) =

(n

k

)B(k + α, n− k + β)/B(α, β), for k = 0, 1, 2, . . . , n.

[] BetaBinomial(n, a, b) BetaBinomial distribution with n trials and shapeparameters a, b

params(d) Get the parameters, i.e. (n, a, b) ntrials(d) Get the number oftrials, i.e. n

External links:

• Beta-binomial distribution on Wikipedia

Page 128: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4.5. DISTRIBUTIONS.BETAPRIME 123

4.5 Distributions.BetaPrime

Distributions.BetaPrime — Type.

BetaPrime(,)

The Beta prime distribution has probability density function

f(x;α, β) =1

B(α, β)xα−1(1 + x)−(α+β), x > 0

The Beta prime distribution is related to the Beta distribution via the rela-tion ship that if X ∼ Beta(α, β) then X

1−X ∼ BetaPrime(α, β)

[] BetaPrime() equivalent to BetaPrime(1, 1) BetaPrime(a) equivalent toBetaPrime(a, a) BetaPrime(a, b) Beta prime distribution with shape parame-ters a and b

params(d) Get the parameters, i.e. (a, b)

External links

• Beta prime distribution on Wikipedia

4.6 Distributions.Binomial

Distributions.Binomial — Type.

Binomial(n,p)

A Binomial distribution characterizes the number of successes in a sequenceof independent trials. It has two parameters: n, the number of trials, and p, theprobability of success in an individual trial, with the distribution:

P (X = k) =

(n

k

)pk(1− p)n−k, for k = 0, 1, 2, . . . , n.

[] Binomial() Binomial distribution with n = 1 and p = 0.5 Binomial(n)Binomial distribution for n trials with success rate p = 0.5 Binomial(n, p)Binomial distribution for n trials with success rate p

params(d) Get the parameters, i.e. (n, p) ntrials(d) Get the number oftrials, i.e. n succprob(d) Get the success rate, i.e. p failprob(d) Get the failurerate, i.e. 1 - p

External links:

• Binomial distribution on Wikipedia

Page 129: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

124 CHAPTER 4. DISTRIBUTIONS

4.7 Distributions.Categorical

Distributions.Categorical — Type.

Categorical(p)

A Categorical distribution is parameterized by a probability vector p (oflength K). P (X = k) = p[k] for k = 1, 2, . . . ,K.

[] Categorical(p) Categorical distribution with probability vector p params(d)Get the parameters, i.e. (p,) probs(d) Get the probability vector, i.e. p ncate-gories(d) Get the number of categories, i.e. K

Here, p must be a real vector, of which all components are nonnegativeand sum to one. Note: The input vector p is directly used as a field of theconstructed distribution, without being copied. External links:

• Categorical distribution on Wikipedia

4.8 Distributions.Cauchy

Distributions.Cauchy — Type.

Cauchy(, )

The Cauchy distribution with location and scale has probability densityfunction

f(x;µ, σ) =1

πσ(

1 +(x−µσ

)2)[] Cauchy() Standard Cauchy distribution, i.e. Cauchy(0, 1) Cauchy(u)

Cauchy distribution with location u and unit scale, i.e. Cauchy(u, 1) Cauchy(u,b) Cauchy distribution with location u and scale b

params(d) Get the parameters, i.e. (u, b) location(d) Get the locationparameter, i.e. u scale(d) Get the scale parameter, i.e. b

External links

• Cauchy distribution on Wikipedia

4.9 Distributions.Chi

Distributions.Chi — Type.

Chi()

Page 130: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4.10. DISTRIBUTIONS.CHISQ 125

The Chi distribution degrees of freedom has probability density function

f(x; k) =1

Γ(k/2)21−k/2xk−1e−x

2/2, x > 0

It is the distribution of the square-root of a Chisq variate.[] Chi(k) Chi distribution with k degrees of freedomparams(d) Get the parameters, i.e. (k,) dof(d) Get the degrees of freedom,

i.e. kExternal links

• Chi distribution on Wikipedia

4.10 Distributions.Chisq

Distributions.Chisq — Type.

Chisq()

The Chi squared distribution (typically written ) with degrees of freedomhas the probability density function

f(x; k) =xk/2−1e−x/2

2k/2Γ(k/2), x > 0.

If is an integer, then it is the distribution of the sum of squares of inde-pendent standard Normal variates.

[] Chisq(k) Chi-squared distribution with k degrees of freedomparams(d) Get the parameters, i.e. (k,) dof(d) Get the degrees of freedom,

i.e. kExternal links

• Chi-squared distribution on Wikipedia

4.11 Distributions.DiscreteUniform

Distributions.DiscreteUniform — Type.

DiscreteUniform(a,b)

A Discrete uniform distribution is a uniform distribution over a consecutivesequence of integers between a and b, inclusive.

P (X = k) = 1/(b− a+ 1) for k = a, a+ 1, . . . , b.

[] DiscreteUniform(a, b) a uniform distribution over {a, a+1, ..., b}params(d) Get the parameters, i.e. (a, b) span(d) Get the span of the

support, i.e. (b - a + 1) probval(d) Get the probability value, i.e. 1 / (b - a +1) minimum(d) Return a maximum(d) Return b

External links

Page 131: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

126 CHAPTER 4. DISTRIBUTIONS

• Discrete uniform distribution on Wikipedia

4.12 Distributions.Erlang

Distributions.Erlang — Type.

Erlang(,)

The Erlang distribution is a special case of a Gamma distribution with integershape parameter.

[] Erlang() Erlang distribution with unit shape and unit scale, i.e. Erlang(1,1) Erlang(a) Erlang distribution with shape parameter a and unit scale, i.e.Erlang(a, 1) Erlang(a, s) Erlang distribution with shape parameter a and scaleb

External links

• Erlang distribution on Wikipedia

4.13 Distributions.Exponential

Distributions.Exponential — Type.

Exponential()

The Exponential distribution with scale parameter has probability densityfunction

f(x; θ) =1

θe−

xθ , x > 0

[] Exponential() Exponential distribution with unit scale, i.e. Exponen-tial(1) Exponential(b) Exponential distribution with scale b

params(d) Get the parameters, i.e. (b,) scale(d) Get the scale parameter,i.e. b rate(d) Get the rate parameter, i.e. 1 / b

External links

• Exponential distribution on Wikipedia

4.14 Distributions.FDist

Distributions.FDist — Type.

FDist(1,2)

Page 132: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4.15. DISTRIBUTIONS.FRECHET 127

The F distribution has probability density function

f(x; ν1, ν2) =1

xB(ν1/2, ν2/2)

√(ν1x)ν1 · νν22

(ν1x+ ν2)ν1+ν2, x > 0

It is related to the Chisq distribution via the property that if X1 ∼ Chisq(ν1)and X2 ∼ Chisq(ν2), then $(X 1/ν 1)/(X 2/ν 2) ∼ FDist(ν 1, ν 2)‘.

[] FDist(d1, d2) F-Distribution with parameters d1 and d2params(d) Get the parameters, i.e. (d1, d2)External links

• F distribution on Wikipedia

4.15 Distributions.Frechet

Distributions.Frechet — Type.

Frechet(,)

The Frchet distribution with shape and scale has probability density func-tion

f(x;α, θ) =α

θ

(xθ

)−α−1e−(x/θ)

−α, x > 0

[] Frechet() Frchet distribution with unit shape and unit scale, i.e. Frechet(1,1) Frechet(a) Frchet distribution with shape a and unit scale, i.e. Frechet(a, 1)Frechet(a, b) Frchet distribution with shape a and scale b

params(d) Get the parameters, i.e. (a, b) shape(d) Get the shape param-eter, i.e. a scale(d) Get the scale parameter, i.e. b

External links

• Frchet distribution on Wikipedia

4.16 Distributions.Gamma

Distributions.Gamma — Type.

Gamma(,)

The Gamma distribution with shape parameter and scale has probabilitydensity function

f(x;α, β) =xα−1e−x/β

Γ(α)βα, x > 0

[] Gamma() Gamma distribution with unit shape and unit scale, i.e. Gamma(1,1) Gamma(a) Gamma distribution with shape a and unit scale, i.e. Gamma(a,1) Gamma(a, b) Gamma distribution with shape a and scale b

Page 133: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

128 CHAPTER 4. DISTRIBUTIONS

params(d) Get the parameters, i.e. (a, b) shape(d) Get the shape param-eter, i.e. a scale(d) Get the scale parameter, i.e. b

External links

• Gamma distribution on Wikipedia

4.17 Distributions.GeneralizedExtremeValue

Distributions.GeneralizedExtremeValue — Type.

GeneralizedExtremeValue(, , )

The Generalized extreme value distribution with shape parameter , scale andlocation has probability density function

f(x; ξ, σ, µ) =

{1σ

[1 +

(x−µσ

)ξ]−1/ξ−1

exp{−[1 +

(x−µσ

)ξ]−1/ξ}

for ξ 6= 0

1σ exp

{−x−µσ

}exp

{− exp

[−x−µσ

]}for ξ = 0

for

x ∈

[µ− σ

ξ ,+∞)

for ξ > 0

(−∞,+∞) for ξ = 0(−∞, µ− σ

ξ

]for ξ < 0

[] GeneralizedExtremeValue(m, s, k) Generalized Pareto distribution withshape k, scale s and location m.

params(d) Get the parameters, i.e. (m, s, k) location(d) Get the locationparameter, i.e. m scale(d) Get the scale parameter, i.e. s shape(d) Get theshape parameter, i.e. k (sometimes called c)

External links

• Generalized extreme value distribution on Wikipedia

4.18 Distributions.GeneralizedPareto

Distributions.GeneralizedPareto — Type.

GeneralizedPareto(, , )

The Generalized Pareto distribution with shape parameter , scale and loca-tion has probability density function

f(x;µ, σ, ξ) =

{1σ (1 + ξ x−µσ )−

1ξ−1 for ξ 6= 0

1σ e− (x−µ)

σ for ξ = 0, x ∈

{[µ,∞] for ξ ≥ 0

[µ, µ− σ/ξ] for ξ < 0

Page 134: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4.19. DISTRIBUTIONS.GEOMETRIC 129

[] GeneralizedPareto() Generalized Pareto distribution with unit shape andunit scale, i.e. GeneralizedPareto(0, 1, 1) GeneralizedPareto(k, s) GeneralizedPareto distribution with shape k and scale s, i.e. GeneralizedPareto(0, k, s)GeneralizedPareto(m, k, s) Generalized Pareto distribution with shape k, scales and location m.

params(d) Get the parameters, i.e. (m, s, k) location(d) Get the locationparameter, i.e. m scale(d) Get the scale parameter, i.e. s shape(d) Get theshape parameter, i.e. k

External links

• Generalized Pareto distribution on Wikipedia

4.19 Distributions.Geometric

Distributions.Geometric — Type.

Geometric(p)

A Geometric distribution characterizes the number of failures before the firstsuccess in a sequence of independent Bernoulli trials with success rate p.

P (X = k) = p(1− p)k, for k = 0, 1, 2, . . . .

[] Geometric() Geometric distribution with success rate 0.5 Geometric(p)Geometric distribution with success rate p

params(d) Get the parameters, i.e. (p,) succprob(d) Get the success rate,i.e. p failprob(d) Get the failure rate, i.e. 1 - p

External links

• Geometric distribution on Wikipedia

4.20 Distributions.Gumbel

Distributions.Gumbel — Type.

Gumbel(, )

The Gumbel distribution with location and scale has probability densityfunction

f(x;µ, θ) =1

θe−(z+e

z), with z =x− µθ

[] Gumbel() Gumbel distribution with zero location and unit scale, i.e.Gumbel(0, 1) Gumbel(u) Gumbel distribution with location u and unit scale,i.e. Gumbel(u, 1) Gumbel(u, b) Gumbel distribution with location u and scaleb

Page 135: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

130 CHAPTER 4. DISTRIBUTIONS

params(d) Get the parameters, i.e. (u, b) location(d) Get the locationparameter, i.e. u scale(d) Get the scale parameter, i.e. b

External links

• Gumbel distribution on Wikipedia

4.21 Distributions.Hypergeometric

Distributions.Hypergeometric — Type.

Hypergeometric(s, f, n)

A Hypergeometric distribution describes the number of successes in n drawswithout replacement from a finite population containing s successes and f fail-ures.

P (X = k) =

(sk

)(f

n−k)(

s+fn

) , for k = max(0, n− f), . . . ,min(n, s).

[] Hypergeometric(s, f, n) Hypergeometric distribution for a population withs successes and f failures, and a sequence of n trials.

params(d) Get the parameters, i.e. (s, f, n)External links

• Hypergeometric distribution on Wikipedia

4.22 Distributions.InverseGamma

Distributions.InverseGamma — Type.

InverseGamma(, )

The inverse gamma distribution with shape parameter and scale has prob-ability density function

f(x;α, θ) =θαx−(α+1)

Γ(α)e−

θx , x > 0

It is related to the Gamma distribution: if X ∼ Gamma(α, β), then 1/X ∼InverseGamma(α, β−1).

.. code-block:: julia

InverseGamma() # Inverse Gamma distribution with unit shape and unit scale, i.e. InverseGamma(1, 1)

InverseGamma(a) # Inverse Gamma distribution with shape a and unit scale, i.e. InverseGamma(a, 1)

InverseGamma(a, b) # Inverse Gamma distribution with shape a and scale b

params(d) # Get the parameters, i.e. (a, b)

shape(d) # Get the shape parameter, i.e. a

scale(d) # Get the scale parameter, i.e. b

Page 136: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4.23. DISTRIBUTIONS.INVERSEGAUSSIAN 131

External links

• Inverse gamma distribution on Wikipedia

4.23 Distributions.InverseGaussian

Distributions.InverseGaussian — Type.

InverseGaussian(,)

The inverse Gaussian distribution with mean and shape has probabilitydensity function

f(x;µ, λ) =

√λ

2πx3exp

(−λ(x− µ)2

2µ2x

), x > 0

[] InverseGaussian() Inverse Gaussian distribution with unit mean and unitshape, i.e. InverseGaussian(1, 1) InverseGaussian(mu), Inverse Gaussian distri-bution with mean mu and unit shape, i.e. InverseGaussian(u, 1) InverseGaus-sian(mu, lambda) Inverse Gaussian distribution with mean mu and shapelambda

params(d) Get the parameters, i.e. (mu, lambda) mean(d) Get the meanparameter, i.e. mu shape(d) Get the shape parameter, i.e. lambda

External links

• Inverse Gaussian distribution on Wikipedia

4.24 Distributions.Laplace

Distributions.Laplace — Type.

Laplace(,)

The Laplace distribution with location and scale has probability densityfunction

f(x;µ, β) =1

2βexp

(−|x− µ|

β

)[] Laplace() Laplace distribution with zero location and unit scale, i.e.

Laplace(0, 1) Laplace(u) Laplace distribution with location u and unit scale,i.e. Laplace(u, 1) Laplace(u, b) Laplace distribution with location u ans scaleb

params(d) Get the parameters, i.e. (u, b) location(d) Get the locationparameter, i.e. u scale(d) Get the scale parameter, i.e. b

External links

• Laplace distribution on Wikipedia

Page 137: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

132 CHAPTER 4. DISTRIBUTIONS

4.25 Distributions.Levy

Distributions.Levy — Type.

Levy(, )

The Lvy distribution with location and scale has probability density func-tion

f(x;µ, σ) =

√σ

2π(x− µ)3exp

(− σ

2(x− µ)

), x > µ

[] Levy() Levy distribution with zero location and unit scale, i.e. Levy(0,1) Levy(u) Levy distribution with location u and unit scale, i.e. Levy(u, 1)Levy(u, c) Levy distribution with location u ans scale c

params(d) Get the parameters, i.e. (u, c) location(d) Get the locationparameter, i.e. u

External links

• Lvy distribution on Wikipedia

4.26 Distributions.LogNormal

Distributions.LogNormal — Type.

LogNormal(,)

The log normal distribution is the distribution of the exponential of a Normal

variate: if X ∼ Normal(µ, σ) then exp(X) ∼ LogNormal(µ, σ). The probabilitydensity function is

f(x;µ, σ) =1

x√

2πσ2exp

(− (log(x)− µ)2

2σ2

), x > 0

[] LogNormal() Log-normal distribution with zero log-mean and unit scaleLogNormal(mu) Log-normal distribution with log-mean mu and unit scale Log-Normal(mu, sig) Log-normal distribution with log-mean mu and scale sig

params(d) Get the parameters, i.e. (mu, sig) meanlogx(d) Get the mean oflog(X), i.e. mu varlogx(d) Get the variance of log(X), i.e. sig2stdlogx(d)Getthestandarddeviationoflog(X), i.e.sig

External links

• Log normal distribution on Wikipedia

Page 138: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4.27. DISTRIBUTIONS.LOGISTIC 133

4.27 Distributions.Logistic

Distributions.Logistic — Type.

Logistic(,)

The Logistic distribution with location and scale has probability densityfunction

f(x;µ, θ) =1

4θsech2

(x− µ

)[] Logistic() Logistic distribution with zero location and unit scale, i.e.

Logistic(0, 1) Logistic(u) Logistic distribution with location u and unit scale,i.e. Logistic(u, 1) Logistic(u, b) Logistic distribution with location u ans scaleb

params(d) Get the parameters, i.e. (u, b) location(d) Get the locationparameter, i.e. u scale(d) Get the scale parameter, i.e. b

External links

• Logistic distribution on Wikipedia

4.28 Distributions.NegativeBinomial

Distributions.NegativeBinomial — Type.

NegativeBinomial(r,p)

A Negative binomial distribution describes the number of failures before therth success in a sequence of independent Bernoulli trials. It is parameterizedby r, the number of successes, and p, the probability of success in an individualtrial.

P (X = k) =

(k + r − 1

k

)pr(1− p)k, for k = 0, 1, 2, . . . .

The distribution remains well-defined for any positive r, in which case

P (X = k) =Γ(k + r)

k!Γ(r)pr(1− p)k, for k = 0, 1, 2, . . . .

[] NegativeBinomial() Negative binomial distribution with r = 1 and p =0.5 NegativeBinomial(r, p) Negative binomial distribution with r successes andsuccess rate p

params(d) Get the parameters, i.e. (r, p) succprob(d) Get the success rate,i.e. p failprob(d) Get the failure rate, i.e. 1 - p

External links:

• Negative binomial distribution on Wikipedia

Page 139: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

134 CHAPTER 4. DISTRIBUTIONS

4.29 Distributions.NoncentralChisq

Distributions.NoncentralChisq — Type.

NoncentralChisq(, )

The noncentral chi-squared distribution with degrees of freedom and non-centrality parameter has the probability density function

f(x;u, lambda) =rac12 e−(x+lambda)/2left(racxlambda ight)u/4−1/2Iu/2−1(sqrtlambdax), quadx > 0It is the distribution of the sum of squares of independent Normal variates

with individual means mui andlambda = sumu

i=1mu2i

[] NoncentralChisq(, ) Noncentral chi-squared distribution with degrees offreedom and noncentrality parameter

params(d) Get the parameters, i.e. (, )External links

• Noncentral chi-squared distribution on Wikipedia

4.30 Distributions.Normal

Distributions.Normal — Type.

Normal(,)

The Normal distribution with mean and standard deviation has probabilitydensity function

f(x;µ, σ) =1√

2πσ2exp

(− (x− µ)2

2σ2

)[] Normal() standard Normal distribution with zero mean and unit variance

Normal(mu) Normal distribution with mean mu and unit variance Normal(mu,sig) Normal distribution with mean mu and variance sig2

params(d) Get the parameters, i.e. (mu, sig) mean(d) Get the mean, i.e.mu std(d) Get the standard deviation, i.e. sig

External links

• Normal distribution on Wikipedia

4.31 Distributions.NormalInverseGaussian

Distributions.NormalInverseGaussian — Type.

NormalInverseGaussian(,,,)

Page 140: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4.32. DISTRIBUTIONS.PARETO 135

The Normal-inverse Gaussian distribution with location , tail heaviness ,asymmetry parameter and scale has probability density function

f(x;µ, α, β, δ) =αδK1

(α√δ2 + (x− µ)2

)π√δ2 + (x− µ)2

eδγ+β(x−µ)

where Kj denotes a modified Bessel function of the third kind.External links

• Normal-inverse Gaussian distribution on Wikipedia

4.32 Distributions.Pareto

Distributions.Pareto — Type.

Pareto(,)

The Pareto distribution with shape and scale has probability density func-tion

f(x;α, θ) =αθα

xα+1, x ≥ θ

[] Pareto() Pareto distribution with unit shape and unit scale, i.e. Pareto(1,1) Pareto(a) Pareto distribution with shape a and unit scale, i.e. Pareto(a, 1)Pareto(a, b) Pareto distribution with shape a and scale b

params(d) Get the parameters, i.e. (a, b) shape(d) Get the shape param-eter, i.e. a scale(d) Get the scale parameter, i.e. b

External links

• Pareto distribution on Wikipedia

4.33 Distributions.Poisson

Distributions.Poisson — Type.

Poisson()

A Poisson distribution descibes the number of independent events occurringwithin a unit time interval, given the average rate of occurrence .

P (X = k) =λk

k!e−λ, for k = 0, 1, 2, . . . .

[] Poisson() Poisson distribution with rate parameter 1 Poisson(lambda)Poisson distribution with rate parameter lambda

params(d) Get the parameters, i.e. (,) mean(d) Get the mean arrival rate,i.e.

External links:

• Poisson distribution on Wikipedia

Page 141: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

136 CHAPTER 4. DISTRIBUTIONS

4.34 Distributions.PoissonBinomial

Distributions.PoissonBinomial — Type.

PoissonBinomial(p)

A Poisson-binomial distribution describes the number of successes in a se-quence of independent trials, wherein each trial has a different success rate. Itis parameterized by a vector p (of length K), where K is the total number oftrials and p[i] corresponds to the probability of success of the ith trial.

P (X = k) =∑A∈Fk

∏i∈A

p[i]∏j∈Ac

(1− p[j]), for k = 0, 1, 2, . . . ,K,

where Fk is the set of all subsets of k integers that can be selected from{1, 2, 3, ...,K}.

[] PoissonBinomial(p) Poisson Binomial distribution with success rate vectorp

params(d) Get the parameters, i.e. (p,) succprob(d) Get the vector ofsuccess rates, i.e. p failprob(d) Get the vector of failure rates, i.e. 1-p

External links:

• Poisson-binomial distribution on Wikipedia

4.35 Distributions.Rayleigh

Distributions.Rayleigh — Type.

Rayleigh()

The Rayleigh distribution with scale has probability density function

f(x;σ) =x

σ2e−

x2

2σ2 , x > 0

It is related to the Normal distribution via the property that if X,Y ∼Normal(0, σ), independently, then

√X2 + Y 2 ∼ Rayleigh(σ).

[] Rayleigh() Rayleigh distribution with unit scale, i.e. Rayleigh(1) Rayleigh(s)Rayleigh distribution with scale s

params(d) Get the parameters, i.e. (s,) scale(d) Get the scale parameter,i.e. s

External links

• Rayleigh distribution on Wikipedia

Page 142: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4.36. DISTRIBUTIONS.SKELLAM 137

4.36 Distributions.Skellam

Distributions.Skellam — Type.

Skellam(1, 2)

A Skellam distribution describes the difference between two independentPoisson variables, respectively with rate 1 and 2.

P (X = k) = e−(µ1+µ2)

(µ1

µ2

)k/2Ik(2√µ1µ2) for integer k

where Ik is the modified Bessel function of the first kind.

[] Skellam(mu1, mu2) Skellam distribution for the difference between twoPoisson variables, respectively with expected values mu1 and mu2.

params(d) Get the parameters, i.e. (mu1, mu2)

External links:

• Skellam distribution on Wikipedia

4.37 Distributions.SymTriangularDist

Distributions.SymTriangularDist — Type.

SymTriangularDist(,)

The Symmetric triangular distribution with location and scale has proba-bility density function

f(x;µ, σ) =1

σ

(1−

∣∣∣∣x− µσ∣∣∣∣) , µ− σ ≤ x ≤ µ+ σ

[] SymTriangularDist() Symmetric triangular distribution with zero loca-tion and unit scale SymTriangularDist(u) Symmetric triangular distributionwith location u and unit scale SymTriangularDist(u, s) Symmetric triangulardistribution with location u and scale s

params(d) Get the parameters, i.e. (u, s) location(d) Get the locationparameter, i.e. u scale(d) Get the scale parameter, i.e. s

4.38 Distributions.TDist

Distributions.TDist — Type.

TDist()

Page 143: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

138 CHAPTER 4. DISTRIBUTIONS

The Students T distribution with degrees of freedom has probability densityfunction

f(x; d) =1√

dB(1/2, d/2)

(1 +

x2

d

)− d+12

[] TDist(d) t-distribution with d degrees of freedomparams(d) Get the parameters, i.e. (d,) dof(d) Get the degrees of freedom,

i.e. dExternal linksStudent’s T distribution on Wikipedia

4.39 Distributions.TriangularDist

Distributions.TriangularDist — Type.

TriangularDist(a,b,c)

The triangular distribution with lower limit a, upper limit b and mode c hasprobability density function

f(x; a, b, c) =

0 for x < a,2(x−a)

(b−a)(c−a) for a ≤ x ≤ c,2(b−x)

(b−a)(b−c) for c < x ≤ b,

0 for b < x,

[] TriangularDist(a, b) Triangular distribution with lower limit a, upperlimit b, and mode (a+b)/2 TriangularDist(a, b, c) Triangular distribution withlower limit a, upper limit b, and mode c

params(d) Get the parameters, i.e. (a, b, c) minimum(d) Get the lowerbound, i.e. a maximum(d) Get the upper bound, i.e. b mode(d) Get the mode,i.e. c

External links

• Triangular distribution on Wikipedia

4.40 Distributions.Uniform

Distributions.Uniform — Type.

Uniform(a,b)

The continuous uniform distribution over an interval [a, b] has probabilitydensity function

Page 144: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

4.41. DISTRIBUTIONS.VONMISES 139

f(x; a, b) =1

b− a, a ≤ x ≤ b

[] Uniform() Uniform distribution over [0, 1] Uniform(a, b) Uniform distri-bution over [a, b]

params(d) Get the parameters, i.e. (a, b) minimum(d) Get the lowerbound, i.e. a maximum(d) Get the upper bound, i.e. b location(d) Get thelocation parameter, i.e. a scale(d) Get the scale parameter, i.e. b - a

External links

• Uniform distribution (continuous) on Wikipedia

4.41 Distributions.VonMises

Distributions.VonMises — Type.

VonMises(, )

The von Mises distribution with mean and concentration has probabilitydensity function

f(x;µ, κ) =1

2πI0(κ)exp (κ cos(x− µ))

[] VonMises() von Mises distribution with zero mean and unit concentrationVonMises() von Mises distribution with zero mean and concentration Von-Mises(, ) von Mises distribution with mean and concentration

External links

• von Mises distribution on Wikipedia

4.42 Distributions.Weibull

Distributions.Weibull — Type.

Weibull(,)

The Weibull distribution with shape and scale has probability densityfunction

f(x;α, θ) =α

θ

(xθ

)α−1e−(x/θ)

α

, x ≥ 0

[] Weibull() Weibull distribution with unit shape and unit scale, i.e. Weibull(1,1) Weibull(a) Weibull distribution with shape a and unit scale, i.e. Weibull(a,1) Weibull(a, b) Weibull distribution with shape a and scale b

params(d) Get the parameters, i.e. (a, b) shape(d) Get the shape param-eter, i.e. a scale(d) Get the scale parameter, i.e. b

External links

• Weibull distribution on Wikipedia

Page 145: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 5

Images

5.1 ColorTypes.blue

ColorTypes.blue — Function.b = blue(img) extracts the blue channel from an RGB image img

5.2 ColorTypes.green

ColorTypes.green — Function.g = green(img) extracts the green channel from an RGB image img

5.3 ColorTypes.red

ColorTypes.red — Function.r = red(img) extracts the red channel from an RGB image img

5.4 Images.adjust gamma

Images.adjust gamma — Method.

gamma_corrected_img = adjust_gamma(img, gamma)

Returns a gamma corrected image.The adjust gamma function can handle a variety of input types. The re-

turned image depends on the input type. If the input is an Image then theresulting image is of the same type and has the same properties.

For coloured images, the input is converted to YIQ type and the Y channelis gamma corrected. This is the combined with the I and Q channels and theresulting image converted to the same type as the input.

140

Page 146: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

5.5. IMAGES.BILINEAR INTERPOLATION 141

5.5 Images.bilinear interpolation

Images.bilinear interpolation — Method.

P = bilinear_interpolation(img, r, c)

Bilinear Interpolation is used to interpolate functions of two variables on arectilinear 2D grid.

The interpolation is done in one direction first and then the values obtainedare used to do the interpolation in the second direction.

5.6 Images.blob LoG

Images.blob LoG — Function.

blob_LoG(img, s, [edges]) -> Vector{BlobLoG}

Find “blobs” in an N-D image using the negative Lapacian of Gaussians withthe specifed vector or tuple of values. The algorithm searches for places wherethe filtered image (for a particular ) is at a peak compared to all spatially- and-adjacent voxels.

The optional edges argument controls whether peaks on the edges are in-cluded. edges can be true or false, or a N+1-tuple in which the first entrycontrols whether edge- values are eligible to serve as peaks, and the remainingN entries control each of the N dimensions of img.

Citation:Lindeberg T (1998), “Feature Detection with Automatic Scale Selection”,

International Journal of Computer Vision, 30(2), 79–116.See also: BlobLoG.

5.7 Images.bothat

Images.bothat — Function.imgbh = bothat(img, [region]) performs bottom hat of an image, which

is defined as its morphological closing minus the original image. region allowsyou to control the dimensions over which this operation is performed.

5.8 Images.boxdiff

Images.boxdiff — Method.

sum = boxdiff(integral_image, ytop:ybot, xtop:xbot)

sum = boxdiff(integral_image, CartesianIndex(tl_y, tl_x), CartesianIndex(br_y, br_x))

sum = boxdiff(integral_image, tl_y, tl_x, br_y, br_x)

Page 147: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

142 CHAPTER 5. IMAGES

An integral image is a data structure which helps in efficient calculation ofsum of pixels in a rectangular subset of an image. It stores at each pixel the sumof all pixels above it and to its left. The sum of a window in an image can bedirectly calculated using four array references of the integral image, irrespectiveof the size of the window, given the yrange and xrange of the window. Givenan integral image -

A - - - - - - B -

- * * * * * * * -

- * * * * * * * -

- * * * * * * * -

- * * * * * * * -

- * * * * * * * -

C * * * * * * D -

- - - - - - - - -

The sum of pixels in the area denoted by * is given by S = D + A - B - C.

5.9 Images.canny

Images.canny — Function.

canny_edges = canny(img, sigma = 1.4, upperThreshold = 0.80, lowerThreshold = 0.20)

Performs Canny Edge Detection on the input image.Parameters :sigma : Specifies the standard deviation of the gaussian filter upperThresh-

old : Upper bound for hysteresis thresholding lowerThreshold : Lower boundfor hysteresis thresholding astype : Specifies return type of result percentile :Specifies if upperThreshold and lowerThreshold should be used as quantiles orabsolute values

5.10 Images.clahe

Images.clahe — Function.

hist_equalised_img = clahe(img, nbins, xblocks = 8, yblocks = 8, clip = 3)

Performs Contrast Limited Adaptive Histogram Equalisation (CLAHE) onthe input image. It differs from ordinary histogram equalization in the respectthat the adaptive method computes several histograms, each corresponding toa distinct section of the image, and uses them to redistribute the lightnessvalues of the image. It is therefore suitable for improving the local contrast andenhancing the definitions of edges in each region of an image.

In the straightforward form, CLAHE is done by calculation a histogramof a window around each pixel and using the transformation function of the

Page 148: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

5.11. IMAGES.CLIPHIST 143

equalised histogram to rescale the pixel. Since this is computationally expen-sive, we use interpolation which gives a significant rise in efficiency withoutcompromising the result. The image is divided into a grid and equalised his-tograms are calculated for each block. Then, each pixel is interpolated usingthe closest histograms.

The xblocks and yblocks specify the number of blocks to divide the inputimage into in each direction. nbins specifies the granularity of histogram cal-culation of each local region. clip specifies the value at which the histogram isclipped. The excess in the histogram bins with value exceeding clip is redis-tributed among the other bins.

5.11 Images.cliphist

Images.cliphist — Method.

clipped_hist = cliphist(hist, clip)

Clips the histogram above a certain value clip. The excess left in the binsexceeding clip is redistributed among the remaining bins.

5.12 Images.closing

Images.closing — Function.imgc = closing(img, [region]) performs the closing morphology oper-

ation, equivalent to erode(dilate(img)). region allows you to control thedimensions over which this operation is performed.

5.13 Images.component boxes

Images.component boxes — Method.component boxes(labeled array) -> an array of bounding boxes for each

label, including the background label 0

5.14 Images.component centroids

Images.component centroids — Method.component centroids(labeled array) -> an array of centroids for each

label, including the background label 0

5.15 Images.component indices

Images.component indices — Method.component indices(labeled array) -> an array of pixels for each label,

including the background label 0

Page 149: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

144 CHAPTER 5. IMAGES

5.16 Images.component lengths

Images.component lengths — Method.component lengths(labeled array) -> an array of areas (2D), volumes

(3D), etc. for each label, including the background label 0

5.17 Images.component subscripts

Images.component subscripts — Method.component subscripts(labeled array) -> an array of pixels for each la-

bel, including the background label 0

5.18 Images.dilate

Images.dilate — Function.

imgd = dilate(img, [region])

perform a max-filter over nearest-neighbors. The default is 8-connectivityin 2d, 27-connectivity in 3d, etc. You can specify the list of dimensions thatyou want to include in the connectivity, e.g., region = [1,2] would excludethe third dimension from filtering.

5.19 Images.entropy

Images.entropy — Method.

entropy(log, img)

entropy(img; [kind=:shannon])

Compute the entropy of a grayscale image defined as -sum(p.*log(p)). Thebase of the logarithm (a.k.a. entropy unit) is one of the following:

• :shannon (log base 2, default), or use log = log2

• :nat (log base e), or use log = log

• :hartley (log base 10), or use log = log10

5.20 Images.erode

Images.erode — Function.

imge = erode(img, [region])

perform a min-filter over nearest-neighbors. The default is 8-connectivity in2d, 27-connectivity in 3d, etc. You can specify the list of dimensions that youwant to include in the connectivity, e.g., region = [1,2] would exclude thethird dimension from filtering.

Page 150: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

5.21. IMAGES.FASTCORNERS 145

5.21 Images.fastcorners

Images.fastcorners — Function.

fastcorners(img, n, threshold) -> corners

Performs FAST Corner Detection. n is the number of contiguous pixels whichneed to be greater (lesser) than intensity + threshold (intensity - threshold) fora pixel to be marked as a corner. The default value for n is 12.

5.22 Images.findlocalmaxima

Images.findlocalmaxima — Function.

findlocalmaxima(img, [region, edges]) -> Vector{Tuple}Returns the coordinates of elements whose value is larger than all of their

immediate neighbors. region is a list of dimensions to consider. edges is aboolean specifying whether to include the first and last elements of each dimen-sion, or a tuple-of-Bool specifying edge behavior for each dimension separately.

5.23 Images.findlocalminima

Images.findlocalminima — Function.

Like findlocalmaxima, but returns the coordinates of the smallest elements.

5.24 Images.gaussian pyramid

Images.gaussian pyramid — Method.

pyramid = gaussian_pyramid(img, n_scales, downsample, sigma)

Returns a gaussian pyramid of scales n scales, each downsampled by afactor downsample and sigma for the gaussian kernel.

5.25 Images.harris

Images.harris — Method.

harris_response = harris(img; [k], [border], [weights])

Performs Harris corner detection. The covariances can be taken using eithera mean weighted filter or a gamma kernel.

Page 151: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

146 CHAPTER 5. IMAGES

5.26 Images.hausdorff distance

Images.hausdorff distance — Method.hausdorff distance(imgA, imgB) is the modified Hausdorff distance be-

tween binary images (or point sets).ReferencesDubuisson, M-P; Jain, A. K., 1994. A Modified Hausdorff Distance for

Object-Matching.

5.27 Images.histeq

Images.histeq — Method.

hist_equalised_img = histeq(img, nbins)

hist_equalised_img = histeq(img, nbins, minval, maxval)

Returns a histogram equalised image with a granularity of approximatelynbins number of bins.

The histeq function can handle a variety of input types. The returnedimage depends on the input type. If the input is an Image then the resultingimage is of the same type and has the same properties.

For coloured images, the input is converted to YIQ type and the Y channelis equalised. This is the combined with the I and Q channels and the resultingimage converted to the same type as the input.

If minval and maxval are specified then intensities are equalized to the range(minval, maxval). The default values are 0 and 1.

5.28 Images.histmatch

Images.histmatch — Function.

hist_matched_img = histmatch(img, oimg, nbins)

Returns a grayscale histogram matched image with a granularity of nbins

number of bins. img is the image to be matched and oimg is the image havingthe desired histogram to be matched to.

5.29 Images.imROF

Images.imROF — Method.

imgr = imROF(img, lambda, iterations)

Perform Rudin-Osher-Fatemi (ROF) filtering, more commonly known as To-tal Variation (TV) denoising or TV regularization. lambda is the regularizationcoefficient for the derivative, and iterations is the number of relaxation iter-ations taken. 2d only.

Page 152: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

5.30. IMAGES.IMADJUSTINTENSITY 147

5.30 Images.imadjustintensity

Images.imadjustintensity — Method.

imadjustintensity(img [, (minval,maxval)]) -> Image

Map intensities over the interval (minval,maxval) to the interval [0,1].This is equivalent to map(ScaleMinMax(eltype(img), minval, maxval),

img). (minval,maxval) defaults to extrema(img).

5.31 Images.imaverage

Images.imaverage — Function.

kern = imaverage(filtersize) constructs a boxcar-filter of the specifiedsize.

5.32 Images.imcomplement

Images.imcomplement — Method.

complement_img = imcomplement(img)

Returns the complement of an image.

5.33 Images.imcorner

Images.imcorner — Method.

corners = imcorner(img; [method])

corners = imcorner(img, threshold, percentile; [method])

Performs corner detection using one of the following methods -

1. harris

2. shi_tomasi

3. kitchen_rosenfeld

The parameters of the individual methods are described in their documen-tation. The maxima values of the resultant responses are taken as corners. If athreshold is specified, the values of the responses are thresholded to give the cor-ner pixels. The threshold is assumed to be a percentile value unless percentileis set to false.

Page 153: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

148 CHAPTER 5. IMAGES

5.34 Images.imedge

Images.imedge — Function.

grad_x, grad_y, mag, orient = imedge(img, [method], [border])

Edge-detection filtering. method is one of "sobel", "prewitt", "ando3","ando4", "ando4 sep", "ando5", or "ando5 sep", defaulting to "ando3" (seethe functions of the same name for more information). border is any of theboundary conditions specified in padarray.

Returns a tuple (grad x, grad y, mag, orient), which are the horizontalgradient, vertical gradient, and the magnitude and orientation of the strongestedge, respectively.

5.35 Images.imhist

Images.imhist — Method.

edges, count = imhist(img, nbins)

edges, count = imhist(img, nbins, minval, maxval)

Generates a histogram for the image over nbins spread between (minval,

maxval]. If minval and maxval are not given, then the minimum and maximumvalues present in the image are taken.

edges is a vector that specifies how the range is divided; count[i+1] is thenumber of values x that satisfy edges[i] <= x < edges[i+1]. count[1] isthe number satisfying x < edges[1], and count[end] is the number satisfyingx >= edges[end]. Consequently, length(count) == length(edges)+1.

5.36 Images.imstretch

Images.imstretch — Method.

imgs = imstretch(img, m, slope) enhances or reduces (for slope > 1 or< 1, respectively) the contrast near saturation (0 and 1). This is essentially asymmetric gamma-correction. For a pixel of brightness p, the new intensity is1/(1+(m/(p+eps))^slope).

This assumes the input img has intensities between 0 and 1.

5.37 Images.integral image

Images.integral image — Method.

integral_img = integral_image(img)

Page 154: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

5.38. IMAGES.KITCHEN ROSENFELD 149

Returns the integral image of an image. The integral image is calculatedby assigning to each pixel the sum of all pixels above it and to its left, i.e. therectangle from (1, 1) to the pixel. An integral image is a data structure whichhelps in efficient calculation of sum of pixels in a rectangular subset of an image.See boxdiff for more information.

5.38 Images.kitchen rosenfeld

Images.kitchen rosenfeld — Method.

kitchen_rosenfeld_response = kitchen_rosenfeld(img; [border])

Performs Kitchen Rosenfeld corner detection. The covariances can be takenusing either a mean weighted filter or a gamma kernel.

5.39 Images.label components

Images.label components — Function.

label = label_components(tf, [connectivity])

label = label_components(tf, [region])

Find the connected components in a binary array tf. There are two formsthat connectivity can take:

• It can be a boolean array of the same dimensionality as tf, of size 1 or 3

along each dimension. Each entry in the array determines whether a givenneighbor is used for connectivity analyses. For example, connectivity = trues(3,3)

would use 8-connectivity and test all pixels that touch the current one, even thecorners.

• You can provide a list indicating which dimensions are used to

determine connectivity. For example, region = [1,3] would not test neigh-bors along dimension 2 for connectivity. This corresponds to just the nearestneighbors, i.e., 4-connectivity in 2d and 6-connectivity in 3d.

The default is region = 1:ndims(A).The output label is an integer array, where 0 is used for background pixels,

and each connected region gets a different integer index.

5.40 Images.magnitude

Images.magnitude — Method.

m = magnitude(grad_x, grad_y)

Calculates the magnitude of the gradient images given by grad x and grad y.Equivalent to sqrt(gradx.

2 + grady.2).

Returns a magnitude image the same size as grad x and grad y.

Page 155: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

150 CHAPTER 5. IMAGES

5.41 Images.magnitude phase

Images.magnitude phase — Method.

magnitude_phase(grad_x, grad_y) -> m, p

Convenience function for calculating the magnitude and phase of the gradientimages given in grad x and grad y. Returns a tuple containing the magnitudeand phase images. See magnitude and phase for details.

5.42 Images.mapinfo

Images.mapinfo — Method.mapi = mapinf(T, img) returns a MapInfo object that is deemed appro-

priate for converting pixels of img to be of type T. T can either be a specific type(e.g., RGB24), or you can specify an abstract type like Clamp and it will returnone of the Clamp family of MapInfo objects.

You can define your own rules for mapinfo. For example, the ImageMagick

package defines methods for how pixels values should be converted before savingimages to disk.

5.43 Images.maxabsfinite

Images.maxabsfinite — Method.m = maxabsfinite(A) calculates the maximum absolute value in A, ignoring

any values that are not finite (Inf or NaN).

5.44 Images.maxfinite

Images.maxfinite — Method.m = maxfinite(A) calculates the maximum value in A, ignoring any values

that are not finite (Inf or NaN).

5.45 Images.meanfinite

Images.meanfinite — Method.M = meanfinite(img, region) calculates the mean value along the dimen-

sions listed in region, ignoring any non-finite values.

5.46 Images.minfinite

Images.minfinite — Method.m = minfinite(A) calculates the minimum value in A, ignoring any values

that are not finite (Inf or NaN).

Page 156: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

5.47. IMAGES.MORPHOGRADIENT 151

5.47 Images.morphogradient

Images.morphogradient — Function.imgmg = morphogradient(img, [region]) returns morphological gradient

of the image, which is the difference between the dilation and the erosion ofa given image. region allows you to control the dimensions over which thisoperation is performed.

5.48 Images.morpholaplace

Images.morpholaplace — Function.imgml = morpholaplace(img, [region]) performs Morphological Laplacian

of an image, which is defined as the arithmetic difference between the internaland the external gradient. region allows you to control the dimensions overwhich this operation is performed.

5.49 Images.ncc

Images.ncc — Method.C = ncc(A, B) computes the normalized cross-correlation of A and B.

5.50 Images.opening

Images.opening — Function.imgo = opening(img, [region]) performs the opening morphology oper-

ation, equivalent to dilate(erode(img)). region allows you to control thedimensions over which this operation is performed.

5.51 Images.orientation

Images.orientation — Function.

orientation(grad_x, grad_y) -> orient

Calculate the orientation angle of the strongest edge from gradient imagesgiven by grad x and grad y. Equivalent to atan2(grad x, grad y). Whenboth grad x and grad y are effectively zero, the corresponding angle is set tozero.

5.52 Images.phase

Images.phase — Function.

phase(grad_x, grad_y) -> p

Page 157: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

152 CHAPTER 5. IMAGES

Calculate the rotation angle of the gradient given by grad x and grad y.Equivalent to atan2(-grad y, grad x), except that when both grad x andgrad y are effectively zero, the corresponding angle is set to zero.

5.53 Images.sad

Images.sad — Method.s = sad(A, B) computes the sum-of-absolute differences over arrays/images

A and B

5.54 Images.sadn

Images.sadn — Method.s = sadn(A, B) computes the sum-of-absolute differences over arrays/images

A and B, normalized by array size

5.55 Images.sc

Images.sc — Method.

imgsc = sc(img)

imgsc = sc(img, min, max)

Applies default or specified ScaleMinMax mapping to the image.

5.56 Images.shepp logan

Images.shepp logan — Method.

phantom = shepp_logan(N,[M]; highContrast=true)

output the NxM Shepp-Logan phantom, which is a standard test image usu-ally used for comparing image reconstruction algorithms in the field of computedtomography (CT) and magnetic resonance imaging (MRI). If the argument Mis omitted, the phantom is of size NxN. When setting the keyword argumenthighConstrast to false, the CT version of the phantom is created. Otherwise,the high contrast MRI version is calculated.

5.57 Images.shi tomasi

Images.shi tomasi — Method.

shi_tomasi_response = shi_tomasi(img; [border], [weights])

Performs Shi Tomasi corner detection. The covariances can be taken usingeither a mean weighted filter or a gamma kernel.

Page 158: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

5.58. IMAGES.SSD 153

5.58 Images.ssd

Images.ssd — Method.

s = ssd(A, B) computes the sum-of-squared differences over arrays/imagesA and B

5.59 Images.ssdn

Images.ssdn — Method.

s = ssdn(A, B) computes the sum-of-squared differences over arrays/imagesA and B, normalized by array size

5.60 Images.thin edges

Images.thin edges — Function.

thinned = thin_edges(img, gradientangle, [border])

thinned, subpix = thin_edges_subpix(img, gradientangle, [border])

thinned, subpix = thin_edges_nonmaxsup(img, gradientangle, [border]; [radius::Float64=1.35], [theta=pi/180])

thinned, subpix = thin_edges_nonmaxsup_subpix(img, gradientangle, [border]; [radius::Float64=1.35], [theta=pi/180])

Edge thinning for 2D edge images. Currently the only algorithm availableis non-maximal suppression, which takes an edge image and its gradient angle,and checks each edge point for local maximality in the direction of the gradient.The returned image is non-zero only at maximal edge locations.

border is any of the boundary conditions specified in padarray.

In addition to the maximal edge image, the subpix versions of these func-tions also return an estimate of the subpixel location of each local maxima, as a2D array or image of Graphics.Point objects. Additionally, each local maximais adjusted to the estimated value at the subpixel location.

Currently, the nonmaxsup functions are identical to the first two functioncalls, except that they also accept additional keyword arguments. radius indi-cates the step size to use when searching in the direction of the gradient; valuesbetween 1.2 and 1.5 are suggested (default 1.35). theta indicates the step sizeto use when discretizing angles in the gradientangle image, in radians (default:1 degree in radians = pi/180).

Example:

g = rgb2gray(rgb_image)

gx, gy = imgradients(g)

mag, grad_angle = magnitude_phase(gx,gy)

mag[mag .< 0.5] = 0.0 # Threshold magnitude image

thinned, subpix = thin_edges_subpix(mag, grad_angle)

Page 159: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

154 CHAPTER 5. IMAGES

5.61 Images.tophat

Images.tophat — Function.imgth = tophat(img, [region]) performs top hat of an image, which is

defined as the image minus its morphological opening. region allows you tocontrol the dimensions over which this operation is performed.

Page 160: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 6

DataFrames

6.1 DataArrays.head

DataArrays.head — Function.Show the first or last part of an AbstractDataFrame[] head(df::AbstractDataFrame, r::Int = 6) tail(df::AbstractDataFrame, r::Int

= 6)Arguments

• df : the AbstractDataFrame

• r : the number of rows to show

Result

• ::AbstractDataFrame : the first or last part of df

Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10))

head(df) tail(df)

6.2 DataArrays.tail

DataArrays.tail — Function.Show the first or last part of an AbstractDataFrame[] head(df::AbstractDataFrame, r::Int = 6) tail(df::AbstractDataFrame, r::Int

= 6)Arguments

• df : the AbstractDataFrame

• r : the number of rows to show

155

Page 161: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

156 CHAPTER 6. DATAFRAMES

Result

• ::AbstractDataFrame : the first or last part of df

Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10))

head(df) tail(df)

6.3 DataFrames.aggregate

DataFrames.aggregate — Method.Split-apply-combine that applies a set of functions over columns of an Ab-

stractDataFrame or GroupedDataFrame[] aggregate(d::AbstractDataFrame, cols, fs) aggregate(gd::GroupedDataFrame,

fs)Arguments

• d : an AbstractDataFrame

• gd : a GroupedDataFrame

• cols : a column indicator (Symbol, Int, Vector{Symbol}, etc.)

• fs : a function or vector of functions to be applied to vectors withingroups; expects each argument to be a column vector

Each fs should return a value or vector. All returns must be the samelength.

Returns

• ::DataFrame

Examples[] df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]), b = repeat([2, 1],

outer=[4]), c = randn(8)) aggregate(df, :a, sum) aggregate(df, :a, [sum, mean])aggregate(groupby(df, :a), [sum, mean]) df —¿ groupby(:a) —¿ [sum, mean]equivalent

6.4 DataFrames.by

DataFrames.by — Method.Split-apply-combine in one step; apply f to each grouping in d based on

columns col

[] by(d::AbstractDataFrame, cols, f::Function) by(f::Function, d::AbstractDataFrame,cols)

Arguments

Page 162: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

6.5. DATAFRAMES.COEFNAMES 157

• d : an AbstractDataFrame

• cols : a column indicator (Symbol, Int, Vector{Symbol}, etc.)

• f : a function to be applied to groups; expects each argument to be anAbstractDataFrame

f can return a value, a vector, or a DataFrame. For a value or vector, theseare merged into a column along with the cols keys. For a DataFrame, cols arecombined along columns with the resulting DataFrame. Returning a DataFrameis the clearest because it allows column labeling.

A method is defined with f as the first argument, so do-block notation canbe used.

by(d, cols, f) is equivalent to combine(map(f, groupby(d, cols))).Returns

• ::DataFrame

Examples[] df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]), b = repeat([2, 1],

outer=[4]), c = randn(8)) by(df, :a, d -¿ sum(d[:c])) by(df, :a, d -¿ 2 * d[:c]) by(df,:a, d -¿ DataFrame(csum = sum(d[: c]), cmean = mean(d[: c])))by(df, : a, d− > DataFrame(c = d[: c], cmean = mean(d[: c])))by(df, [: a, : b])dodDataFrame(m = mean(d[: c]), v = var(d[: c]))end

6.5 DataFrames.coefnames

DataFrames.coefnames — Method.

coefnames(mf::ModelFrame)

Returns a vector of coefficient names constructed from the Terms memberand the types of the evaluation columns.

6.6 DataFrames.colwise

DataFrames.colwise — Method.Apply a function to each column in an AbstractDataFrame or Grouped-

DataFrame[] colwise(f::Function, d) colwise(d)Arguments

• f : a function or vector of functions

• d : an AbstractDataFrame of GroupedDataFrame

If d is not provided, a curried version of groupby is given.Returns

Page 163: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

158 CHAPTER 6. DATAFRAMES

• various, depending on the call

Examples

[] df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]), b = repeat([2, 1],outer=[4]), c = randn(8)) colwise(sum, df) colwise(sum, groupby(df, :a))

6.7 DataFrames.combine

DataFrames.combine — Method.

Combine a GroupApplied object (rudimentary)

[] combine(ga::GroupApplied)

Arguments

• ga : a GroupApplied

Returns

• ::DataFrame

Examples

[] df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]), b = repeat([2, 1],outer=[4]), c = randn(8)) combine(map(d -¿ mean(d[:c]), gd))

6.8 DataFrames.complete cases!

DataFrames.complete cases! — Method.

Delete rows with NA’s.

[] completecases!(df :: AbstractDataFrame)

Arguments

• df : the AbstractDataFrame

Result

• ::AbstractDataFrame : the updated version

See also complete cases.

Examples

[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10))df[[1,4,5], :x] = NA df[[9,10], :y] = NA completecases!(df)

Page 164: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

6.9. DATAFRAMES.COMPLETE CASES 159

6.9 DataFrames.complete cases

DataFrames.complete cases — Method.Indexes of complete cases (rows without NA’s)[] completecases(df :: AbstractDataFrame)Arguments

• df : the AbstractDataFrame

Result

• ::Vector{Bool} : indexes of complete cases

See also complete cases!.Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10))

df[[1,4,5], :x] = NA df[[9,10], :y] = NA completecases(df)

6.10 DataFrames.eltypes

DataFrames.eltypes — Method.Column elemental types[] eltypes(df::AbstractDataFrame)Arguments

• df : the AbstractDataFrame

Result

• ::Vector{Type} : the elemental type of each column

Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10))

eltypes(df)

6.11 DataFrames.groupby

DataFrames.groupby — Method.A view of an AbstractDataFrame split into row groups[] groupby(d::AbstractDataFrame, cols) groupby(cols)Arguments

• d : an AbstractDataFrame

• cols : an

If d is not provided, a curried version of groupby is given.Returns

Page 165: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

160 CHAPTER 6. DATAFRAMES

• ::GroupedDataFrame : a grouped view into d

DetailsAn iterator over a GroupedDataFrame returns a SubDataFrame view for each

grouping into d. A GroupedDataFrame also supports indexing by groups andmap.

See the following for additional split-apply-combine operations:

• by : split-apply-combine using functions

• aggregate : split-apply-combine; applies functions in the form of a crossproduct

• combine : combine (obviously)

• colwise : apply a function to each column in an AbstractDataFrame orGroupedDataFrame

Piping methods |> are also provided.See the DataFramesMeta package for more operations on GroupedDataFrames.Examples[] df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]), b = repeat([2, 1],

outer=[4]), c = randn(8)) gd = groupby(df, :a) gd[1] last(gd) vcat([g[:b] forg in gd]...) for g in gd println(g) end map(d -¿ mean(d[:c]), gd) returns aGroupApplied object combine(map(d -¿ mean(d[:c]), gd)) df —¿ groupby(:a)—¿ [sum, length] df —¿ groupby([:a, :b]) —¿ [sum, length]

6.12 DataFrames.melt

DataFrames.melt — Method.Stacks a DataFrame; convert from a wide to long format; see stack.

6.13 DataFrames.meltdf

DataFrames.meltdf — Method.A stacked view of a DataFrame (long format); see stackdf

6.14 DataFrames.names!

DataFrames.names! — Method.Set column names[] names!(df::AbstractDataFrame, vals)Arguments

• df : the AbstractDataFrame

Page 166: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

6.15. DATAFRAMES.NONUNIQUE 161

• vals : column names, normally a Vector{Symbol} the same length as thenumber of columns in df

• allow duplicates : if false (the default), an error will be raised ifduplicate names are found; if true, duplicate names will be suffixed withi (i starting at 1 for the first duplicate).

Result

• ::AbstractDataFrame : the updated result

Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10))

names!(df, [:a, :b, :c]) names!(df, [:a, :b, :a]) throws ArgumentError names!(df,[:a, :b, :a], allowduplicates = true)renamessecond : ato : a1

6.15 DataFrames.nonunique

DataFrames.nonunique — Method.Indexes of complete cases (rows without NA’s)[] nonunique(df::AbstractDataFrame) nonunique(df::AbstractDataFrame, cols)

Arguments

• df : the AbstractDataFrame

• cols : a column indicator (Symbol, Int, Vector{Symbol}, etc.) specifyingthe column(s) to compare

Result

• ::Vector{Bool} : indicates whether the row is a duplicate of some priorrow

See also unique and unique!.Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10)) df

= vcat(df, df) nonunique(df) nonunique(df, 1)

6.16 DataFrames.readtable

DataFrames.readtable — Method.Read data from a tabular-file format (CSV, TSV, . . . )[] readtable(filename, [keyword options])Arguments

• filename::AbstractString : the filename to be read

Page 167: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

162 CHAPTER 6. DATAFRAMES

Keyword Arguments

• header::Bool – Use the information from the file’s header line to deter-mine column names. Defaults to true.

• separator::Char – Assume that fields are split by the separator char-acter. If not specified, it will be guessed from the filename: .csv defaultsto ,, .tsv defaults to , .wsv defaults to .

• quotemark::Vector{Char} – Assume that fields contained inside of twoquotemark characters are quoted, which disables processing of separatorsand linebreaks. Set to Char[] to disable this feature and slightly improveperformance. Defaults to ["].

• decimal::Char – Assume that the decimal place in numbers is writtenusing the decimal character. Defaults to ..

• nastrings::Vector{String} – Translate any of the strings into this vec-tor into an NA. Defaults to ["", "NA"].

• truestrings::Vector{String} – Translate any of the strings into thisvector into a Boolean true. Defaults to ["T", "t", "TRUE", "true"].

• falsestrings::Vector{String} – Translate any of the strings into thisvector into a Boolean false. Defaults to ["F", "f", "FALSE", "false"].

• makefactors::Bool – Convert string columns into PooledDataVector’sfor use as factors. Defaults to false.

• nrows::Int – Read only nrows from the file. Defaults to -1, which indi-cates that the entire file should be read.

• names::Vector{Symbol} – Use the values in this array as the names forall columns instead of or in lieu of the names in the file’s header. Defaultsto [], which indicates that the header should be used if present or thatnumeric names should be invented if there is no header.

• eltypes::Vector – Specify the types of all columns. Defaults to [].

• allowcomments::Bool – Ignore all text inside comments. Defaults tofalse.

• commentmark::Char – Specify the character that starts comments. De-faults to #.

• ignorepadding::Bool – Ignore all whitespace on left and right sides of afield. Defaults to true.

• skipstart::Int – Specify the number of initial rows to skip. Defaults to0.

Page 168: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

6.17. DATAFRAMES.RENAME 163

• skiprows::Vector{Int} – Specify the indices of lines in the input toignore. Defaults to [].

• skipblanks::Bool – Skip any blank lines in input. Defaults to true.

• encoding::Symbol – Specify the file’s encoding as either :utf8 or :latin1.Defaults to :utf8.

• normalizenames::Bool – Ensure that column names are valid Julia iden-tifiers. For instance this renames a column named "a b" to "a b" whichcan then be accessed with :a b instead of Symbol("a b"). Defaults totrue.

Result

• ::DataFrame

Examples[] df = readtable(”data.csv”) df = readtable(”data.tsv”) df = readtable(”data.wsv”)

df = readtable(”data.txt”, separator = ’ ’) df = readtable(”data.txt”, header =false)

6.17 DataFrames.rename

DataFrames.rename — Function.Rename columns[] rename!(df::AbstractDataFrame, from::Symbol, to::Symbol) rename!(df::AbstractDataFrame,

d::Associative) rename!(f::Function, df::AbstractDataFrame) rename(df::AbstractDataFrame,from::Symbol, to::Symbol) rename(f::Function, df::AbstractDataFrame)

Arguments

• df : the AbstractDataFrame

• d : an Associative type that maps the original name to a new name

• f : a function that has the old column name (a symbol) as input and newcolumn name (a symbol) as output

Result

• ::AbstractDataFrame : the updated result

Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10))

rename(x -¿ @compat(Symbol)(uppercase(string(x))), df) rename(df, @com-pat(Dict(:i=¿:A, :x=¿:X))) rename(df, :y, :Y) rename!(df, @compat(Dict(:i=¿:A,:x=¿:X)))

Page 169: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

164 CHAPTER 6. DATAFRAMES

6.18 DataFrames.rename!

DataFrames.rename! — Function.Rename columns[] rename!(df::AbstractDataFrame, from::Symbol, to::Symbol) rename!(df::AbstractDataFrame,

d::Associative) rename!(f::Function, df::AbstractDataFrame) rename(df::AbstractDataFrame,from::Symbol, to::Symbol) rename(f::Function, df::AbstractDataFrame)

Arguments

• df : the AbstractDataFrame

• d : an Associative type that maps the original name to a new name

• f : a function that has the old column name (a symbol) as input and newcolumn name (a symbol) as output

Result

• ::AbstractDataFrame : the updated result

Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10))

rename(x -¿ @compat(Symbol)(uppercase(string(x))), df) rename(df, @com-pat(Dict(:i=¿:A, :x=¿:X))) rename(df, :y, :Y) rename!(df, @compat(Dict(:i=¿:A,:x=¿:X)))

6.19 DataFrames.stack

DataFrames.stack — Method.Stacks a DataFrame; convert from a wide to long format[] stack(df::AbstractDataFrame, measurevars, idvars)stack(df :: AbstractDataFrame,measurevars)stack(df :: AbstractDataFrame)melt(df :: AbstractDataFrame, idvars,measurevars)melt(df :: AbstractDataFrame, idvars)

Arguments

• df : the AbstractDataFrame to be stacked

• measure vars : the columns to be stacked (the measurement variables),a normal column indexing type, like a Symbol, Vector{Symbol}, Int, etc.;for melt, defaults to all variables that are not id vars

• id vars : the identifier columns that are repeated during stacking, anormal column indexing type; for stack defaults to all variables that arenot measure vars

If neither measure vars or id vars are given, measure vars defaults to allfloating point columns.

Result

Page 170: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

6.20. DATAFRAMES.STACKDF 165

• ::DataFrame : the long-format dataframe with column :value holding thevalues of the stacked columns (measure vars), with column :variable

a Vector of Symbols with the measure vars name, and with columns foreach of the id vars.

See also stackdf and meltdf for stacking methods that return a view intothe original DataFrame. See unstack for converting from long to wide format.

Examples[] d1 = DataFrame(a = repeat([1:3;], inner = [4]), b = repeat([1:4;], inner =

[3]), c = randn(12), d = randn(12), e = map(string, ’a’:’l’))d1s = stack(d1, [:c, :d]) d1s2 = stack(d1, [:c, :d], [:a]) d1m = melt(d1, [:a,

:b, :e])

6.20 DataFrames.stackdf

DataFrames.stackdf — Method.A stacked view of a DataFrame (long format)Like stack and melt, but a view is returned rather than data copies.[] stackdf(df::AbstractDataFrame, measurevars, idvars)stackdf(df :: AbstractDataFrame,measurevars)meltdf(df :: AbstractDataFrame, idvars,measurevars)meltdf(df :: AbstractDataFrame, idvars)

Arguments

• df : the wide AbstractDataFrame

• measure vars : the columns to be stacked (the measurement variables),a normal column indexing type, like a Symbol, Vector{Symbol}, Int, etc.;for melt, defaults to all variables that are not id vars

• id vars : the identifier columns that are repeated during stacking, anormal column indexing type; for stack defaults to all variables that arenot measure vars

Result

• ::DataFrame : the long-format dataframe with column :value holding thevalues of the stacked columns (measure vars), with column :variable

a Vector of Symbols with the measure vars name, and with columns foreach of the id vars.

The result is a view because the columns are special AbstractVectors thatreturn indexed views into the original DataFrame.

Examples[] d1 = DataFrame(a = repeat([1:3;], inner = [4]), b = repeat([1:4;], inner =

[3]), c = randn(12), d = randn(12), e = map(string, ’a’:’l’))d1s = stackdf(d1, [:c, :d]) d1s2 = stackdf(d1, [:c, :d], [:a]) d1m = meltdf(d1,

[:a, :b, :e])

Page 171: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

166 CHAPTER 6. DATAFRAMES

6.21 DataFrames.unique!

DataFrames.unique! — Function.Delete duplicate rows[] unique(df::AbstractDataFrame) unique(df::AbstractDataFrame, cols) unique!(df::AbstractDataFrame)

unique!(df::AbstractDataFrame, cols)Arguments

• df : the AbstractDataFrame

• cols : column indicator (Symbol, Int, Vector{Symbol}, etc.)

specifying the column(s) to compare.Result

• ::AbstractDataFrame : the updated version of df with unique rows.

When cols is specified, the return DataFrame contains complete rows, re-taining in each case the first instance for which df[cols] is unique.

See also nonunique.Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10)) df

= vcat(df, df) unique(df) doesn’t modify df unique(df, 1) unique!(df) modifiesdf

6.22 DataFrames.unstack

DataFrames.unstack — Method.Unstacks a DataFrame; convert from a long to wide format[] unstack(df::AbstractDataFrame, rowkey, colkey, value) unstack(df::AbstractDataFrame,

colkey, value) unstack(df::AbstractDataFrame)Arguments

• df : the AbstractDataFrame to be unstacked

• rowkey : the column with a unique key for each row, if not given, find akey by grouping on anything not a colkey or value

• colkey : the column holding the column names in wide format, defaultsto :variable

• value : the value column, defaults to :value

Result

• ::DataFrame : the wide-format dataframe

Page 172: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

6.23. DATAFRAMES.WRITETABLE 167

Examples

[] wide = DataFrame(id = 1:12, a = repeat([1:3;], inner = [4]), b = re-peat([1:4;], inner = [3]), c = randn(12), d = randn(12))

long = stack(wide) wide0 = unstack(long) wide1 = unstack(long, :variable,:value) wide2 = unstack(long, :id, :variable, :value)

Note that there are some differences between the widened results above.

6.23 DataFrames.writetable

DataFrames.writetable — Method.

Write data to a tabular-file format (CSV, TSV, . . . )

[] writetable(filename, df, [keyword options])

Arguments

• filename::AbstractString : the filename to be created

• df::AbstractDataFrame : the AbstractDataFrame to be written

Keyword Arguments

• separator::Char – The separator character that you would like to use.Defaults to the output of getseparator(filename), which uses commasfor files that end in .csv, tabs for files that end in .tsv and a single spacefor files that end in .wsv.

• quotemark::Char – The character used to delimit string fields. Defaultsto ".

• header::Bool – Should the file contain a header that specifies the columnnames from df. Defaults to true.

• nastring::AbstractString – What to write in place of missing data.Defaults to "NA".

Result

• ::DataFrame

Examples

[] df = DataFrame(A = 1:10) writetable(”output.csv”, df) writetable(”output.dat”,df, separator = ’,’, header = false) writetable(”output.dat”, df, quotemark = ”,separator = ’,’) writetable(”output.dat”, df, header = false)

Page 173: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

168 CHAPTER 6. DATAFRAMES

6.24 StatsBase.describe

StatsBase.describe — Method.Summarize the columns of an AbstractDataFrame[] describe(df::AbstractDataFrame) describe(io, df::AbstractDataFrame)Arguments

• df : the AbstractDataFrame

• io : optional output descriptor

Result

• nothing

DetailsIf the column’s base type derives from Number, compute the minimum, first

quantile, median, mean, third quantile, and maximum. NA’s are filtered andreported separately.

For boolean columns, report trues, falses, and NAs.For other types, show column characteristics and number of NAs.Examples[] df = DataFrame(i = 1:10, x = rand(10), y = rand([”a”, ”b”, ”c”], 10))

describe(df)

6.25 StatsBase.model response

StatsBase.model response — Method.

StatsBase.model_response(mf::ModelFrame)

Extract the response column, if present. DataVector or PooledDataVectorcolumns are converted to Arrays

Page 174: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 7

EzXML

7.1 EzXML.AttributeNode

EzXML.AttributeNode — Method.

AttributeNode(name, value)

Create an attribute node with name and value.

7.2 EzXML.CDataNode

EzXML.CDataNode — Method.

CDataNode(content)

Create a CDATA node with content.

7.3 EzXML.CommentNode

EzXML.CommentNode — Method.

CommentNode(content)

Create a comment node with content.

7.4 EzXML.DTDNode

EzXML.DTDNode — Method.

DTDNode(name, [systemID, [externalID]])

Create a DTD node with name, systemID, and externalID.

169

Page 175: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

170 CHAPTER 7. EZXML

7.5 EzXML.ElementNode

EzXML.ElementNode — Method.

ElementNode(name)

Create an element node with name.

7.6 EzXML.HTMLDocument

EzXML.HTMLDocument — Function.

HTMLDocument(uri=nothing, externalID=nothing)

Create an HTML document.

7.7 EzXML.HTMLDocumentNode

EzXML.HTMLDocumentNode — Method.

HTMLDocumentNode(uri, externalID)

Create an HTML document node.uri and externalID are either a string or nothing.

7.8 EzXML.TextNode

EzXML.TextNode — Method.

TextNode(content)

Create a text node with content.

7.9 EzXML.XMLDocument

EzXML.XMLDocument — Function.

XMLDocument(version="1.0")

Create an XML document.

7.10 EzXML.XMLDocumentNode

EzXML.XMLDocumentNode — Method.

XMLDocumentNode(version)

Create an XML document node with version.

Page 176: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

7.11. EZXML.ADDELEMENT! 171

7.11 EzXML.addelement!

EzXML.addelement! — Method.

addelement!(parent::Node, name::AbstractString, content::AbstractString)

Add a new child element of name with content to parent and return thenew child element.

7.12 EzXML.addelement!

EzXML.addelement! — Method.

addelement!(parent::Node, name::AbstractString)

Add a new child element of name with no content to parent and return thenew child element.

7.13 EzXML.attributes

EzXML.attributes — Method.

attributes(node::Node)

Create a vector of attributes.

7.14 EzXML.content

EzXML.content — Method.

content(node::Node)

Return the node content of node.

7.15 EzXML.content

EzXML.content — Method.

content(reader::StreamReader)

Return the content of the current node of reader.

7.16 EzXML.countattributes

EzXML.countattributes — Method.

countattributes(elem::Node)

Count the number of attributes of elem.

Page 177: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

172 CHAPTER 7. EZXML

7.17 EzXML.countelements

EzXML.countelements — Method.

countelements(parent::Node)

Count the number of child elements of parent.

7.18 EzXML.countnodes

EzXML.countnodes — Method.

countnodes(parent::Node)

Count the number of child nodes of parent.

7.19 EzXML.depth

EzXML.depth — Method.

depth(reader::StreamReader)

Return the depth of the current node of reader.

7.20 EzXML.document

EzXML.document — Method.

document(node::Node)

Return the document of node.

7.21 EzXML.dtd

EzXML.dtd — Method.

dtd(doc::Document)

Return the DTD node of doc.

7.22 EzXML.eachattribute

EzXML.eachattribute — Method.

eachattribute(node::Node)

Create an iterator of attributes.

Page 178: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

7.23. EZXML.EACHELEMENT 173

7.23 EzXML.eachelement

EzXML.eachelement — Function.

eachelement(node::Node, [backward=false])

Create an iterator of child elements.

7.24 EzXML.eachnode

EzXML.eachnode — Function.

eachnode(node::Node, [backward=false])

Create an iterator of child nodes.

7.25 EzXML.elements

EzXML.elements — Function.

elements(node::Node, [backward=false])

Create a vector of child elements.

7.26 EzXML.expandtree

EzXML.expandtree — Method.

expandtree(reader::StreamReader)

Expand the current node of reader into a full subtree that will be availableuntil the next read of node.

7.27 EzXML.externalID

EzXML.externalID — Method.

externalID(node::Node)

Return the external ID of node.

7.28 EzXML.firstelement

EzXML.firstelement — Method.

firstelement(node::Node)

Return the first child element of node.

Page 179: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

174 CHAPTER 7. EZXML

7.29 EzXML.firstnode

EzXML.firstnode — Method.

firstnode(node::Node)

Return the first child node of node.

7.30 EzXML.hasdocument

EzXML.hasdocument — Method.

hasdocument(node::Node)

Return if node belongs to a document.

7.31 EzXML.hasdtd

EzXML.hasdtd — Method.

hasdtd(doc::Document)

Return if doc has a DTD node.

7.32 EzXML.haselement

EzXML.haselement — Method.

haselement(node::Node)

Return if node has a child element.

7.33 EzXML.hasnextelement

EzXML.hasnextelement — Method.

hasnextelement(node::Node)

Return if node has a next node.

7.34 EzXML.hasnextnode

EzXML.hasnextnode — Method.

hasnextnode(node::Node)

Return if node has a next node.

Page 180: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

7.35. EZXML.HASNODE 175

7.35 EzXML.hasnode

EzXML.hasnode — Method.

hasnode(node::Node)

Return if node has a child node.

7.36 EzXML.hasparentelement

EzXML.hasparentelement — Method.

hasparentelement(node::Node)

Return if node has a parent node.

7.37 EzXML.hasparentnode

EzXML.hasparentnode — Method.

hasparentnode(node::Node)

Return if node has a parent node.

7.38 EzXML.hasprevelement

EzXML.hasprevelement — Method.

hasprevelement(node::Node)

Return if node has a previous node.

7.39 EzXML.hasprevnode

EzXML.hasprevnode — Method.

hasprevnode(node::Node)

Return if node has a previous node.

7.40 EzXML.hasroot

EzXML.hasroot — Method.

hasroot(doc::Document)

Return if doc has a root element.

Page 181: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

176 CHAPTER 7. EZXML

7.41 EzXML.isattribute

EzXML.isattribute — Method.

isattribute(node::Node)

Return if node is an attribute node.

7.42 EzXML.iscdata

EzXML.iscdata — Method.

iscdata(node::Node)

Return if node is a CDATA node.

7.43 EzXML.iscomment

EzXML.iscomment — Method.

iscomment(node::Node)

Return if node is a comment node.

7.44 EzXML.isdtd

EzXML.isdtd — Method.

isdtd(node::Node)

Return if node is a DTD node.

7.45 EzXML.iselement

EzXML.iselement — Method.

iselement(node::Node)

Return if node is an element node.

7.46 EzXML.lastelement

EzXML.lastelement — Method.

lastelement(node::Node)

Return the last child element of node.

Page 182: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

7.47. EZXML.LASTNODE 177

7.47 EzXML.lastnode

EzXML.lastnode — Method.

lastnode(node::Node)

Return the last child node of node.

7.48 EzXML.link!

EzXML.link! — Method.

link!(parent::Node, child::Node)

Link child at the end of children of parent.

7.49 EzXML.linknext!

EzXML.linknext! — Method.

linknext!(target::Node, node::Node)

Link node as the next sibling of target.

7.50 EzXML.linkprev!

EzXML.linkprev! — Method.

linkprev!(target::Node, node::Node)

Link node as the prev sibling of target.

7.51 EzXML.name

EzXML.name — Method.

name(node::Node)

Return the node name of node.

7.52 EzXML.name

EzXML.name — Method.

name(reader::StreamReader)

Return the name of the current node of reader.

Page 183: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

178 CHAPTER 7. EZXML

7.53 EzXML.namespace

EzXML.namespace — Method.

namespace(node::Node)

Return the namespace associated with node.

7.54 EzXML.namespace

EzXML.namespace — Method.

namespace(reader::StreamReader)

Return the namespace of the current node of reader.

7.55 EzXML.namespaces

EzXML.namespaces — Method.

namespaces(node::Node)

Create a vector of namespaces applying to node.

7.56 EzXML.nextelement

EzXML.nextelement — Method.

nextelement(node::Node)

Return the next element of node.

7.57 EzXML.nextnode

EzXML.nextnode — Method.

nextnode(node::Node)

Return the next node of node.

7.58 EzXML.nodepath

EzXML.nodepath — Method.

nodepath(node::Node)

Return the path of node.

Page 184: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

7.59. EZXML.NODES 179

7.59 EzXML.nodes

EzXML.nodes — Function.

nodes(node::Node, [backward=false])

Create a vector of child nodes.

7.60 EzXML.nodetype

EzXML.nodetype — Method.

nodetype(node::Node)

Return the type of node as an integer.

7.61 EzXML.nodetype

EzXML.nodetype — Method.

nodetype(reader::StreamReader)

Return the type of the current node of reader.

7.62 EzXML.parentelement

EzXML.parentelement — Method.

parentelement(node::Node)

Return the parent element of node.

7.63 EzXML.parentnode

EzXML.parentnode — Method.

parentnode(node::Node)

Return the parent of node.

7.64 EzXML.parsehtml

EzXML.parsehtml — Method.

parsehtml(htmlstring)

Parse htmlstring and create an HTML document.

Page 185: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

180 CHAPTER 7. EZXML

7.65 EzXML.parsexml

EzXML.parsexml — Method.

parsexml(xmlstring)

Parse xmlstring and create an XML document.

7.66 EzXML.prettyprint

EzXML.prettyprint — Method.

prettyprint([io], doc::Document)

Print doc with formatting.

7.67 EzXML.prettyprint

EzXML.prettyprint — Method.

prettyprint([io], node::Node)

Print node with formatting.

7.68 EzXML.prevelement

EzXML.prevelement — Method.

prevelement(node::Node)

Return the previous element of node.

7.69 EzXML.prevnode

EzXML.prevnode — Method.

prevnode(node::Node)

Return the previous node of node.

7.70 EzXML.readdtd

EzXML.readdtd — Method.

readdtd(filename::AbstractString)

Read filename and create a DTD node.

Page 186: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

7.71. EZXML.READHTML 181

7.71 EzXML.readhtml

EzXML.readhtml — Method.

readhtml(filename)

Read filename and create an HTML document.

7.72 EzXML.readhtml

EzXML.readhtml — Method.

readhtml(input::IO)

Read input and create an HTML document.

7.73 EzXML.readxml

EzXML.readxml — Method.

readxml(filename)

Read filename and create an XML document.

7.74 EzXML.readxml

EzXML.readxml — Method.

readxml(input::IO)

Read input and create an XML document.

7.75 EzXML.root

EzXML.root — Method.

root(doc::Document)

Return the root element of doc.

7.76 EzXML.setcontent!

EzXML.setcontent! — Method.

setcontent!(node::Node, content::AbstractString)

Replace the content of node.

Page 187: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

182 CHAPTER 7. EZXML

7.77 EzXML.setdtd!

EzXML.setdtd! — Method.

setdtd!(doc::Document, node::Node)

Set the DTD node of doc to node and return the DTD node.

7.78 EzXML.setname!

EzXML.setname! — Method.

setname!(node::Node, name::AbstractString)

Set the name of node.

7.79 EzXML.setroot!

EzXML.setroot! — Method.

setroot!(doc::Document, node::Node)

Set the root element of doc to node and return the root element.

7.80 EzXML.systemID

EzXML.systemID — Method.

systemID(node::Node)

Return the system ID of node.

7.81 EzXML.unlink!

EzXML.unlink! — Method.

unlink!(node::Ndoe)

Unlink node from its context.

7.82 EzXML.validate

EzXML.validate — Method.

validate(doc::Document, [dtd::Node])

Validate doc against dtd and return the validation log.The validation log is empty if and only if doc is valid. The DTD node in

doc will be used if dtd is not passed.

Page 188: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 8

ImageCore

8.1 ImageCore.assert timedim last

ImageCore.assert timedim last — Method.

assert_timedim_last(img)

Throw an error if the image has a time dimension that is not the last di-mension.

8.2 ImageCore.assert xfirst

ImageCore.assert xfirst — Method.

assert_xfirst(img)

Throw an error if the first spatial dimension is not :x.

8.3 ImageCore.assert yfirst

ImageCore.assert yfirst — Method.

assert_yfirst(img)

Throw an error if the first spatial dimension is not :y.

8.4 ImageCore.channelview

ImageCore.channelview — Method.

channelview(A)

183

Page 189: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

184 CHAPTER 8. IMAGECORE

returns a view of A, splitting out (if necessary) the color channels of A into anew first dimension. This is almost identical to ChannelView(A), except that ifA is a ColorView, it will simply return the parent of A, or will use reinterpret

when appropriate. Consequently, the output may not be a ChannelView array.

8.5 ImageCore.clamp01

ImageCore.clamp01 — Method.

clamp01(x) -> y

Produce a value y that lies between 0 and 1, and equal to x when x is alreadyin this range. Equivalent to clamp(x, 0, 1) for numeric values. For colors,this function is applied to each color channel separately.

See also: clamp01nan.

8.6 ImageCore.clamp01nan

ImageCore.clamp01nan — Method.

clamp01nan(x) -> y

Similar to clamp01, except that any NaN values are changed to 0.See also: clamp01.

8.7 ImageCore.colorsigned

ImageCore.colorsigned — Method.

colorsigned()

colorsigned(colorneg, colorpos) -> f

colorsigned(colorneg, colorcenter, colorpos) -> f

Define a function that maps negative values (in the range [-1,0]) to the linearcolormap between colorneg and colorcenter, and positive values (in the range[0,1]) to the linear colormap between colorcenter and colorpos.

The default colors are:

• colorcenter: white

• colorneg: green1

• colorpos: magenta

See also: scalesigned.

Page 190: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

8.8. IMAGECORE.COLORVIEW 185

8.8 ImageCore.colorview

ImageCore.colorview — Method.

colorview(C, A)

returns a view of the numeric array A, interpreting successive elements of A asif they were channels of Colorant C. This is almost identical to ColorView{C}(A),except that if A is a ChannelView, it will simply return the parent of A, oruse reinterpret when appropriate. Consequently, the output may not be aColorView array.

Example[] A = rand(3, 10, 10) img = colorview(RGB, A)

8.9 ImageCore.colorview

ImageCore.colorview — Method.

colorview(C, gray1, gray2, ...) -> imgC

Combine numeric/grayscale images gray1, gray2, etc., into the separatecolor channels of an array imgC with element type C<:Colorant.

As a convenience, the constant zeroarray fills in an array of matched sizewith all zeros.

Example[] imgC = colorview(RGB, r, zeroarray, b)creates an image with r in the red chanel, b in the blue channel, and nothing

in the green channel.See also: StackedView.

8.10 ImageCore.coords spatial

ImageCore.coords spatial — Method.coords spatial(img)Return a tuple listing the spatial dimensions of img.Note that a better strategy may be to use ImagesAxes and take slices along

the time axis.

8.11 ImageCore.float32

ImageCore.float32 — Function.

float32.(img)

converts the raw storage type of img to Float32, without changing the colorspace.

Page 191: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

186 CHAPTER 8. IMAGECORE

8.12 ImageCore.float64

ImageCore.float64 — Function.

float64.(img)

converts the raw storage type of img to Float64, without changing the colorspace.

8.13 ImageCore.indices spatial

ImageCore.indices spatial — Method.

indices_spatial(img)

Return a tuple with the indices of the spatial dimensions of the image. De-faults to the same as indices, but using ImagesAxes you can mark some axesas being non-spatial.

8.14 ImageCore.isxfirst

ImageCore.isxfirst — Method.

isxfirst(img)

Return true if the first spatial dimension is :x. Supported only if you useImagesAxes.

See also: isyfirst, assert xfirst.

8.15 ImageCore.isyfirst

ImageCore.isyfirst — Method.

isyfirst(img)

Return true if the first spatial dimension is :y. Supported only if you useImagesAxes.

See also: isxfirst, assert yfirst.

8.16 ImageCore.n0f16

ImageCore.n0f16 — Function.

n0f16.(img)

converts the raw storage type of img to N0f16, without changing the colorspace.

Page 192: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

8.17. IMAGECORE.N0F8 187

8.17 ImageCore.n0f8

ImageCore.n0f8 — Function.

n0f8.(img)

converts the raw storage type of img to N0f8, without changing the colorspace.

8.18 ImageCore.n2f14

ImageCore.n2f14 — Function.

n2f14.(img)

converts the raw storage type of img to N2f14, without changing the colorspace.

8.19 ImageCore.n4f12

ImageCore.n4f12 — Function.

n4f12.(img)

converts the raw storage type of img to N4f12, without changing the colorspace.

8.20 ImageCore.n6f10

ImageCore.n6f10 — Function.

n6f10.(img)

converts the raw storage type of img to N6f10, without changing the colorspace.

8.21 ImageCore.nimages

ImageCore.nimages — Method.

nimages(img)

Return the number of time-points in the image array. Defaults to

1. Use ImagesAxes if you want to use an explicit time dimension.

Page 193: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

188 CHAPTER 8. IMAGECORE

8.22 ImageCore.normedview

ImageCore.normedview — Method.

normedview([T], img::AbstractArray{Unsigned})

returns a “view” of img where the values are interpreted in terms of Normednumber types. For example, if img is an Array{UInt8}, the view will act like anArray{N0f8}. Supply T if the element type of img is UInt16, to specify whetheryou want a N6f10, N4f12, N2f14, or N0f16 result.

8.23 ImageCore.permuteddimsview

ImageCore.permuteddimsview — Method.

permuteddimsview(A, perm)

returns a “view” of A with its dimensions permuted as specified by perm.This is like permutedims, except that it produces a view rather than a copy ofA; consequently, any manipulations you make to the output will be mirrored inA. Compared to the copy, the view is much faster to create, but generally slowerto use.

8.24 ImageCore.pixelspacing

ImageCore.pixelspacing — Method.

pixelspacing(img) -> (sx, sy, ...)

Return a tuple representing the separation between adjacent pixels alongeach axis of the image. Defaults to (1,1,. . . ). Use ImagesAxes for images withanisotropic spacing or to encode the spacing using physical units.

8.25 ImageCore.rawview

ImageCore.rawview — Method.

rawview(img::AbstractArray{FixedPoint})

returns a “view” of img where the values are interpreted in terms of theirraw underlying storage. For example, if img is an Array{N0f8}, the view willact like an Array{UInt8}.

Page 194: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

8.26. IMAGECORE.SCALEMINMAX 189

8.26 ImageCore.scaleminmax

ImageCore.scaleminmax — Method.

scaleminmax(min, max) -> f

scaleminmax(T, min, max) -> f

Return a function f which maps values less than or equal to min to 0, valuesgreater than or equal to max to 1, and uses a linear scale in between. min andmax should be real values.

Optionally specify the return type T. If T is a colorant (e.g., RGB), thenscaling is applied to each color channel.

ExamplesExample 1[] julia¿ f = scaleminmax(-10, 10) (::9) (generic function with 1 method)julia¿ f(10) 1.0julia¿ f(-10) 0.0julia¿ f(5) 0.75Example 2[] julia¿ c = RGB(255.0,128.0,0.0) RGB{Float64}(255.0,128.0,0.0)julia¿ f = scaleminmax(RGB, 0, 255) (::13) (generic function with 1 method)julia¿ f(c) RGB{Float64}(1.0,0.5019607843137255,0.0)See also: takemap.

8.27 ImageCore.scalesigned

ImageCore.scalesigned — Method.

scalesigned(maxabs) -> f

Return a function f which scales values in the range [-maxabs, maxabs]

(clamping values that lie outside this range) to the range [-1, 1].See also: colorsigned.

8.28 ImageCore.scalesigned

ImageCore.scalesigned — Method.

scalesigned(min, center, max) -> f

Return a function f which scales values in the range [min, center] to[-1,0] and [center,max] to [0,1]. Values smaller than min/max get clampedto min/max, respectively.

See also: colorsigned.

Page 195: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

190 CHAPTER 8. IMAGECORE

8.29 ImageCore.sdims

ImageCore.sdims — Method.

sdims(img)

Return the number of spatial dimensions in the image. Defaults to the sameas ndims, but with ImagesAxes you can specify that some axes correspond toother quantities (e.g., time) and thus not included by sdims.

8.30 ImageCore.size spatial

ImageCore.size spatial — Method.

size_spatial(img)

Return a tuple listing the sizes of the spatial dimensions of the image. De-faults to the same as size, but using ImagesAxes you can mark some axes asbeing non-spatial.

8.31 ImageCore.spacedirections

ImageCore.spacedirections — Method.

spacedirections(img) -> (axis1, axis2, ...)

Return a tuple-of-tuples, each axis[i] representing the displacement vectorbetween adjacent pixels along spatial axis i of the image array, relative to someexternal coordinate system (“physical coordinates”).

By default this is computed from pixelspacing, but you can set this man-ually using ImagesMeta.

8.32 ImageCore.takemap

ImageCore.takemap — Function.

takemap(f, A) -> fnew

takemap(f, T, A) -> fnew

Given a value-mapping function f and an array A, return a “concrete” map-ping function fnew. When applied to elements of A, fnew should return validvalues for storage or display, for example in the range from 0 to 1 (for grayscale)or valid colorants. fnew may be adapted to the actual values present in A, andmay not produce valid values for any inputs not in A.

Optionally one can specify the output type T that fnew should produce.Example:[] julia¿ A = [0, 1, 1000];julia¿ f = takemap(scaleminmax, A) (::7) (generic function with 1 method)julia¿ f.(A) 3-element Array{Float64,1}: 0.0 0.001 1.0

Page 196: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 9

SpecialFunctions

9.1 SpecialFunctions.airyai

SpecialFunctions.airyai — Function.

airyai(x)

Airy function of the first kind Ai(x).

9.2 SpecialFunctions.airyaiprime

SpecialFunctions.airyaiprime — Function.

airyaiprime(x)

Derivative of the Airy function of the first kind Ai′(x).

9.3 SpecialFunctions.airybi

SpecialFunctions.airybi — Function.

airybi(x)

Airy function of the second kind Bi(x).

9.4 SpecialFunctions.airybiprime

SpecialFunctions.airybiprime — Function.

airybiprime(x)

Derivative of the Airy function of the second kind Bi′(x).

191

Page 197: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

192 CHAPTER 9. SPECIALFUNCTIONS

9.5 SpecialFunctions.besselh

SpecialFunctions.besselh — Function.

besselh(nu, [k=1,] x)

Bessel function of the third kind of order nu (the Hankel function). k iseither 1 or 2, selecting hankelh1 or hankelh2, respectively. k defaults to 1 if itis omitted. (See also besselhx for an exponentially scaled variant.)

9.6 SpecialFunctions.besselhx

SpecialFunctions.besselhx — Function.

besselhx(nu, [k=1,] z)

Compute the scaled Hankel function exp(iz)H(k)(z), where k is 1 or 2,H(k)(z) is besselh(nu, k, z), and is − for k = 1 and + for k = 2. k

defaults to 1 if it is omitted.The reason for this function is that H(k)(z) is asymptotically proportional to

exp(iz)/√z for large |z|, and so the besselh function is susceptible to overflow

or underflow when z has a large imaginary part. The besselhx function cancelsthis exponential factor (analytically), so it avoids these problems.

9.7 SpecialFunctions.besseli

SpecialFunctions.besseli — Method.

besseli(nu, x)

Modified Bessel function of the first kind of order nu, Iν(x).

9.8 SpecialFunctions.besselix

SpecialFunctions.besselix — Method.

besselix(nu, x)

Scaled modified Bessel function of the first kind of order nu, Iν(x)e−|Re(x)|.

9.9 SpecialFunctions.besselj

SpecialFunctions.besselj — Method.

besselj(nu, x)

Bessel function of the first kind of order nu, Jν(x).

Page 198: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

9.10. SPECIALFUNCTIONS.BESSELJ0 193

9.10 SpecialFunctions.besselj0

SpecialFunctions.besselj0 — Method.

besselj0(x)

Bessel function of the first kind of order 0, J0(x).

9.11 SpecialFunctions.besselj1

SpecialFunctions.besselj1 — Method.

besselj1(x)

Bessel function of the first kind of order 1, J1(x).

9.12 SpecialFunctions.besseljx

SpecialFunctions.besseljx — Method.

besseljx(nu, x)

Scaled Bessel function of the first kind of order nu, Jν(x)e−| Im(x)|.

9.13 SpecialFunctions.besselk

SpecialFunctions.besselk — Method.

besselk(nu, x)

Modified Bessel function of the second kind of order nu, Kν(x).

9.14 SpecialFunctions.besselkx

SpecialFunctions.besselkx — Method.

besselkx(nu, x)

Scaled modified Bessel function of the second kind of order nu, Kν(x)ex.

9.15 SpecialFunctions.bessely

SpecialFunctions.bessely — Method.

bessely(nu, x)

Bessel function of the second kind of order nu, Yν(x).

Page 199: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

194 CHAPTER 9. SPECIALFUNCTIONS

9.16 SpecialFunctions.bessely0

SpecialFunctions.bessely0 — Method.

bessely0(x)

Bessel function of the second kind of order 0, Y0(x).

9.17 SpecialFunctions.bessely1

SpecialFunctions.bessely1 — Method.

bessely1(x)

Bessel function of the second kind of order 1, Y1(x).

9.18 SpecialFunctions.besselyx

SpecialFunctions.besselyx — Method.

besselyx(nu, x)

Scaled Bessel function of the second kind of order nu, Yν(x)e−| Im(x)|.

9.19 SpecialFunctions.dawson

SpecialFunctions.dawson — Function.

dawson(x)

Compute the Dawson function (scaled imaginary error function) of x, defined

by√π2 e−x2

erfi(x).

9.20 SpecialFunctions.digamma

SpecialFunctions.digamma — Method.

digamma(x)

Compute the digamma function of x (the logarithmic derivative of gamma(x)).

9.21 SpecialFunctions.erf

SpecialFunctions.erf — Function.

erf(x)

Compute the error function of x, defined by 2√π

∫ x0e−t

2

dt for arbitrary com-

plex x.

Page 200: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

9.22. SPECIALFUNCTIONS.ERFC 195

9.22 SpecialFunctions.erfc

SpecialFunctions.erfc — Function.

erfc(x)

Compute the complementary error function of x, defined by 1− erf(x).

9.23 SpecialFunctions.erfcinv

SpecialFunctions.erfcinv — Method.

erfcinv(x)

Compute the inverse error complementary function of a real x, defined byerfc(erfcinv(x)) = x.

9.24 SpecialFunctions.erfcx

SpecialFunctions.erfcx — Function.

erfcx(x)

Compute the scaled complementary error function of x, defined by ex2

erfc(x).Note also that erfcx(−ix) computes the Faddeeva function w(x).

9.25 SpecialFunctions.erfi

SpecialFunctions.erfi — Function.

erfi(x)

Compute the imaginary error function of x, defined by −i erf(ix).

9.26 SpecialFunctions.eta

SpecialFunctions.eta — Method.

eta(x)

Dirichlet eta function η(s) =∑∞n=1(−1)n−1/ns.

9.27 SpecialFunctions.hankelh1

SpecialFunctions.hankelh1 — Method.

hankelh1(nu, x)

Bessel function of the third kind of order nu, H(1)ν (x).

Page 201: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

196 CHAPTER 9. SPECIALFUNCTIONS

9.28 SpecialFunctions.hankelh1x

SpecialFunctions.hankelh1x — Method.

hankelh1x(nu, x)

Scaled Bessel function of the third kind of order nu, H(1)ν (x)e−xi.

9.29 SpecialFunctions.hankelh2

SpecialFunctions.hankelh2 — Method.

hankelh2(nu, x)

Bessel function of the third kind of order nu, H(2)ν (x).

9.30 SpecialFunctions.hankelh2x

SpecialFunctions.hankelh2x — Method.

hankelh2x(nu, x)

Scaled Bessel function of the third kind of order nu, H(2)ν (x)exi.

9.31 SpecialFunctions.invdigamma

SpecialFunctions.invdigamma — Method.

invdigamma(x)

Compute the inverse digamma function of x.

9.32 SpecialFunctions.polygamma

SpecialFunctions.polygamma — Method.

polygamma(m, x)

Compute the polygamma function of order m of argument x (the (m+1)thderivative of the logarithm of gamma(x))

9.33 SpecialFunctions.trigamma

SpecialFunctions.trigamma — Method.

trigamma(x)

Compute the trigamma function of x (the logarithmic second derivative ofgamma(x)).

Page 202: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

9.34. SPECIALFUNCTIONS.ZETA 197

9.34 SpecialFunctions.zeta

SpecialFunctions.zeta — Method.

zeta(s, z)

Generalized zeta function ζ(s, z), defined by the sum∑∞k=0((k + z)2)−s/2,

where any term with k + z = 0 is excluded. For <z > 0, this definition isequivalent to the Hurwitz zeta function

∑∞k=0(k+ z)−s. For z = 1, it yields the

Riemann zeta function ζ(s).

9.35 SpecialFunctions.zeta

SpecialFunctions.zeta — Method.

zeta(s)

Riemann zeta function ζ(s).

Page 203: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 10

Knet

10.1 Knet.bilinear

Knet.bilinear — Method.Bilinear interpolation filter weights; used for initializing deconvolution layers.Adapted from https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/surgery.py#L33Arguments:T : Data Typefw: Width upscale factorfh: Height upscale factorIN: Number of input filtersON: Number of output filtersExample usage:w = bilinear(Float32,2,2,128,128)

10.2 Knet.conv4

Knet.conv4 — Method.

conv4(w, x; kwargs...)

Execute convolutions or cross-correlations using filters specified with w overtensor x.

Currently KnetArray{Float32/64,4/5} and Array{Float32/64,4} are sup-ported as w and x. If w has dimensions (W1,W2,...,I,O) and x has dimensions(X1,X2,...,I,N), the result y will have dimensions (Y1,Y2,...,O,N) where

Yi=1+floor((Xi+2*padding[i]-Wi)/stride[i])

Here I is the number of input channels, O is the number of output channels,N is the number of instances, and Wi,Xi,Yi are spatial dimensions. padding

and stride are keyword arguments that can be specified as a single number

198

Page 204: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

10.3. KNET.DECONV4 199

(in which case they apply to all dimensions), or an array/tuple with entries foreach spatial dimension.

Keywords

• padding=0: the number of extra zeros implicitly concatenated at the startand at the end of each dimension.

• stride=1: the number of elements to slide to reach the next filteringwindow.

• upscale=1: upscale factor for each dimension.

• mode=0: 0 for convolution and 1 for cross-correlation.

• alpha=1: can be used to scale the result.

• algo=0: specifies which convolution algorithm shoud be used to computethe results. See the CUDNN User Guide for details.

• workSpace=C NULL: data pointer to GPU memory to a workspace neededto able to execute the specified algorithm.

• workSpaceSizeInBytes=0: the size in bytes of the provided workSpace.Default=0.

• handle: handle to a previously created cuDNN context. Defaults to aKnet allocated handle.

10.3 Knet.deconv4

Knet.deconv4 — Method.

Deconvolution; reverse of convolution.

10.4 Knet.gaussian

Knet.gaussian — Method.

gaussian(a...; mean=0.0, std=0.01)

Return a Gaussian array with a given mean and standard deviation. The a

arguments are passed to randn.

Page 205: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

200 CHAPTER 10. KNET

10.5 Knet.gpu

Knet.gpu — Function.gpu() returns the id of the active GPU device or -1 if none are active.gpu(true) resets all GPU devices and activates the one with the most avail-

able memory.gpu(false) resets and deactivates all GPU devices.gpu(d::Int) activates the GPU device d if 0 <= d < gpuCount(), other-

wise deactivates devices.gpu(true/false) resets all devices. If there are any allocated KnetArrays

their pointers will be left dangling. Thus gpu(true/false) should only be usedduring startup. If you want to suspend GPU use temporarily, use gpu(-1).

gpu(d::Int) does not reset the devices. You can select a previous deviceand find allocated memory preserved. However trying to operate on arrays ofan inactive device will result in error.

10.6 Knet.invx

Knet.invx — Function.invx(x) = (1./x)

10.7 Knet.logp

Knet.logp — Method.

logp(x,[dims])

Treat entries in x as as unnormalized log probabilities and return normalizedlog probabilities.

dims is an optional argument, if not specified the normalization is over thewhole x, otherwise the normalization is performed over the given dimensions.In particular, if x is a matrix, dims=1 normalizes columns of x and dims=2

normalizes rows of x.

10.8 Knet.logsumexp

Knet.logsumexp — Method.

logsumexp(x,[dims])

Compute log(sum(exp(x),dims)) in a numerically stable manner.dims is an optional argument, if not specified the summation is over the

whole x, otherwise the summation is performed over the given dimensions. Inparticular if x is a matrix, dims=1 sums columns of x and dims=2 sums rows ofx.

Page 206: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

10.9. KNET.MAT 201

10.9 Knet.mat

Knet.mat — Method.

mat(x)

Reshape x into a two-dimensional matrix.This is typically used when turning the output of a 4-D convolution re-

sult into a 2-D input for a fully connected layer. For 1-D inputs returnsreshape(x, (length(x),1)). For inputs with more than two dimensions ofsize (X1,X2,...,XD), returns

reshape(x, (X1*X2*...*X[D-1],XD))

10.10 Knet.pool

Knet.pool — Method.

pool(x; kwargs...)

Compute pooling of input values (i.e., the maximum or average of severaladjacent values) to produce an output with smaller height and/or width.

Currently 4 or 5 dimensional KnetArrays with Float32 or Float64 entriesare supported. If x has dimensions (X1,X2,...,I,N), the result y will havedimensions (Y1,Y2,...,I,N) where

Yi=1+floor((Xi+2*padding[i]-window[i])/stride[i])

Here I is the number of input channels, N is the number of instances, andXi,Yi are spatial dimensions. window, padding and stride are keyword argu-ments that can be specified as a single number (in which case they apply to alldimensions), or an array/tuple with entries for each spatial dimension.

Keywords:

• window=2: the pooling window size for each dimension.

• padding=0: the number of extra zeros implicitly concatenated at the startand at the end of each dimension.

• stride=window: the number of elements to slide to reach the next poolingwindow.

• mode=0: 0 for max, 1 for average including padded values, 2 for averageexcluding padded values.

• maxpoolingNanOpt=0: Nan numbers are not propagated if 0, they arepropagated if 1.

• alpha=1: can be used to scale the result.

• handle: Handle to a previously created cuDNN context. Defaults to aKnet allocated handle.

Page 207: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

202 CHAPTER 10. KNET

10.11 Knet.relu

Knet.relu — Function.relu(x) = max(0,x)

10.12 Knet.sigm

Knet.sigm — Function.sigm(x) = (1./(1+exp(-x)))

10.13 Knet.unpool

Knet.unpool — Method.Unpooling; reverse of pooling.

x == pool(unpool(x;o...); o...)

10.14 Knet.update!

Knet.update! — Method.

update!(weights, gradients, params)

update!(weights, gradients; lr=0.001)

Update the weights using their gradients and the optimization algorithmparameters specified by params. The 2-arg version defaults to the Sgd algorithmwith learning rate lr. The weights and possibly params are modified in-place.

weights can be an individual numeric array or a collection of arrays repre-sented by an iterator or dictionary. In the individual case, gradients shouldbe a similar numeric array of size(weights) and params should be a singleobject. In the collection case, each individual weight array should have a cor-responding params object. This way different weight arrays can have their ownoptimization state, different learning rates, or even different optimization algo-rithms running in parallel. In the iterator case, gradients and params shouldbe iterators of the same length as weights with corresponding elements. In thedictionary case, gradients and params should be dictionaries with the samekeys as weights.

Individual optimization parameters can be one of the following types:

• Sgd(;lr=0.001)

• Momentum(;lr=0.001, gamma=0.9)

• Rmsprop(;lr=0.001, rho=0.9, eps=1e-6)

• Adagrad(;lr=0.1, eps=1e-6)

Page 208: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

10.15. KNET.XAVIER 203

• Adadelta(;lr=0.01, rho=0.9, eps=1e-6)

• Adam(;lr=0.001, beta1=0.9, beta2=0.999, eps=1e-8)

Example:

w = rand(d) # an individual weight array

g = lossgradient(w) # gradient g has the same shape as w

update!(w, g) # update w in-place with Sgd()

update!(w, g; lr=0.1) # update w in-place with Sgd(lr=0.1)

update!(w, g, Sgd(lr=0.1)) # update w in-place with Sgd(lr=0.1)

w = (rand(d1), rand(d2)) # a tuple of weight arrays

g = lossgradient2(w) # g will also be a tuple

p = (Adam(), Sgd()) # p has params for each w[i]

update!(w, g, p) # update each w[i] in-place with g[i],p[i]

w = Any[rand(d1), rand(d2)] # any iterator can be used

g = lossgradient3(w) # g will be similar to w

p = Any[Adam(), Sgd()] # p should be an iterator of same length

update!(w, g, p) # update each w[i] in-place with g[i],p[i]

w = Dict(:a => rand(d1), :b => rand(d2)) # dictionaries can be used

g = lossgradient4(w)

p = Dict(:a => Adam(), :b => Sgd())

update!(w, g, p)

10.15 Knet.xavier

Knet.xavier — Method.

xavier(a...)

Xavier initialization. The a arguments are passed to rand. See (Glorotand Bengio 2010) for a description. Caffe implements this slightly differently.Lasagne calls it GlorotUniform.

Page 209: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 11

Combinatorics

11.1 Base.combinations

Base.combinations — Method.

Generate all combinations of n elements from an indexable object. Becausethe number of combinations can be very large, this function returns an iteratorobject. Use collect(combinations(array,n)) to get an array of all combina-tions.

11.2 Base.combinations

Base.combinations — Method.

generate combinations of all orders, chaining of order iterators is eager, butsequence at each order is lazy

11.3 Base.factorial

Base.factorial — Method.

computes n!/k!

11.4 Base.levicivita

Base.levicivita — Method.

Levi-Civita symbol of a permutation.

Returns 1 is the permutation is even, -1 if it is odd and 0 otherwise.

The parity is computed by using the fact that a permutation is odd if andonly if the number of even-length cycles is odd.

204

Page 210: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

11.5. BASE.NTHPERM! 205

11.5 Base.nthperm!

Base.nthperm! — Method.

In-place version of nthperm.

11.6 Base.nthperm

Base.nthperm — Method.

Compute the kth lexicographic permutation of the vector a.

11.7 Base.nthperm

Base.nthperm — Method.

Return the k that generated permutation p. Note that nthperm(nthperm([1:n],k)) == k for 1 <= k <= factorial(n).

11.8 Base.parity

Base.parity — Method.

Computes the parity of a permutation using the levicivita function, so youcan ask iseven(parity(p)). If p is not a permutation throws an error.

11.9 Base.partitions

Base.partitions — Method.

Generate all set partitions of the elements of an array into exactly m subsets,represented as arrays of arrays. Because the number of partitions can be verylarge, this function returns an iterator object. Use collect(partitions(array,m))to get an array of all partitions. The number of partitions into m subsets is equalto the Stirling number of the second kind and can be efficiently computed usinglength(partitions(array,m)).

11.10 Base.partitions

Base.partitions — Method.

Generate all set partitions of the elements of an array, represented as arraysof arrays. Because the number of partitions can be very large, this functionreturns an iterator object. Use collect(partitions(array)) to get an array ofall partitions. The number of partitions to generate can be efficiently computedusing length(partitions(array)).

Page 211: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

206 CHAPTER 11. COMBINATORICS

11.11 Base.partitions

Base.partitions — Method.

Generate all arrays of m integers that sum to n. Because the number ofpartitions can be very large, this function returns an iterator object. Usecollect(partitions(n,m)) to get an array of all partitions. The number ofpartitions to generate can be efficiently computed using length(partitions(n,m)).

11.12 Base.partitions

Base.partitions — Method.

Generate all integer arrays that sum to n. Because the number of partitionscan be very large, this function returns an iterator object. Use collect(partitions(n))to get an array of all partitions. The number of partitions to generate can beefficiently computed using length(partitions(n)).

11.13 Base.permutations

Base.permutations — Method.

Generate all size t permutations of an indexable object.

11.14 Base.permutations

Base.permutations — Method.

Generate all permutations of an indexable object. Because the number ofpermutations can be very large, this function returns an iterator object. Usecollect(permutations(array)) to get an array of all permutations.

11.15 Base.prevprod

Base.prevprod — Method.

Previous integer not greater than n that can be written as∏kpii for integers

p1, p2, etc.

For a list of integers i1, i2, i3, find the largest i1ˆn1 * i2ˆn2 * i3ˆn3 <= xfor integer n1, n2, n3

11.16 Combinatorics.bellnum

Combinatorics.bellnum — Method.

Returns the n-th Bell number

Page 212: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

11.17. COMBINATORICS.CATALANNUM 207

11.17 Combinatorics.catalannum

Combinatorics.catalannum — Method.

Returns the n-th Catalan number

11.18 Combinatorics.character

Combinatorics.character — Method.

Computes character () of the partition in the th irrep of the symmetricgroup Sn

Implements the Murnaghan-Nakayama algorithm as described in: Dan Bern-stein, “The computational complexity of rules for the character table of Sn”,Journal of Symbolic Computation, vol. 37 iss. 6 (2004), pp 727-748. doi:10.1016/j.jsc.2003.11.001

11.19 Combinatorics.derangement

Combinatorics.derangement — Method.

The number of permutations of n with no fixed points (subfactorial)

11.20 Combinatorics.integer partitions

Combinatorics.integer partitions — Method.

Lists the partitions of the number n, the order is consistent with GAP

11.21 Combinatorics.isrimhook

Combinatorics.isrimhook — Method.

Checks if skew diagram is a rim hook

11.22 Combinatorics.isrimhook

Combinatorics.isrimhook — Method.

Takes two elements of a partition sequence, with a to the left of b

11.23 Combinatorics.lassallenum

Combinatorics.lassallenum — Method.

Computes Lassalle’s sequence OEIS entry A180874

Page 213: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

208 CHAPTER 11. COMBINATORICS

11.24 Combinatorics.leglength

Combinatorics.leglength — Method.Strictly speaking, defined for rim hook only, but here we define it for all

skew diagrams

11.25 Combinatorics.multinomial

Combinatorics.multinomial — Method.Multinomial coefficient where n = sum(k)

11.26 Combinatorics.multiset combinations

Combinatorics.multiset combinations — Method.generate all combinations of size t from an array a with possibly duplicated

elements.

11.27 Combinatorics.multiset permutations

Combinatorics.multiset permutations — Method.generate all permutations of size t from an array a with possibly duplicated

elements.

11.28 Combinatorics.partitionsequence

Combinatorics.partitionsequence — Method.Computes essential part of the partition sequence of lambda

11.29 Combinatorics.stirlings1

Combinatorics.stirlings1 — Method.Returns s(n, k), the signed Stirling number of first kind

11.30 Combinatorics.with replacement combinations

Combinatorics.with replacement combinations — Method.generate all combinations with replacement of size t from an array a.

Page 214: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 12

Roots

12.1 Roots.D

Roots.D — Function.Take derivative of order k of a function.Arguments:

• f::Function: a mathematical function from R to R.

• k::Int=1: A non-negative integer specifying the order of the derivative.Values larger than 8 can be slow to compute.

Wrapper around derivative function in ForwardDiff

12.2 Roots.find zero

Roots.find zero — Method.Find a zero of a univariate function using one of several different methods.Positional arugments:

• f a function, callable object, or tuple of same. A tuple is used to pass inderivatives, as desired. Most methods are derivative free. Some (Newton,Halley) may have derivative(s) computed using the ForwardDiff pacakge.

• x0 an initial starting value. Typically a scalar, but may be an array forbisection methods. The value float(x0) is passed on.

• method one of several methods, see below.

Keyword arguments:

• xabstol=zero(): declare convergence if |x n - x {n-1}| <= max(xabstol,max(1, |x n|) * xreltol)

209

Page 215: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

210 CHAPTER 12. ROOTS

• xreltol=eps():

• abstol=zero(): declare convergence if |f(x n)| <= max(abstol, max(1,|x n|) * reltol)

• reltol:

• bracket: Optional. A bracketing interval for the sought after root. Ifgiven, a hybrid algorithm may be used where bisection is utilized for stepsthat would go out of bounds.

• maxevals::Int=40: stop trying after maxevals steps

• maxfnevals::Int=typemax(Int): stop trying after maxfnevals functionevaluations

• verbose::Bool=false: If true show information about algorithm and atrace.

Returns:Returns xn if the algorithm converges. If the algorithm stops, returns xn if

|f(xn)| ˆ(2/3), where = reltol, otherwise a ConvergenceFailed error is thrown.Exported methods:Bisection(); Order0() (heuristic, slow more robust); Order1() (also Secant());

Order2() (also Steffensen()); Order5() (KSS); Order8() (Thukral); Order16()(Thukral);

Not exported:Secant(), use Order1() Steffensen() use Order2() Newton() (use newton()

function) Halley() (use halley() function)The order 0 method is more robust to the initial starting point, but can

utilize many more function calls. The higher order methods may be of usewhen greater precision is desired.‘

Examples:

f(x) = x^5 - x - 1

find_zero(f, 1.0, Order5())

find_zero(f, 1.0, Steffensen()) # also Order2()

12.3 Roots.fzero

Roots.fzero — Method.Find a zero with bracket specified via [a,b], as fzero(sin, [3,4]).

12.4 Roots.fzero

Roots.fzero — Method.Find a zero within a bracket with an initial guess to possibly speed things

along.

Page 216: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

12.5. ROOTS.FZERO 211

12.5 Roots.fzero

Roots.fzero — Method.Find zero of a function within a bracketUses a modified bisection method for non big argumentsArguments:

• f A scalar function or callable object

• a left endpont of interval

• b right endpont of interval

• xtol optional additional tolerance on sub-bracket size.

For a bracket to be valid, it must be that f(a)*f(b) < 0.For Float64 values, the answer is such that f(prevfloat(x)) * f(nextfloat(x))

< 0 unless a non-zero value of xtol is specified in which case, it stops when thesub-bracketing produces an bracket with length less than max(xtol, abs(x1)*xtolrel).

For Big values, which defaults to the algorithm of Alefeld, Potra, and Shi,a default tolerance is used for the sub-bracket length that can be enlarged withxtol.

If a==-Inf it is replaced with nextfloat(a); if b==Inf it is replaced withprevfloat(b).

Example:

‘fzero(sin, 3, 4)‘ # find pi

‘fzero(sin, [big(3), 4]) find pi with more digits

12.6 Roots.fzero

Roots.fzero — Method.Find zero of a function using an iterative algorithm

• f: a scalar function or callable object

• x0: an initial guess, finite valued.

Keyword arguments:

• ftol: tolerance for a guess abs(f(x)) < ftol

• xtol: stop if abs(xold - xnew) <= xtol + max(1, |xnew|)*xtolrel

• xtolrel: see xtol

• maxeval: maximum number of steps

• verbose: Boolean. Set true to trace algorithm

Page 217: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

212 CHAPTER 12. ROOTS

• order: Can specify order of algorithm. 0 is most robust, also 1, 2, 5, 8,16.

• kwargs... passed on to different algorithms. There are maxfneval whenorder is 1,2,5,8, or 16 and beta for orders 2,5,8,16,

This is a polyalgorithm redirecting different algorithms based on the valueof order.

12.7 Roots.fzero

Roots.fzero — Method.Find zero using Newton’s method.

12.8 Roots.fzero

Roots.fzero — Method.Find zero of a polynomial with derivative free algorithm.Arguments:

• p a Poly object

• x0 an initial guess

Returns:An approximate root or an error.See fzeros(p) to return all real roots.

12.9 Roots.fzeros

Roots.fzeros — Method.Attempt to find all zeros of f within an interval [a,b].Simple algorithm that splits [a,b] into subintervals and checks each for a

root. For bracketing subintervals, bisection is used. Otherwise, a derivative-free method is used. If there are a large number of roots found relative to thenumber of subintervals, the number of subintervals is increased and the processis re-run.

There are possible issues with close-by zeros and zeros which do not cross theorigin (non-simple zeros). Answers should be confirmed graphically, if possible.

12.10 Roots.fzeros

Roots.fzeros — Method.Find real zeros of a polynomialargs:

Page 218: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

12.11. ROOTS.HALLEY 213

f: a Polynomial function of R -> R. May also be of Poly type.For polynomials in Z[x] or Q[x], the real roots method will use Poly{Rational{BigInt}}

arithmetic, which allows it to handle much larger degree polynomials accurately.This can be called directly using Polynomial objects.

12.11 Roots.halley

Roots.halley — Method.Implementation of Halley’s method. xn1 = xn - 2f(xn)*f(xn) / (2*f(xn)^2

- f(xn) * f(xn))

Arguments:

• f::Function – function to find zero of

• fp::Function=D(f) – derivative of f. Defaults to automatic derivative

• fpp:Function=D(f,2) – second derivative of f.

• x0::Real – initial guess

Keyword arguments:

• ftol. Stop iterating when |f(xn)| <= max(1, |xn|) * ftol.

• xtol. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel

• xtolrel. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel

• maxeval. Stop iterating if more than this many steps, throw error.

• verbose::Bool=false Set to true to see trace.

12.12 Roots.newton

Roots.newton — Method.Implementation of Newton’s method: x n1 = x n - f(x n)/ f(x n)

Arguments:

• f::Function – function to find zero of

• fp::Function=D(f) – derivative of f. Defaults to automatic derivative

• x0::Real – initial guess

Keyword arguments:

• ftol. Stop iterating when |f(xn)| <= max(1, |xn|) * ftol.

• xtol. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel

Page 219: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

214 CHAPTER 12. ROOTS

• xtolrel. Stop iterating when |xn+1 - xn| <= xtol + max(1, |xn|) * xtolrel

• maxeval. Stop iterating if more than this many steps, throw error.

• maxfneval. Stop iterating if more than this many function calls, throwerror.

• verbose::Bool=false Set to true to see trace.

12.13 Roots.polyfactor

Roots.polyfactor — Method.Factor a polynomial function with rational or integer coefficients over the

integers. Returns a dictionary with irreducible factors and their multiplicities.See multroot to do similar act over polynomials with real coefficients. Example:

polyfactor(x -> (x-1)^3*(x-2))

12.14 Roots.secant method

Roots.secant method — Method.secant method: solve for zero of f(x) = 0 using the secant method

Page 220: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 13

Reactive

13.1 Base.filter

Base.filter — Method.

filter(f, signal)

remove updates from the signal where f returns false.

13.2 Base.map

Base.map — Method.

map(f, s::Signal...) -> signal

Transform signal s by applying f to each element. For multiple signal argu-ments, apply f elementwise.

13.3 Base.merge

Base.merge — Method.

merge(input...)

Merge many signals into one. Returns a signal which updates when any ofthe inputs update. If many signals update at the same time, the value of theyoungest input signal is taken.

215

Page 221: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

216 CHAPTER 13. REACTIVE

13.4 Base.push!

Base.push! — Function.

push!(signal, value, onerror=Reactive.print error)

Queue an update to a signal. The update will be propagated when allcurrently queued updates are done processing.

The third optional argument is a callback to be called in case the updateends in an error. The callback receives 3 arguments: the signal, the value, anda CapturedException with the fields ex which is the original exception object,and processed bt which is the backtrace of the exception.

The default error callback will print the error and backtrace to STDERR.

13.5 Reactive.async map

Reactive.async map — Method.

tasks, results = async_map(f, init, input...;typ=typeof(init), onerror=Reactive.print_error)

Spawn a new task to run a function when input signal updates. Returnsa signal of tasks and a results signal which updates asynchronously with theresults. init will be used as the default value of results. onerror is thecallback to be called when an error occurs, by default it is set to a callbackwhich prints the error to STDERR. It’s the same as the onerror argument topush! but is run in the spawned task.

13.6 Reactive.bind!

Reactive.bind! — Function.

bind!(a,b,twoway=true)

for every update to a also update b with the same value and vice-versa. Toonly bind updates from b to a, pass in a third argument as false

13.7 Reactive.delay

Reactive.delay — Function.

delay(input, default=value(input))

Schedule an update to happen after the current update propagates through-out the signal graph.

Returns the delayed signal.

Page 222: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

13.8. REACTIVE.DROPREPEATS 217

13.8 Reactive.droprepeats

Reactive.droprepeats — Method.

droprepeats(input)

Drop updates to input whenever the new value is the same as the previousvalue of the signal.

13.9 Reactive.every

Reactive.every — Method.

every(dt)

A signal that updates every dt seconds to the current timestamp. Considerusing fpswhen or fps before using every.

13.10 Reactive.filterwhen

Reactive.filterwhen — Method.

filterwhen(switch::Signal{Bool}, default, input)

Keep updates to input only when switch is true.If switch is false initially, the specified default value is used.

13.11 Reactive.flatten

Reactive.flatten — Method.

flatten(input::Signal{Signal}; typ=Any)

Flatten a signal of signals into a signal which holds the value of the currentsignal. The typ keyword argument specifies the type of the flattened signal. Itis Any by default.

13.12 Reactive.foldp

Reactive.foldp — Method.

foldp(f, init, input)

Fold over past values.Accumulate a value as the input signal changes. init is the initial value

of the accumulator. f should take 2 arguments: the current accumulated valueand the current update, and result in the next accumulated value.

Page 223: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

218 CHAPTER 13. REACTIVE

13.13 Reactive.fps

Reactive.fps — Method.

fps(rate)

Same as fpswhen(Input(true), rate)

13.14 Reactive.fpswhen

Reactive.fpswhen — Method.

fpswhen(switch, rate)

returns a signal which when switch signal is true, updates rate times everysecond. If rate is not possible to attain because of slowness in computingdependent signal values, the signal will self adjust to provide the best possiblerate.

13.15 Reactive.preserve

Reactive.preserve — Method.

preserve(signal::Signal)

prevents signal from being garbage collected as long as any of its parentsare around. Useful for when you want to do some side effects in a signal. e.g.preserve(map(println, x)) - this will continue to print updates to x, until xgoes out of scope. foreach is a shorthand for map with preserve.

13.16 Reactive.previous

Reactive.previous — Function.

previous(input, default=value(input))

Create a signal which holds the previous value of input. You can optionallyspecify a different initial value.

13.17 Reactive.remote map

Reactive.remote map — Method.

remoterefs, results = remote_map(procid, f, init, input...;typ=typeof(init), onerror=Reactive.print_error)

Page 224: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

13.18. REACTIVE.SAMPLEON 219

Spawn a new task on process procid to run a function when input signalupdates. Returns a signal of remote refs and a results signal which updatesasynchronously with the results. init will be used as the default value ofresults. onerror is the callback to be called when an error occurs, by defaultit is set to a callback which prints the error to STDERR. It’s the same as theonerror argument to push! but is run in the spawned task.

13.18 Reactive.sampleon

Reactive.sampleon — Method.

sampleon(a, b)

Sample the value of b whenever a updates.

13.19 Reactive.throttle

Reactive.throttle — Function.

throttle(dt, input, f=(acc,x)->x, init=value(input), reinit=x->x)

Throttle a signal to update at most once every dt seconds. By default, thethrottled signal holds the last update in the time window.

This behavior can be changed by the f, init and reinit arguments. Theinit and f functions are similar to init and f in foldp. reinit is called when anew throttle time window opens to reinitialize the initial value for accumulation,it gets one argument, the previous accumulated value.

For example y = throttle(0.2, x, push!, Int[], ->Int[]) will cre-ate vectors of updates to the integer signal x which occur within 0.2 second timewindows.

13.20 Reactive.unbind!

Reactive.unbind! — Function.

unbind!(a,b,twoway=true)

remove a link set up using bind!

13.21 Reactive.unpreserve

Reactive.unpreserve — Method.

unpreserve(signal::Signal)

allow signal to be garbage collected. See also preserve.

Page 225: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 14

Documenter

14.1 Documenter.deploydocs

Documenter.deploydocs — Method.

deploydocs(

root = "<current-directory>",

target = "site",

repo = "<required>",

branch = "gh-pages",

latest = "master",

osname = "linux",

julia = "nightly",

deps = <Function>,

make = <Function>,

)

Converts markdown files generated by makedocs to HTML and pushes themto repo. This function should be called from within a package’s docs/make.jlfile after the call to makedocs, like so

[] using Documenter, PACKAGENAMEmakedocs(options...)deploydocs(repo =”github.com/...”)

Keywords

root has the same purpose as the root keyword for makedocs.

target is the directory, relative to root, where generated HTML contentshould be written to. This directory must be added to the repository’s .gitignorefile. The default value is "site".

repo is the remote repository where generated HTML content should bepushed to. This keyword must be set and will throw an error when left unde-fined. For example this package uses the following repo value:

[] repo = ”github.com/JuliaDocs/Documenter.jl.git”

220

Page 226: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

14.2. DOCUMENTER.HIDE 221

branch is the branch where the generated documentation is pushed. Bydefault this value is set to "gh-pages".

latest is the branch that “tracks” the latest generated documentation. Bydefault this value is set to "master".

osname is the operating system which will be used to deploy generated docu-mentation. This defaults to "linux". This value must be one of those specifiedin the os: section of the .travis.yml configuration file.

julia is the version of Julia that will be used to deploy generated documen-tation. This defaults to "nightly". This value must be one of those specifiedin the julia: section of the .travis.yml configuration file.

deps is the function used to install any dependencies needed to build thedocumentation. By default this function installs pygments and mkdocs usingthe Deps.pip function:

[] deps = Deps.pip(”pygments”, ”mkdocs”)

make is the function used to convert the markdown files to HTML. By defaultthis just runs mkdocs build which populates the target directory.

See Also

The Hosting Documentation section of the manual provides a step-by-stepguide to using the deploydocs function to automatically generate docs andpush then to GitHub.

14.2 Documenter.hide

Documenter.hide — Method.

[] hide(root, children)

Allows a subsection of pages to be hidden from the navigation menu. root

will be linked to in the navigation menu, with the title determined as usual.children should be a list of pages (note that it can not be hierarchical).

Usage

[] makedocs( ..., pages = [ ..., hide(”Hidden section” =¿ ”hiddenindex.md”, [”hidden1.md”,”Hidden2”=>”hidden2.md”]),hide(”hiddenindex.md”, [...])])

14.3 Documenter.hide

Documenter.hide — Method.

[] hide(page)

Allows a page to be hidden in the navigation menu. It will only show up ifit happens to be the current page. The hidden page will still be present in thelinear page list that can be accessed via the previous and next page links. Thetitle of the hidden page can be overriden using the => operator as usual.

Usage

[] makedocs( ..., pages = [ ..., hide(”page1.md”), hide(”Title” =¿ ”page2.md”)] )

Page 227: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

222 CHAPTER 14. DOCUMENTER

14.4 Documenter.makedocs

Documenter.makedocs — Method.

makedocs(

root = "<current-directory>",

source = "src",

build = "build",

clean = true,

doctest = true,

modules = Module[],

repo = "",

)

Combines markdown files and inline docstrings into an interlinked document.In most cases makedocs should be run from a make.jl file:

[] using Documenter makedocs( keywords... )which is then run from the command line with:[] juliamake.jlThe folder structure that makedocs expects looks like:

docs/

build/

src/

make.jl

Keywordsroot is the directory from which makedocs should run. When run from a

make.jl file this keyword does not need to be set. It is, for the most part,needed when repeatedly running makedocs from the Julia REPL like so:

julia> makedocs(root = Pkg.dir("MyPackage", "docs"))

source is the directory, relative to root, where the markdown source filesare read from. By convention this folder is called src. Note that any non-markdown files stored in source are copied over to the build directory whenmakedocs is run.

build is the directory, relative to root, into which generated files and foldersare written when makedocs is run. The name of the build directory is, byconvention, called build, though, like with source, users are free to changethis to anything else to better suit their project needs.

clean tells makedocs whether to remove all the content from the build

folder prior to generating new content from source. By default this is set totrue.

doctest instructs makedocs on whether to try to test Julia code blocksthat are encountered in the generated document. By default this keyword isset to true. Doctesting should only ever be disabled when initially setting

Page 228: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

14.4. DOCUMENTER.MAKEDOCS 223

up a newly developed package where the developer is just trying to get theirpackage and documentation structure correct. After that, it’s encouraged toalways make sure that documentation examples are runnable and produce theexpected results. See the Doctests manual section for details about runningdoctests.

modules specifies a vector of modules that should be documented in source.If any inline docstrings from those modules are seen to be missing from thegenerated content then a warning will be printed during execution of makedocs.By default no modules are passed to modules and so no warnings will appear.This setting can be used as an indicator of the “coverage” of the generateddocumentation. For example Documenter’s make.jl file contains:

[] makedocs( modules = [Documenter], ... )and so any docstring from the module Documenter that is not spliced into

the generated documentation in build will raise a warning.repo specifies a template for the “link to source” feature. If you are using

GitHub, this is automatically generated from the remote. If you are using adifferent host, you can use this option to tell Documenter how URLs should begenerated. The following placeholders will be replaced with the respective valueof the generated link:

• {commit} Git commit id

• {path} Path to the file in the repository

• {line} Line (or range of lines) in the source file

For example if you are using GitLab.com, you could use[] makedocs(repo = ”https://gitlab.com/user/project/blob/{commit}{path}L{line}”)

See AlsoA guide detailing how to document a package using Documenter’s makedocs

is provided in the Usage section of the manual.

Page 229: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 15

CategoricalArrays

15.1 CategoricalArrays.categorical

CategoricalArrays.categorical — Function.

categorical{T}(A::AbstractArray{T}[, compress::Bool]; ordered::Bool=false)

Construct a categorical array with the values from A. If T<:Nullable, returna NullableCategoricalArray{T}; else, return a CategoricalArray{T}.

If the element type supports it, levels are sorted in ascending order; else,they are kept in their order of appearance in A. The ordered keyword argumentdetermines whether the array values can be compared according to the orderingof levels or not (see isordered).

If compress is provided and set to true, the smallest reference type ableto hold the number of unique values in A will be used. While this will reducememory use, passing this parameter will also introduce a type instability whichcan affect performance inside the function where the call is made. Therefore,use this option with caution (the one-argument version does not suffer from thisproblem).

categorical{T}(A::CategoricalArray{T}[, compress::Bool]; ordered::Bool=false)

categorical{T}(A::NullableCategoricalArray{T}[, compress::Bool]; ordered::Bool=false)

If A is already a CategoricalArray or a NullableCategoricalArray, itslevels are preserved. The reference type is also preserved unless compress isprovided. On the contrary, the ordered keyword argument takes precedenceover the corresponding property of the input array, even when not provided.

In all cases, a copy of A is made: use convert to avoid making copies whenunnecessary.

15.2 CategoricalArrays.compress

CategoricalArrays.compress — Method.

224

Page 230: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

15.3. CATEGORICALARRAYS.CUT 225

compress(A::CategoricalArray)

compress(A::NullableCategoricalArray)

Return a copy of categorical array A using the smallest reference type ableto hold the number of levels of A.

While this will reduce memory use, this function is type-unstable, which canaffect performance inside the function where the call is made. Therefore, use itwith caution.

15.3 CategoricalArrays.cut

CategoricalArrays.cut — Method.

cut(x::AbstractArray, ngroups::Integer;

labels::AbstractVector=String[])

Cut a numeric array into ngroups quantiles, determined using quantile.

15.4 CategoricalArrays.cut

CategoricalArrays.cut — Method.

cut(x::AbstractArray, breaks::AbstractVector;

extend::Bool=false, labels::AbstractVector=[])

Cut a numeric array into intervals and return an ordered CategoricalArray

indicating the interval into which each entry falls. Intervals are of the form[lower, upper), i.e. the lower bound is included and the upper bound is ex-cluded.

Arguments

• extend::Bool=false: when false, an error is raised if some values in x

fall outside of the breaks; when true, breaks are automatically added toinclude all values in x, and the upper bound is included in the last interval.

• labels::AbstractVector=[]: a vector of strings giving the names to usefor the intervals; if empty, default labels are used.

cut(x::AbstractArray{<:Nullable}, breaks::AbstractVector;

extend::Bool=false, labels::AbstractVector=[]), nullok::Bool=false)

For nullable arrays, return a NullableCategoricalArray. If nullok=true,values outside of breaks result in null values.

Page 231: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

226 CHAPTER 15. CATEGORICALARRAYS

15.5 CategoricalArrays.decompress

CategoricalArrays.decompress — Method.

decompress(A::CategoricalArray)

decompress(A::NullableCategoricalArray)

Return a copy of categorical array A using the default reference type (UInt32).If A is using a small reference type (such as UInt8 or UInt16) the decompressedarray will have room for more levels.

To avoid the need to call decompress, ensure compress is not called whencreating the categorical array.

15.6 CategoricalArrays.isordered

CategoricalArrays.isordered — Method.

isordered(A::CategoricalArray)

isordered(A::NullableCategoricalArray)

Test whether entries in A can be compared using <, > and similar operators,using the ordering of levels.

15.7 CategoricalArrays.levels!

CategoricalArrays.levels! — Function.

levels!(A::CategoricalArray, newlevels::Vector)

levels!(A::NullableCategoricalArray, newlevels::Vector; nullok::Bool=false)

Set the levels categorical array A. The order of appearance of levels will berespected by levels, which may affect display of results in some operations; ifA is ordered (see isordered), it will also be used for order comparisons using <,> and similar operators. Reordering levels will never affect the values of entriesin the array.

If A is a CategoricalArray, newlevels must include all levels which appearin the data. The same applies if A is a NullableCategoricalArray, unlessnullok=false is passed: in that case, entries corresponding to missing levelswill be set to null.

15.8 CategoricalArrays.levels

CategoricalArrays.levels — Method.

levels(A::CategoricalArray)

levels(A::NullableCategoricalArray)

Return the levels of categorical array A. This may include levels which donot actually appear in the data (see droplevels!).

Page 232: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

15.9. CATEGORICALARRAYS.ORDERED! 227

15.9 CategoricalArrays.ordered!

CategoricalArrays.ordered! — Method.

ordered!(A::CategoricalArray, ordered::Bool)

ordered!(A::NullableCategoricalArray, ordered::Bool)

Set whether entries in A can be compared using <, > and similar operators,using the ordering of levels. Return the modified A.

Page 233: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 16

Gadfly

16.1 Compose.draw

Compose.draw — Method.

draw(backend::Compose.Backend, p::Plot)

A convenience version of Compose.draw without having to call renderArgs

• backend: The Compose.Backend object

• p: The Plot object

16.2 Compose.gridstack

Compose.gridstack — Method.

gridstack(ps::Matrix{Plot}) -> Context

Arrange plots into a rectangular array.

16.3 Compose.hstack

Compose.hstack — Method.

hstack(ps::Plot...) = hstack(Context[render(p) for p in ps]...)

hstack(ps::Vector{Plot}) = hstack(Context[render(p) for p in ps]...)

hstack(p::Plot, c::Context) = hstack(render(p), c)

hstack(c::Context, p::Plot) = hstack(c, render(p))

Plots can be stacked horizontally to allow more customization in regardsto tick marks, axis labeling, and other plot details than what is available withsubplot grid

228

Page 234: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

16.4. COMPOSE.VSTACK 229

16.4 Compose.vstack

Compose.vstack — Method.

vstack(ps::Plot...) = vstack(Context[render(p) for p in ps]...)

vstack(ps::Vector{Plot}) = vstack(Context[render(p) for p in ps]...)

vstack(p::Plot, c::Context) = vstack(render(p), c)

vstack(c::Context, p::Plot) = vstack(c, render(p))

Plots can be stacked vertically to allow more customization in regards totick marks, axis labeling, and other plot details than what is available withsubplot grid

16.5 Gadfly.layer

Gadfly.layer — Method.

layer(data_source::@compat(Union{AbstractDataFrame, (@compat Void)}),

elements::ElementOrFunction...; mapping...)

Creates layers based on elementsArgs

• data source: The data source as a dataframe

• elements: The elements

• mapping: mapping

ReturnsAn array of layers

16.6 Gadfly.plot

Gadfly.plot — Method.

function plot(data_source::@compat(Union{(@compat Void), AbstractMatrix, AbstractDataFrame}),

mapping::Dict, elements::ElementOrFunctionOrLayers...)

The old fashioned (pre named arguments) version of plot.This version takes an explicit mapping dictionary, mapping aesthetics sym-

bols to expressions or columns in the data frame.Args:

• data source: Data to be bound to aesthetics.

• mapping: Dictionary of aesthetics symbols (e.g. :x, :y, :color) to names ofcolumns in the data frame or other expressions.

Page 235: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

230 CHAPTER 16. GADFLY

• elements: Geometries, statistics, etc.

Returns:A Plot object.

16.7 Gadfly.plot

Gadfly.plot — Method.

function plot(data_source::@compat(Union{AbstractMatrix, AbstractDataFrame}),

elements::ElementOrFunctionOrLayers...; mapping...)

Create a new plot.Grammar of graphics style plotting consists of specifying a dataset, one

or more plot elements (scales, coordinates, geometries, etc), and binding ofaesthetics to columns or expressions of the dataset.

For example, a simple scatter plot would look something like:plot(my data, Geom.point, x=“time”, y=“price”)Where “time” and “price” are the names of columns in my data.Args:

• data source: Data to be bound to aesthetics.

• elements: Geometries, statistics, etc.

• mapping: Aesthetics symbols (e.g. :x, :y, :color) mapped to names ofcolumns in the data frame or other expressions.

16.8 Gadfly.render

Gadfly.render — Method.

render(plot::Plot)

Render a plot based on the Plot objectArgs

• plot: Plot to be rendered.

ReturnsA Compose context containing the rendered plot.

16.9 Gadfly.set default plot format

Gadfly.set default plot format — Method.

set_default_plot_format(fmt::Symbol)

Sets the default plot format

Page 236: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

16.10. GADFLY.SET DEFAULT PLOT SIZE 231

16.10 Gadfly.set default plot size

Gadfly.set default plot size — Method.

set_default_plot_size(width::Compose.MeasureOrNumber, height::Compose.MeasureOrNumber)

Sets preferred canvas size when rendering a plot without an explicit call todraw

16.11 Gadfly.spy

Gadfly.spy — Method.

spy(M::AbstractMatrix, elements::ElementOrFunction...; mapping...)

Simple heatmap plots of matrices.It is a wrapper around the plot() function using the rectbin geometry.

It also applies a sane set of defaults to make sure that the plots look nice bydefault. Specifically

• the aspect ratio of the coordinate system is fixed Coord.cartesian(fixed=true),

so that the rectangles become squares

• the axes run from 0.5 to N+0.5, because the first row/column is drawn to

(0.5, 1.5) and the last one to (N-0.5, N+0.5).

• the y-direction is flipped, so that the [1,1] of a matrix is in the top

left corner, as is customary

• NaNs are not drawn. spy leaves “holes” instead into the heatmap.

Args:

• M: A matrix.

Returns:A plot object.Known bugs:

• If the matrix is only NaNs, then it throws an ArgumentError, because anempty collection gets passed to the plot function / rectbin geometry.

16.12 Gadfly.style

Gadfly.style — Method.Set some attributes in the current Theme. See Theme for available field.

Page 237: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

232 CHAPTER 16. GADFLY

16.13 Gadfly.title

Gadfly.title — Method.

title(ctx::Context, str::String, props::Property...) -> Context

Add a title string to a group of plots, typically created with vstack, hstack,or gridstack.

Examples

p1 = plot(x=[1,2], y=[3,4], Geom.line);

p2 = plot(x=[1,2], y=[4,3], Geom.line);

title(hstack(p1,p2), "my latest data", Compose.fontsize(18pt), fill(colorant"red"))

Page 238: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 17

DataStructures

17.1 DataStructures.back

DataStructures.back — Method.

back(q::Deque)

Returns the last element of the deque q.

17.2 DataStructures.compare

DataStructures.compare — Method.

compare(m::SAContainer, s::IntSemiToken, t::IntSemiToken)

Determines the relative positions of the data items indexed by (m,s) and(m,t) in the sorted order. The return value is -1 if (m,s) precedes (m,t), 0 ifthey are equal, and 1 if (m,s) succeeds (m,t). s and t are semitokens for thesame container m.

17.3 DataStructures.counter

DataStructures.counter — Method.

counter{T}(seq::AbstractArray)

Returns an Accumulator object containing the elements from seq.

17.4 DataStructures.deque

DataStructures.deque — Method.

deque(T)

Create a deque of type T.

233

Page 239: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

234 CHAPTER 17. DATASTRUCTURES

17.5 DataStructures.dequeue!

DataStructures.dequeue! — Method.

dequeue!(pq)

Remove and return the lowest priority key from a priority queue.

julia> a = PriorityQueue(["a","b","c"],[2,3,1],Base.Order.Forward)

PriorityQueue{String,Int64,Base.Order.ForwardOrdering} with 3 entries:

"c" => 1

"b" => 3

"a" => 2

julia> dequeue!(a)

"c"

julia> a

PriorityQueue{String,Int64,Base.Order.ForwardOrdering} with 2 entries:

"b" => 3

"a" => 2

17.6 DataStructures.dequeue!

DataStructures.dequeue! — Method.

dequeue!(s::Queue)

Removes an element from the front of the queue s and returns it.

17.7 DataStructures.enqueue!

DataStructures.enqueue! — Method.

enqueue!(pq, k, v)

Insert the a key k into a priority queue pq with priority v.

julia> a = PriorityQueue(["a","b","c"],[2,3,1],Base.Order.Forward)

PriorityQueue{String,Int64,Base.Order.ForwardOrdering} with 3 entries:

"c" => 1

"b" => 3

"a" => 2

julia> enqueue!(a, "d", 4)

PriorityQueue{String,Int64,Base.Order.ForwardOrdering} with 4 entries:

Page 240: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

17.8. DATASTRUCTURES.ENQUEUE! 235

"c" => 1

"b" => 3

"a" => 2

"d" => 4

17.8 DataStructures.enqueue!

DataStructures.enqueue! — Method.

enqueue!(s::Queue, x)

Inserts the value x to the end of the queue s.

17.9 DataStructures.find root

DataStructures.find root — Method.

find_root{T}(s::DisjointSets{T}, x::T)

Finds the root element of the subset in s which has the element x as amember.

17.10 DataStructures.front

DataStructures.front — Method.

front(q::Deque)

Returns the first element of the deque q.

17.11 DataStructures.heapify

DataStructures.heapify — Function.

heapify(v, ord::Ordering=Forward)

Returns a new vector in binary heap order, optionally using the given order-ing.

julia> a = [1,3,4,5,2];

julia> heapify(a)

5-element Array{Int64,1}:

1

2

Page 241: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

236 CHAPTER 17. DATASTRUCTURES

4

5

3

julia> heapify(a, Base.Order.Reverse)

5-element Array{Int64,1}:

5

3

4

1

2

17.12 DataStructures.heapify!

DataStructures.heapify! — Function.

heapify!(v, ord::Ordering=Forward)

In-place heapify.

17.13 DataStructures.heappop!

DataStructures.heappop! — Function.

heappop!(v, [ord])

Given a binary heap-ordered array, remove and return the lowest orderedelement. For efficiency, this function does not check that the array is indeedheap-ordered.

17.14 DataStructures.heappush!

DataStructures.heappush! — Function.

heappush!(v, x, [ord])

Given a binary heap-ordered array, push a new element x, preserving theheap property. For efficiency, this function does not check that the array isindeed heap-ordered.

17.15 DataStructures.in same set

DataStructures.in same set — Method.

in_same_set(s::IntDisjointSets, x::Integer, y::Integer)

Returns true if x and y belong to the same subset in s and false otherwise.

Page 242: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

17.16. DATASTRUCTURES.ISHEAP 237

17.16 DataStructures.isheap

DataStructures.isheap — Function.

isheap(v, ord::Ordering=Forward)

Return true if an array is heap-ordered according to the given order.

julia> a = [1,2,3]

3-element Array{Int64,1}:

1

2

3

julia> isheap(a,Base.Order.Forward)

true

julia> isheap(a,Base.Order.Reverse)

false

17.17 DataStructures.nlargest

DataStructures.nlargest — Method.Returns the n largest elements of arr.Equivalent to sort(arr, lt = >)[1:min(n, end)]

17.18 DataStructures.nsmallest

DataStructures.nsmallest — Method.Returns the n smallest elements of arr.Equivalent to sort(arr, lt = <)[1:min(n, end)]

17.19 DataStructures.peek

DataStructures.peek — Method.

peek(pq)

Return the lowest priority key from a priority queue without removing thatkey from the queue.

17.20 DataStructures.top

DataStructures.top — Method.

top(h::BinaryHeap)

Returns the element at the top of the heap h.

Page 243: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

238 CHAPTER 17. DATASTRUCTURES

17.21 DataStructures.update!

DataStructures.update! — Method.

update!{T}(h::MutableBinaryHeap{T}, i::Int, v::T)

Replace the element at index i in heap h with v.

Page 244: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 18

PyCall

18.1 PyCall.PyNULL

PyCall.PyNULL — Method.

PyNULL()

Return a PyObject that has a NULL underlying pointer, i.e. it doesn’t actuallyrefer to any Python object.

This is useful for initializing PyObject global variables and array elementsbefore an actual Python object is available. For example, you might do const

myglobal = PyNULL() and later on (e.g. in a module init function), reas-sign myglobal to point to an actual object with copy!(myglobal, someobject).This procedure will properly handle Python’s reference counting (so that thePython object will not be freed until you are done with myglobal).

18.2 PyCall.PyReverseDims

PyCall.PyReverseDims — Method.

PyReverseDims(array)

Passes a Julia array to Python as a NumPy row-major array (rather thanJulia’s native column-major order) with the dimensions reversed (e.g. a 234 Juliaarray is passed as a 432 NumPy row-major array). This is useful for Pythonlibraries that expect row-major data.

18.3 PyCall.PyTextIO

PyCall.PyTextIO — Method.

239

Page 245: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

240 CHAPTER 18. PYCALL

PyTextIO(io::IO)

PyObject(io::IO)

Julia IO streams are converted into Python objects implementing the Raw-IOBase interface, so they can be used for binary I/O in Python

18.4 PyCall.pybuiltin

PyCall.pybuiltin — Method.

pybuiltin(s::AbstractString)

Look up a string or symbol s among the global Python builtins. If s isa string it returns a PyObject, while if s is a symbol it returns the builtinconverted to PyAny.

18.5 PyCall.pycall

PyCall.pycall — Method.

pycall(o::Union{PyObject,PyPtr}, returntype::TypeTuple, args...; kwargs...)

Call the given Python function (typically looked up from a module) withthe given args. . . (of standard Julia types which are converted automaticallyto the corresponding Python types if possible), converting the return value toreturntype (use a returntype of PyObject to return the unconverted Pythonobject reference, or of PyAny to request an automated conversion)

18.6 PyCall.pyeval

PyCall.pyeval — Function.

pyeval(s::AbstractString, returntype::TypeTuple=PyAny, locals=PyDict{AbstractString, PyObject}(),

input_type=Py_eval_input; kwargs...)

This evaluates s as a Python string and returns the result converted to rtype

(which defaults to PyAny). The remaining arguments are keywords that definelocal variables to be used in the expression.

For example, pyeval("x + y", x=1, y=2) returns 3.

18.7 PyCall.pygui

PyCall.pygui — Method.

pygui()

Return the current GUI toolkit as a symbol.

Page 246: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

18.8. PYCALL.PYGUI START 241

18.8 PyCall.pygui start

PyCall.pygui start — Function.

pygui_start(gui::Symbol = pygui())

Start the event loop of a certain toolkit.The argument gui defaults to the current default GUI, but it could be :wx,

:gtk, :gtk3, :tk, or :qt.

18.9 PyCall.pygui stop

PyCall.pygui stop — Function.

pygui_stop(gui::Symbol = pygui())

Stop any running event loop for gui. The gui argument defaults to currentdefault GUI.

18.10 PyCall.pyimport

PyCall.pyimport — Method.

pyimport(s::AbstractString)

Import the Python module s (a string or symbol) and return a pointer to it(a PyObject). Functions or other symbols in the module may then be lookedup by s[name] where name is a string (for the raw PyObject) or symbol (forautomatic type-conversion). Unlike the @pyimport macro, this does not definea Julia module and members cannot be accessed with s.name

18.11 PyCall.pyimport conda

PyCall.pyimport conda — Function.

pyimport_conda(modulename, condapkg, [channel])

Returns the result of pyimport(modulename) if possible. If the module is notfound, and PyCall is configured to use the Conda Python distro (via the JuliaConda package), then automatically install condapkg via Conda.add(condapkg)and then re-try the pyimport. Other Anaconda-based Python installations arealso supported as long as their conda program is functioning.

If PyCall is not using Conda and the pyimport fails, throws an exceptionwith an error message telling the user how to configure PyCall to use Conda forautomated installation of the module.

The third argument, channel is an optional Anaconda “channel” to use forinstalling the package; this is useful for packages that are not included in thedefault Anaconda package listing.

Page 247: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

242 CHAPTER 18. PYCALL

18.12 PyCall.pytype mapping

PyCall.pytype mapping — Method.

pytype_mapping(pytype, jltype)

Given a Python type object pytype, tell PyCall to convert it to jltype inPyAny(object) conversions.

18.13 PyCall.pytype query

PyCall.pytype query — Function.

pytype_query(o::PyObject, default=PyObject)

Given a Python object o, return the corresponding native Julia type (de-faulting to default) that we convert o to in PyAny(o) conversions.

18.14 PyCall.pywrap

PyCall.pywrap — Function.

pywrap(o::PyObject)

This returns a wrapper w that is an anonymous module which provides (read)access to converted versions of o’s members as w.member.

For example, @pyimport module as name is equivalent to const name =

pywrap(pyimport("module"))

If the Python module contains identifiers that are reserved words in Julia(e.g. function), they cannot be accessed as w.member; one must instead usew.pymember(:member) (for the PyAny conversion) or w.pymember(“member”)(for the raw PyObject).

Page 248: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 19

ColorTypes

19.1 ColorTypes.alpha

ColorTypes.alpha — Method.

alpha(p) extracts the alpha component of a color. For a color without analpha channel, it will always return 1.

19.2 ColorTypes.alphacolor

ColorTypes.alphacolor — Function.

alphacolor(RGB) returns ARGB, i.e., the corresponding transparent colortype with storage order (alpha, color).

19.3 ColorTypes.base color type

ColorTypes.base color type — Method.

base color type is similar to color type, except it “strips off” the elementtype. For example,

color_type(RGB{N0f8}) == RGB{N0f8}

base_color_type(RGB{N0f8}) == RGB

This can be very handy if you want to switch element types. For example:

c64 = base_color_type(c){Float64}(color(c))

converts c into a Float64 representation (potentially discarding any alpha-channel information).

243

Page 249: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

244 CHAPTER 19. COLORTYPES

19.4 ColorTypes.base colorant type

ColorTypes.base colorant type — Method.base colorant type is similar to base color type, but it preserves the

“alpha” portion of the type.For example,

base_color_type(ARGB{N0f8}) == RGB

base_colorant_type(ARGB{N0f8}) == ARGB

If you just want to switch element types, this is the safest default and theeasiest to use:

c64 = base_colorant_type(c){Float64}(c)

19.5 ColorTypes.blue

ColorTypes.blue — Method.blue(c) returns the blue component of an AbstractRGB opaque or trans-

parent color.

19.6 ColorTypes.ccolor

ColorTypes.ccolor — Method.ccolor (“concrete color”) helps write flexible methods. The idea is that

users may write convert(HSV, c) or even convert(Array{HSV}, A) withoutspecifying the element type explicitly (e.g., convert(Array{HSV{Float32}},A)). ccolor implements the logic “choose the user’s eltype if specified, otherwiseretain the eltype of the source object.” However, when the source object hasFixedPoint element type, and the destination only supports AbstractFloat, wechoose Float32.

Usage:

ccolor(desttype, srctype) -> concrete desttype

Example:

convert{C<:Colorant}(::Type{C}, p::Colorant) = cnvt(ccolor(C,typeof(p)), p)

where cnvt is the function that performs explicit conversion.

19.7 ColorTypes.color

ColorTypes.color — Method.color(c) extracts the opaque color component from a Colorant (e.g., omits

the alpha channel, if present).

Page 250: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

19.8. COLORTYPES.COLOR TYPE 245

19.8 ColorTypes.color type

ColorTypes.color type — Method.

color type(c) or color type(C) (c being a color instance and C being thetype) returns the type of the Color object (without alpha channel). This, andrelated functions like base color type, base colorant type, and ccolor areuseful for manipulating types for writing generic code.

For example,

color_type(RGB) == RGB

color_type(RGB{Float32}) == RGB{Float32}

color_type(ARGB{N0f8}) == RGB{N0f8}

19.9 ColorTypes.coloralpha

ColorTypes.coloralpha — Function.

coloralpha(RGB) returns RGBA, i.e., the corresponding transparent colortype with storage order (color, alpha).

19.10 ColorTypes.comp1

ColorTypes.comp1 — Method.

comp1(c) extracts the first component you’d pass to the constructor of thecorresponding object. For most color types without an alpha channel, this isjust the first field, but for types like BGR that reverse the internal storage orderthis provides the value that you’d use to reconstruct the color.

Specifically, for any Color{T,3},

c == typeof(c)(comp1(c), comp2(c), comp3(c))

returns true.

19.11 ColorTypes.comp2

ColorTypes.comp2 — Method.

comp2(c) extracts the second constructor argument (see comp1).

19.12 ColorTypes.comp3

ColorTypes.comp3 — Method.

comp3(c) extracts the third constructor argument (see comp1).

Page 251: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

246 CHAPTER 19. COLORTYPES

19.13 ColorTypes.gray

ColorTypes.gray — Method.gray(c) returns the gray component of a grayscale opaque or transparent

color.

19.14 ColorTypes.green

ColorTypes.green — Method.green(c) returns the green component of an AbstractRGB opaque or trans-

parent color.

19.15 ColorTypes.mapc

ColorTypes.mapc — Method.

mapc(f, rgb) -> rgbf

mapc(f, rgb1, rgb2) -> rgbf

mapc applies the function f to each color channel of the input color(s), re-turning an output color in the same colorspace.

Examples:

julia> mapc(x->clamp(x,0,1), RGB(-0.2,0.3,1.2))

RGB{Float64}(0.0,0.3,1.0)

julia> mapc(max, RGB(0.1,0.8,0.3), RGB(0.5,0.5,0.5))

RGB{Float64}(0.5,0.8,0.5)

julia> mapc(+, RGB(0.1,0.8,0.3), RGB(0.5,0.5,0.5))

RGB{Float64}(0.6,1.3,0.8)

19.16 ColorTypes.red

ColorTypes.red — Method.red(c) returns the red component of an AbstractRGB opaque or transparent

color.

Page 252: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 20

Colors

20.1 Base.hex

Base.hex — Method.

hex(c)

Print a color as a RGB hex triple, or a transparent paint as an ARGB hexquadruplet.

20.2 Colors.MSC

Colors.MSC — Method.

MSC(h)

MSC(h, l)

Calculates the most saturated color for any given hue h by finding the cor-responding corner in LCHuv space. Optionally, the lightness l may also bespecified.

20.3 Colors.colordiff

Colors.colordiff — Method.

colordiff(a, b)

colordiff(a, b, metric)

Compute an approximate measure of the perceptual difference between col-ors a and b. Optionally, a metric may be supplied, chosen among DE 2000

(the default), DE 94, DE JPC79, DE CMC, DE BFD, DE AB, DE DIN99, DE DIN99d,DE DIN99o.

247

Page 253: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

248 CHAPTER 20. COLORS

20.4 Colors.colormap

Colors.colormap — Function.

colormap(cname, [N; mid, logscale, kvs...])

Returns a predefined sequential or diverging colormap computed using thealgorithm by Wijffelaars, M., et al. (2008). Sequential colormaps cname choicesare Blues, Greens, Grays, Oranges, Purples, and Reds. Diverging colormapchoices are RdBu. Optionally, you can specify the number of colors N (default100). Keyword arguments include the position of the middle point mid (default0.5) and the possibility to switch to log scaling with logscale (default false).

20.5 Colors.colormatch

Colors.colormatch — Method.

colormatch(wavelength)

colormatch(matchingfunction, wavelength)

Evaluate the CIE standard observer color match function.

Args:

• matchingfunction (optional): a type used to specify the matching func-tion. Choices include CIE1931 CMF (the default, the CIE 1931 2 match-ing function), CIE1964 CMF (the CIE 1964 10 color matching function),CIE1931J CMF (Judd adjustment to CIE1931 CMF), CIE1931JV CMF (Judd-Vos adjustment to CIE1931 CMF).

• wavelen: Wavelength of stimulus in nanometers.

Returns: XYZ value of perceived color.

20.6 Colors.deuteranopic

Colors.deuteranopic — Method.

deuteranopic(c)

deuteranopic(c, p)

Convert a color to simulate deuteranopic color deficiency (lack of the middle-wavelength photopigment). See the description of protanopic for detail aboutthe arguments.

Page 254: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

20.7. COLORS.DISTINGUISHABLE COLORS 249

20.7 Colors.distinguishable colors

Colors.distinguishable colors — Method.

distinguishable_colors(n, [seed]; [transform, lchoices, cchoices, hchoices])

Generate n maximally distinguishable colors.This uses a greedy brute-force approach to choose n colors that are maxi-

mally distinguishable. Given seed color(s), and a set of possible hue, chroma,and lightness values (in LCHab space), it repeatedly chooses the next color asthe one that maximizes the minimum pairwise distance to any of the colorsalready in the palette.

Args:

• n: Number of colors to generate.

• seed: Initial color(s) included in the palette. Default is Vector{RGB{N0f8}}(0).

Keyword arguments:

• transform: Transform applied to colors before measuring distance. De-fault is the identity; other choices include deuteranopic to simulate color-blindness.

• lchoices: Possible lightness values (default linspace(0,100,15))

• cchoices: Possible chroma values (default linspace(0,100,15))

• hchoices: Possible hue values (default linspace(0,340,20))

Returns: A Vector of colors of length n, of the type specified in seed.

20.8 Colors.protanopic

Colors.protanopic — Method.

protanopic(c)

protanopic(c, p)

Convert a color to simulate protanopic color deficiency (lack of the long-wavelength photopigment). c is the input color; the optional argument p is thefraction of photopigment loss, in the range 0 (no loss) to 1 (complete loss).

20.9 Colors.tritanopic

Colors.tritanopic — Method.

tritanopic(c)

tritanopic(c, p)

Convert a color to simulate tritanopic color deficiency (lack of the short-wavelength photogiment). See protanopic for more detail about the arguments.

Page 255: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

250 CHAPTER 20. COLORS

20.10 Colors.weighted color mean

Colors.weighted color mean — Method.

weighted_color_mean(w1, c1, c2)

Returns the color w1*c1 + (1-w1)*c2 that is the weighted mean of c1 andc2, where c1 has a weight 0 w1 1.

20.11 Colors.whitebalance

Colors.whitebalance — Method.

whitebalance(c, src_white, ref_white)

Whitebalance a color.Input a source (adopted) and destination (reference) white. E.g., if you have

a photo taken under florencent lighting that you then want to appear correctunder regular sunlight, you might do something like whitebalance(c, WP F2,

WP D65).Args:

• c: An observed color.

• src white: Adopted or source white corresponding to c

• ref white: Reference or destination white.

Returns: A whitebalanced color.

Page 256: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 21

Interact

21.1 Interact.button

Interact.button — Method.

button(label; value=nothing, signal)

Create a push button. Optionally specify the label, the value emittedwhen then button is clicked, and/or the (Reactive.jl) signal coupled to thisbutton.

21.2 Interact.checkbox

Interact.checkbox — Method.

checkbox(value=false; label="", signal)

Provide a checkbox with the specified starting (boolean) value. Optionalprovide a label for this widget and/or the (Reactive.jl) signal coupled to thiswidget.

21.3 Interact.dropdown

Interact.dropdown — Method.

dropdown(choices; label="", value, typ, icons, tooltips, signal)

Create a “dropdown” widget. choices can be a vector of options. Option-ally specify the starting value (defaults to the first choice), the typ of elementsin choices, supply custom icons, provide tooltips, and/or specify the (Re-active.jl) signal coupled to this widget.

Examples

251

Page 257: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

252 CHAPTER 21. INTERACT

a = dropdown(["one", "two", "three"])

To link a callback to the dropdown, use

f = dropdown(["turn red"=>colorize_red, "turn green"=>colorize_green])

map(g->g(image), signal(f))

21.4 Interact.radiobuttons

Interact.radiobuttons — Method.radiobuttons: see the help for dropdown

21.5 Interact.selection

Interact.selection — Method.selection: see the help for dropdown

21.6 Interact.selection slider

Interact.selection slider — Method.selection slider: see the help for dropdown If the slider has numeric (<:Real)

values, and its signal is updated, it will update to the nearest value from therange/choices provided. To disable this behaviour, so that the widget state willonly update if an exact match for signal value is found in the range/choice, usesyncnearest=false.

21.7 Interact.set!

Interact.set! — Method.set!(w::Widget, fld::Symbol, val)

Set the value of a widget property and update all displayed instances of thewidget. If val is a Signal, then updates to that signal will be reflected inwidget instances/views.

If fld is :value, val is also push!ed to signal(w)

21.8 Interact.slider

Interact.slider — Method.

slider(range; value, signal, label="", readout=true, continuous_update=true)

Create a slider widget with the specified range. Optionally specify thestarting value (defaults to the median of range), provide the (Reactive.jl)signal coupled to this slider, and/or specify a string label for the widget.

Page 258: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

21.9. INTERACT.TEXTAREA 253

21.9 Interact.textarea

Interact.textarea — Method.

textarea(value=""; label="", signal)

Creates an extended text-entry area. Optionally provide a label and/or the(Reactive.jl) signal associated with this widget. The signal updates when youtype.

21.10 Interact.textbox

Interact.textbox — Method.

textbox(value=""; label="", typ=typeof(value), range=nothing, signal)

Create a box for entering text. value is the starting value; if you don’t wantto provide an initial value, you can constrain the type with typ. Optionally pro-vide a label, specify the allowed range (e.g., -10.0:10.0) for numeric entries,and/or provide the (Reactive.jl) signal coupled to this text box.

21.11 Interact.togglebutton

Interact.togglebutton — Method.

togglebutton(label=""; value=false, signal)

Create a toggle button. Optionally specify the label, the initial state(value=false is off, value=true is on), and/or provide the (Reactive.jl) signalcoupled to this button.

21.12 Interact.togglebuttons

Interact.togglebuttons — Method.

togglebuttons: see the help for dropdown

21.13 Interact.vselection slider

Interact.vselection slider — Method.

vselection slider(args...; kwargs...)

Shorthand for selection slider(args...; orientation="vertical", kwargs...)

Page 259: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

254 CHAPTER 21. INTERACT

21.14 Interact.vslider

Interact.vslider — Method.vslider(args...; kwargs...)

Shorthand for slider(args...; orientation="vertical", kwargs...)

Page 260: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 22

FileIO

22.1 Base.info

Base.info — Method.info(fmt) returns the magic bytes/extension information for DataFormat

fmt.

22.2 FileIO.add format

FileIO.add format — Method.add format(fmt, magic, extention) registers a new DataFormat. For ex-

ample:

add_format(format"PNG", (UInt8[0x4d,0x4d,0x00,0x2b], UInt8[0x49,0x49,0x2a,0x00]), [".tiff", ".tif"])

add_format(format"PNG", [0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a], ".png")

add_format(format"NRRD", "NRRD", [".nrrd",".nhdr"])

Note that extensions, magic numbers, and format-identifiers are case-sensitive.

22.3 FileIO.add loader

FileIO.add loader — Function.add loader(fmt, :Package) triggers using Package before loading format

fmt

22.4 FileIO.add saver

FileIO.add saver — Function.add saver(fmt, :Package) triggers using Package before saving format

fmt

255

Page 261: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

256 CHAPTER 22. FILEIO

22.5 FileIO.del format

FileIO.del format — Method.del format(fmt::DataFormat) deletes fmt from the format registry.

22.6 FileIO.file extension

FileIO.file extension — Method.file extension(file) returns the file extension associated with File file.

22.7 FileIO.file extension

FileIO.file extension — Method.file extension(file) returns a nullable-string for the file extension asso-

ciated with Stream stream.

22.8 FileIO.filename

FileIO.filename — Method.filename(file) returns the filename associated with File file.

22.9 FileIO.filename

FileIO.filename — Method.filename(stream) returns a nullable-string of the filename associated with

Stream stream.

22.10 FileIO.load

FileIO.load — Method.

• load(filename) loads the contents of a formatted file, trying to infer

the format from filename and/or magic bytes in the file.

• load(strm) loads from an IOStream or similar object. In this case,

the magic bytes are essential.

• load(File(format"PNG",filename)) specifies the format directly, andbypasses inference.

• load(f; options...) passes keyword arguments on to the loader.

Page 262: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

22.11. FILEIO.MAGIC 257

22.11 FileIO.magic

FileIO.magic — Method.

magic(fmt) returns the magic bytes of format fmt

22.12 FileIO.query

FileIO.query — Method.

query(filename) returns a File object with information about the formatinferred from the file’s extension and/or magic bytes.

22.13 FileIO.query

FileIO.query — Method.

query(io, [filename]) returns a Stream object with information aboutthe format inferred from the magic bytes.

22.14 FileIO.save

FileIO.save — Method.

• save(filename, data...) saves the contents of a formatted file,

trying to infer the format from filename.

• save(Stream(format"PNG",io), data...) specifies the format directly,and bypasses inference.

• save(f, data...; options...) passes keyword arguments on to thesaver.

22.15 FileIO.skipmagic

FileIO.skipmagic — Method.

skipmagic(s) sets the position of Stream s to be just after the magic bytes.For a plain IO object, you can use skipmagic(io, fmt).

22.16 FileIO.stream

FileIO.stream — Method.

stream(s) returns the stream associated with Stream s

Page 263: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

258 CHAPTER 22. FILEIO

22.17 FileIO.unknown

FileIO.unknown — Method.unknown(f) returns true if the format of f is unknown.

Page 264: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 23

ShowItLikeYouBuildIt

23.1 ShowItLikeYouBuildIt.showarg

ShowItLikeYouBuildIt.showarg — Method.

showarg(stream::IO, x)

Show x as if it were an argument to a function. This function is used in theprinting of “type summaries” in terms of sequences of function calls on objects.

The fallback definition is to print x as ::$(typeof(x)), representing argu-ment x in terms of its type. However, you can specialize this function for specifictypes to customize printing.

Example

A SubArray created as view(a, :, 3, 2:5), where a is a 3-dimensionalFloat64 array, has type

SubArray{Float64,2,Array{Float64,3},Tuple{Colon,Int64,UnitRange{Int64}},false}

and this type will be printed in the summary. To change the printing of thisobject to

view(::Array{Float64,3}, Colon(), 3, 2:5)

you could define

function ShowItLikeYouBuildIt.showarg(io::IO, v::SubArray)

print(io, "view(")

showarg(io, parent(v))

print(io, ", ", join(v.indexes, ", "))

print(io, ’)’)

end

259

Page 265: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

260 CHAPTER 23. SHOWITLIKEYOUBUILDIT

Note that we’re calling showarg recursively for the parent array type. Print-ing the parent as ::Array{Float64,3} is the fallback behavior, assuming nospecialized method for Array has been defined. More generally, this woulddisplay as

view(<a>, Colon(), 3, 2:5)

where <a> is the output of showarg for a.

This printing might be activated any time v is a field in some other container,or if you specialize Base.summary for SubArray to call summary build.

See also: summary build.

23.2 ShowItLikeYouBuildIt.summary build

ShowItLikeYouBuildIt.summary build — Function.

summary_build(A::AbstractArray, [cthresh])

Return a string representing A in terms of the sequence of function calls thatmight be used to create A, along with information about A’s size or indices andelement type. This function should never be called directly, but instead used tospecialize Base.summary for specific AbstractArray subtypes. For example, ifyou want to change the summary of SubArray, you might define

Base.summary(v::SubArray) = summary_build(v)

This function goes hand-in-hand with showarg. If you have defined a showargmethod for SubArray as in the documentation for showarg, then the summaryof a SubArray might look like this:

34 view(::Array{Float64,3}, :, 3, 2:5) with element type Float64

instead of this:

34 SubArray{Float64,2,Array{Float64,3},Tuple{Colon,Int64,UnitRange{Int64}},false}

The optional argument cthresh is a “complexity threshold”; objects withtype descriptions that are less complex than the specified threshold will beprinted using the traditional type-based summary. The default value is n+1,where n is the number of parameters in typeof(A). The complexity is calculatedwith type complexity. You can choose a cthresh of 0 if you want to ensurethat your showarg version is always used.

See also: showarg, type complexity.

Page 266: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

23.3. SHOWITLIKEYOUBUILDIT.TYPE COMPLEXITY 261

23.3 ShowItLikeYouBuildIt.type complexity

ShowItLikeYouBuildIt.type complexity — Method.

type_complexity(T::Type) -> c

Return an integer c representing a measure of the “complexity” of type T.For unnested types, c = n+1 where n is the number of parameters in type T.However, type complexity calls itself recursively on the parameters, so if theparameters have their own parameters then the complexity of the type will be(potentially much) higher than this.

Examples

# Array{Float64,2}

julia> a = rand(3,5);

julia> type_complexity(typeof(a))

3

julia> length(typeof(a).parameters)+1

3

# Create an object that has type:

# SubArray{Int64,2,Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}},Tuple{StepRange{Int64,Int64},Colon},false}

julia> r = reshape(1:9, 3, 3);

julia> v = view(r, 1:2:3, :);

julia> type_complexity(typeof(v))

15

julia> length(typeof(v).parameters)+1

6

The second example indicates that the total complexity of v’s type is con-siderably higher than the complexity of just its “outer” SubArray type.

Page 267: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 24

CoordinateTransformations

24.1 CoordinateTransformations.cameramap

CoordinateTransformations.cameramap — Method.

cameramap()

cameramap(scale)

cameramap(scale, offset)

Create a transformation that takes points in real space (e.g. 3D) and projectsthem through a perspective transformation onto the focal plane of an ideal(pinhole) camera with the given properties.

The scale sets the scale of the screen. For a standard digital camera, thiswould be scale = focal length / pixel size. Non-square pixels are sup-ported by providing a pair of scales in a tuple, scale = (scale x, scale y).Positive scales represent a camera looking in the +z axis with a virtual screenin front of the camera (the x,y coordinates are not inverted compared to 3Dspace). Note that points behind the camera (with negative z component) willbe projected (and inverted) onto the image coordinates and it is up to the userto cull such points as necessary.

The offset = (offset x, offset y) is used to define the origin in theimaging plane. For instance, you may wish to have the point (0,0) represent thetop-left corner of your imaging sensor. This measurement is in the units afterapplying scale (e.g. pixels).

(see also PerspectiveMap)

24.2 CoordinateTransformations.compose

CoordinateTransformations.compose — Method.

compose(trans1, trans2)

trans1 trans2

262

Page 268: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

24.3. COORDINATETRANSFORMATIONS.RECENTER 263

Take two transformations and create a new transformation that is equivalentto successively applying trans2 to the coordinate, and then trans1. By defaultwill create a ComposedTransformation, however this method can be overloadedfor efficiency (e.g. two affine transformations naturally compose to a single affinetransformation).

24.3 CoordinateTransformations.recenter

CoordinateTransformations.recenter — Method.

recenter(trans::Union{AbstractMatrix,Transformation}, origin::AbstractVector) -> ctrans

Return a new transformation ctrans such that point origin serves as theorigin-of-coordinates for trans. Translation by origin occurs both before andafter applying trans, so that if trans is linear we have

ctrans(origin) == origin

As a consequence, recenter only makes sense if the output space of transis isomorphic with the input space.

For example, if trans is a rotation matrix, then ctrans rotates space aroundorigin.

24.4 CoordinateTransformations.transform deriv

CoordinateTransformations.transform deriv — Method.

transform_deriv(trans::Transformation, x)

A matrix describing how differentials on the parameters of x flow throughto the output of transformation trans.

24.5 CoordinateTransformations.transform deriv params

CoordinateTransformations.transform deriv params — Method.

transform_deriv_params(trans::AbstractTransformation, x)

A matrix describing how differentials on the parameters of trans flow throughto the output of transformation trans given input x.

Page 269: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 25

Polynomials

25.1 Polynomials.coeffs

Polynomials.coeffs — Method.coeffs(p::Poly): return coefficient vector [a 0, a 1, . . . , a n]

25.2 Polynomials.degree

Polynomials.degree — Method.degree(p::Poly): return degree of polynomial p

25.3 Polynomials.poly

Polynomials.poly — Function.

• poly(r::AbstractVector): Construct a polynomial from its roots. Thisis in contrast to the Poly constructor, which constructs a polynomial fromits coefficients.

Example:

## Represents (x-1)*(x-2)*(x-3)

poly([1,2,3]) # Poly(-6 + 11x - 6x^2 + x^3)

25.4 Polynomials.polyder

Polynomials.polyder — Function.

• polyder(p::Poly): Differentiate the polynomial p term by term. Theorder of the resulting polynomial is one lower than the order of p.

264

Page 270: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

25.5. POLYNOMIALS.POLYFIT 265

Example:

polyder(Poly([1, 3, -1])) # Poly(3 - 2x)

25.5 Polynomials.polyfit

Polynomials.polyfit — Function.polyfit(x, y, n=length(x)-1, sym=:x ): Fit a polynomial of degree n

through the points specified by x and y where ‘n <= length(x)

• 1using least squares fit. Whenn=length(x)-1‘ (the default), the

interpolating polynomial is returned. The optional fourth argument can beused to pass the symbol for the returned polynomial.

Example:

xs = linspace(0, pi, 5)

ys = map(sin, xs)

polyfit(xs, ys, 2)

Original by ggggggggg More robust version by Marek Peca [email protected]

(1. no exponentiation in system matrix construction, 2. QR least squares)

25.6 Polynomials.polyint

Polynomials.polyint — Method.

• polyint(p::Poly, k::Number=0): Integrate the polynomial p term byterm, optionally adding constant term k. The order of the resulting poly-nomial is one higher than the order of p.

Examples:

polyint(Poly([1, 0, -1])) # Poly(x - 0.3333333333333333x^3)

polyint(Poly([1, 0, -1]), 2) # Poly(2.0 + x - 0.3333333333333333x^3)

25.7 Polynomials.polyval

Polynomials.polyval — Method.

• polyval(p::Poly, x::Number): Evaluate the polynomial p at x usingHorner’s method.

Example:

polyval(Poly([1, 0, -1]), 0.1) # 0.99

For julia version 0.4 or greater, the call method can be used:

p = Poly([1,2,3])

p(4) # 57 = 1 + 2*4 + 3*4^2

Page 271: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

266 CHAPTER 25. POLYNOMIALS

25.8 Polynomials.roots

Polynomials.roots — Method.

• roots(p::Poly): Return the roots (zeros) of p, with multiplicity. Thenumber of roots returned is equal to the order of p. The returned rootsmay be real or complex.

Examples:

roots(Poly([1, 0, -1])) # [-1.0, 1.0]

roots(Poly([1, 0, 1])) # [0.0+1.0im, 0.0-1.0im]

roots(Poly([0, 0, 1])) # [0.0, 0.0]

roots(poly([1,2,3,4])) # [1.0,2.0,3.0,4.0]

25.9 Polynomials.variable

Polynomials.variable — Function.Return the indeterminate of a polynomial, x.

• variable(p::Poly): return variable of p as a Poly object.

• variable(T<:Number, [:x]): return poly one(T)*x

• variable([var::Symbol]): return polynomial 1x over Float64.

Page 272: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 26

Interpolations

26.1 Base.scale

Base.scale — Method.scale(itp, xs, ys, ...) scales an existing interpolation object to allow

for indexing using other coordinate axes than unit ranges, by wrapping theinterpolation object and transforming the indices from the provided axes ontounit ranges upon indexing.

The parameters xs etc must be either ranges or linspaces, and there must beone coordinate range/linspace for each dimension of the interpolation object.

For every NoInterp dimension of the interpolation object, the range mustbe exactly 1:size(itp, d).

26.2 Interpolations.eachvalue

Interpolations.eachvalue — Method.eachvalue(sitp) constructs an iterator for efficiently visiting each grid

point of a ScaledInterpolation object in which a small grid is being “scaledup” to a larger one. For example, suppose you have a core BSpline objectdefined on a 5x7x4 grid, and you are scaling it to a 100x120x20 grid (vialinspace(1,5,100), linspace(1,7,120), linspace(1,4,20)). You can per-form interpolation at each of these grid points via

function foo!(dest, sitp)

i = 0

for s in eachvalue(sitp)

dest[i+=1] = s

end

dest

end

which should be more efficient than

267

Page 273: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

268 CHAPTER 26. INTERPOLATIONS

function bar!(dest, sitp)

for I in CartesianRange(size(dest))

dest[I] = sitp[I]

end

dest

end

26.3 Interpolations.extrapolate

Interpolations.extrapolate — Method.extrapolate(itp, fillvalue) creates an extrapolation object that re-

turns the fillvalue any time the indexes in itp[x1,x2,...] are out-of-bounds.

26.4 Interpolations.extrapolate

Interpolations.extrapolate — Method.extrapolate(itp, scheme) adds extrapolation behavior to an interpola-

tion object, according to the provided scheme.The scheme can take any of these values:

• Throw - throws a BoundsError for out-of-bounds indices

• Flat - for constant extrapolation, taking the closest in-bounds value

• Linear - linear extrapolation (the wrapped interpolation object must sup-port gradient)

• Reflect - reflecting extrapolation (indices must support mod)

• Periodic - periodic extrapolation (indices must support mod)

You can also combine schemes in tuples. For example, the scheme (Linear(),Flat()) will use linear extrapolation in the first dimension, and constant in thesecond.

Finally, you can specify different extrapolation behavior in different direc-tion. ((Linear(),Flat()), Flat()) will extrapolate linearly in the first di-mension if the index is too small, but use constant etrapolation if it is too large,and always use constant extrapolation in the second dimension.

Page 274: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 27

PolynomialFactors

27.1 Base.factor

Base.factor — Method.

Factor f Zx over the rationals (px + q).

Returns a dictionary with factors and multiplicities.

Examples:

x = variable(Int)

f = (x-1)^20 * (2x-3) * (x^5 - x - 1)

factor(f) ## return dictionary with keys (x-1), (2x-3), and (x^5 - x - 1)

f = (12x + 13) * (x-1) * (x^2 - 1) * (x^3 - 1)

factor(f) ## # Dictionary -1 + x, 13 + 12x, 1 + x, 1 + x + x^2

x = variable(BigInt)

f = (2x-1)^20*(x-2)^10*(2x-3)^10*(3x-4)^10

factor(f) # as expected

f = prod([x-i for i in 1:20])

factor(f)

R = big(2)^256

factor(x^2 - R)

x = variable(Rational{Int})

f = 1//2 * x^3 + 3//4 * x^2 + 4//5 *x

factor(f)

Notes:

269

Page 275: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

270 CHAPTER 27. POLYNOMIALFACTORS

Uses Zassenhaus’ algorithm 15.19 from Modern Computer Algebra By Joachimvon zur Gathen and Jrgen Gerhard (GG, [1]). There is some randomness in thealgorithm for factorization over a prime.

For this algorithm, factorization is done over a finite field using a “good”prime and then lifted using Hensel’s technique to a factorization over p^l, wherel is large enough that the modular factors can be used to determine the factorsover Z[x].

Factorization over a finite field can be done in different ways (Cantor &Zassenhaous, Berlekamp, Kaltofen & Shoup, . . . ). Figure 14.9 and the discus-sion on pages 381-2 in GG illustrate that none is optimal. This function doesnot aim for best possible, which would require implementing more algorithms,and follows the easier to implement Cantor & Zassenhaus. Some polynomialscan not be factored here, e.g., x^100 -1 as the primes needed get too big dueto a bound empoloyed. (the bound includes both the degree and the size of thecoefficients).

The other part of the factorization task is identifying factors from the fac-torization over p^l. Two approaches – a brute force approach of looking at allfactor combinations and the use of the LLL algorithm are both utilized. Thelatter for when there are more factors over Zp, the former when this numberis small. Neither is particularly speedy on the xˆ40-1 which factors into manylinear factors over Zp for the p found.

For faster, more able implementations accessible from within Julia, see SymPy.jlor Nemo.jl, for example.

[1] Modern Computer Algebra By Joachim von zur Gathen and Jrgen Ger-hard. Cambridge University Press, 785 pages

27.2 PolynomialFactors.factormod

PolynomialFactors.factormod — Method.Factor a polynomial f in Z[x] over Z/pZ[x], p a prime (not equal to 2).

A dictionary is returned. The keys are the irreducible factors over Zp as polynomials over the integers. The coefficients are centered about 0.

27.3 PolynomialFactors.rational roots

PolynomialFactors.rational roots — Method.Return all rational roots of a polynomial f in Z[x].

Page 276: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 28

JavaCall

28.1 Base.isnull

Base.isnull — Method.

isnull(obj::JavaMetaClass)

Checks if the passed JavaMetaClass is null or not

Args

• obj: The object of type JavaMetaClass

Returns

true if the passed object is null else false

28.2 Base.isnull

Base.isnull — Method.

isnull(obj::JavaObject)

Checks if the passed JavaObject is null or not

Args

• obj: The object of type JavaObject

Returns

true if the passed object is null else false

271

Page 277: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

272 CHAPTER 28. JAVACALL

28.3 JavaCall.getname

JavaCall.getname — Method.

getname(cls::JClass)

Returns the fully qualified name of the java class

Args

• cls: The JClass object

Returns

The fully qualified name of the java class

28.4 JavaCall.getname

JavaCall.getname — Method.

getname(method::JMethod)

Returns the fully qualified name of the java method

Args

• cls: The JClass method

Returns

The fully qualified name of the method

28.5 JavaCall.getparametertypes

JavaCall.getparametertypes — Method.

getparametertypes(method::JMethod)

Returns the parameter types of the java method

Args

• method: The java method object

Returns

Vector the parametertypes

Page 278: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

28.6. JAVACALL.GETRETURNTYPE 273

28.6 JavaCall.getreturntype

JavaCall.getreturntype — Method.

getreturntype(method::JMethod)

Returns the return type of the java methodArgs

• method: The java method object

ReturnsReturns the type of the return object as a JClass

28.7 JavaCall.listmethods

JavaCall.listmethods — Method.

listmethods(obj::JavaObject, name::AbstractString)

Lists the methods that are available on the java object passed. The methodsare filtered based on the name passed

Args

• obj: The java object

• name: The filter (e.g. method name)

ReturnsList of methods available on the java object and matching the name passed

28.8 JavaCall.listmethods

JavaCall.listmethods — Method.

listmethods(obj::JavaObject)

Lists the methods that are available on the java object passedArgs

• obj: The java object

ReturnsList of methods

Page 279: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 29

Libz

29.1 Libz.ZlibDeflateInputStream

Libz.ZlibDeflateInputStream — Method.

ZlibDeflateInputStream(input[; <keyword arguments>])

Construct a zlib deflate input stream to compress gzip/zlib data.Arguments

• input: a byte vector, IO object, or BufferedInputStream containing datato compress.

• bufsize::Integer=8192: input and output buffer size.

• gzip::Bool=true: if true, data is gzip compressed; if false, zlib com-pressed.

• level::Integer=6: compression level in 1-9.

• mem level::Integer=8: memory to use for compression in 1-9.

• strategy=Z DEFAULT STRATEGY: compression strategy; see zlib documen-tation.

29.2 Libz.ZlibDeflateOutputStream

Libz.ZlibDeflateOutputStream — Method.

ZlibDeflateOutputStream(output[; <keyword arguments>])

Construct a zlib deflate output stream to compress gzip/zlib data.Arguments

274

Page 280: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

29.3. LIBZ.ZLIBINFLATEINPUTSTREAM 275

• output: a byte vector, IO object, or BufferedInputStream to which com-pressed data should be written.

• bufsize::Integer=8192: input and output buffer size.

• gzip::Bool=true: if true, data is gzip compressed; if false, zlib com-pressed.

• level::Integer=6: compression level in 1-9.

• mem level::Integer=8: memory to use for compression in 1-9.

• strategy=Z DEFAULT STRATEGY: compression strategy; see zlib documen-tation.

29.3 Libz.ZlibInflateInputStream

Libz.ZlibInflateInputStream — Method.

ZlibInflateInputStream(input[; <keyword arguments>])

Construct a zlib inflate input stream to decompress gzip/zlib data.Arguments

• input: a byte vector, IO object, or BufferedInputStream containing com-pressed data to inflate.

• bufsize::Integer=8192: input and output buffer size.

• gzip::Bool=true: if true, data is gzip compressed; if false, zlib com-pressed.

• reset on end::Bool=true: on stream end, try to find the start of anotherstream.

29.4 Libz.ZlibInflateOutputStream

Libz.ZlibInflateOutputStream — Method.

ZlibInflateOutputStream(output[; <keyword arguments>])

Construct a zlib inflate output stream to decompress gzip/zlib data.Arguments

• output: a byte vector, IO object, or BufferedInputStream to which de-compressed data should be written.

• bufsize::Integer=8192: input and output buffer size.

• gzip::Bool=true: if true, data is gzip compressed; if false, zlib com-pressed.

Page 281: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

276 CHAPTER 29. LIBZ

29.5 Libz.adler32

Libz.adler32 — Function.

adler32(data)

Compute the Adler-32 checksum over the data input. data can be BufferedInputStreamor Vector{UInt8}.

29.6 Libz.crc32

Libz.crc32 — Function.

crc32(data)

Compute the CRC-32 checksum over the data input. data can be BufferedInputStreamor Vector{UInt8}.

Page 282: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 30

BusinessDays

30.1 BusinessDays.advancebdays

BusinessDays.advancebdays — Method.

advancebdays(calendar, dt, bdays_count)

Increments given date dt by bdays count. Decrements it if bdays count isnegative. bdays count can be a Int, Vector{Int} or a UnitRange.

Computation starts by next Business Day if dt is not a Business Day.

30.2 BusinessDays.bdays

BusinessDays.bdays — Method.

bdays(calendar, dt0, dt1)

Counts the number of Business Days between dt0 and dt1. Returns in-stances of Dates.Day.

Computation is always based on next Business Day if given dates are notBusiness Days.

30.3 BusinessDays.isbday

BusinessDays.isbday — Method.

isbday(calendar, dt)

Returns false for weekends or holidays. Returns true otherwise.

277

Page 283: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

278 CHAPTER 30. BUSINESSDAYS

30.4 BusinessDays.isholiday

BusinessDays.isholiday — Method.

isholiday(calendar, dt)

Checks if dt is a holiday based on a given calendar of holidays.calendar can be an instance of HolidayCalendar, a Symbol or an AbstractString.Returns boolean values.

30.5 BusinessDays.isweekday

BusinessDays.isweekday — Method.

isweekday(dt)

Returns true for Monday to Friday. Returns false otherwise.

30.6 BusinessDays.isweekend

BusinessDays.isweekend — Method.

isweekend(dt)

Returns true for Saturdays or Sundays. Returns false otherwise.

30.7 BusinessDays.listbdays

BusinessDays.listbdays — Method.

listbdays(calendar, dt0::Date, dt1::Date) Vector{Date}

Returns the list of business days between dt0 and dt1.

30.8 BusinessDays.listholidays

BusinessDays.listholidays — Method.

listholidays(calendar, dt0::Date, dt1::Date) Vector{Date}

Returns the list of holidays between dt0 and dt1.

30.9 BusinessDays.tobday

BusinessDays.tobday — Method.

tobday(calendar, dt; [forward=true])

Adjusts dt to next Business Day if it’s not a Business Day. If isbday(dt),returns dt.

Page 284: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 31

AxisAlgorithms

31.1 AxisAlgorithms.A ldiv B md!

AxisAlgorithms.A ldiv B md! — Method.A ldiv B md!(dest, F, src, dim) solves a tridiagonal system along di-

mension dim of src, storing the result in dest. Currently, F must be an LU-factorized tridiagonal matrix. If desired, you may safely use the same array forboth src and dest, so that this becomes an in-place algorithm.

31.2 AxisAlgorithms.A ldiv B md

AxisAlgorithms.A ldiv B md — Method.A ldiv B md(F, src, dim) solves F for slices b of src along dimension dim,

storing the result along the same dimension of the output. Currently, F mustbe an LU-factorized tridiagonal matrix or a Woodbury matrix.

31.3 AxisAlgorithms.A mul B md!

AxisAlgorithms.A mul B md! — Method.A mul B md!(dest, M, src, dim) computes M*x for slices x of src along

dimension dim, storing the result in dest. M must be an AbstractMatrix. Thisuses an in-place naive algorithm.

31.4 AxisAlgorithms.A mul B md

AxisAlgorithms.A mul B md — Method.A mul B md(M, src, dim) computes M*x for slices x of src along dimension

dim, storing the resulting vector along the same dimension of the output. M

must be an AbstractMatrix. This uses an in-place naive algorithm.

279

Page 285: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

280 CHAPTER 31. AXISALGORITHMS

31.5 AxisAlgorithms.A mul B perm!

AxisAlgorithms.A mul B perm! — Method.A mul B perm!(dest, M, src, dim) computes M*x for slices x of src along

dimension dim, storing the result in dest. M must be an AbstractMatrix. Thisuses permutedims to make dimension dim into the first dimension, performs astandard matrix multiplication, and restores the original dimension ordering.In many cases, this algorithm exhibits the best cache behavior.

31.6 AxisAlgorithms.A mul B perm

AxisAlgorithms.A mul B perm — Method.A mul B perm(M, src, dim) computes M*x for slices x of src along dimen-

sion dim, storing the resulting vector along the same dimension of the output.M must be an AbstractMatrix. This uses permutedims to make dimension dim

into the first dimension, performs a standard matrix multiplication, and restoresthe original dimension ordering. In many cases, this algorithm exhibits the bestcache behavior.

Page 286: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 32

LegacyStrings

32.1 LegacyStrings.utf16

LegacyStrings.utf16 — Function.

utf16(::Union{Ptr{UInt16},Ptr{Int16}} [, length])

Create a string from the address of a NUL-terminated UTF-16 string. Acopy is made; the pointer can be safely freed. If length is specified, the stringdoes not have to be NUL-terminated.

32.2 LegacyStrings.utf16

LegacyStrings.utf16 — Method.

utf16(s)

Create a UTF-16 string from a byte array, array of UInt16, or any otherstring type. (Data must be valid UTF-16. Conversions of byte arrays check fora byte-order marker in the first two bytes, and do not include it in the resultingstring.)

Note that the resulting UTF16String data is terminated by the NUL code-point (16-bit zero), which is not treated as a character in the string (so thatit is mostly invisible in Julia); this allows the string to be passed directly toexternal functions requiring NUL-terminated data. This NUL is appended au-tomatically by the utf16(s) conversion function. If you have a UInt16 array A

that is already NUL-terminated valid UTF-16 data, then you can instead useUTF16String(A) to construct the string without making a copy of the data andtreating the NUL as a terminator rather than as part of the string.

281

Page 287: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

282 CHAPTER 32. LEGACYSTRINGS

32.3 LegacyStrings.utf32

LegacyStrings.utf32 — Function.

utf32(::Union{Ptr{Char},Ptr{UInt32},Ptr{Int32}} [, length])

Create a string from the address of a NUL-terminated UTF-32 string. Acopy is made; the pointer can be safely freed. If length is specified, the stringdoes not have to be NUL-terminated.

32.4 LegacyStrings.utf32

LegacyStrings.utf32 — Method.

utf32(s)

Create a UTF-32 string from a byte array, array of Char or UInt32, or anyother string type. (Conversions of byte arrays check for a byte-order marker inthe first four bytes, and do not include it in the resulting string.)

Note that the resulting UTF32String data is terminated by the NUL code-point (32-bit zero), which is not treated as a character in the string (so thatit is mostly invisible in Julia); this allows the string to be passed directly toexternal functions requiring NUL-terminated data. This NUL is appended au-tomatically by the utf32(s) conversion function. If you have a Char or UInt32array A that is already NUL-terminated UTF-32 data, then you can instead useUTF32String(A) to construct the string without making a copy of the data andtreating the NUL as a terminator rather than as part of the string.

Page 288: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 33

NullableArrays

33.1 NullableArrays.allnull

NullableArrays.allnull — Method.

allnull(X)

Returns whether or not all the entries in X are null.

33.2 NullableArrays.anynull

NullableArrays.anynull — Method.

anynull(X)

Returns whether or not any entries of X are null.

33.3 NullableArrays.dropnull!

NullableArrays.dropnull! — Method.

dropnull!(X::AbstractVector)

Remove null entries of X in-place and return a Vector view of the unwrappedNullable entries. If no nulls are present, this is a no-op and X is returned.

33.4 NullableArrays.dropnull!

NullableArrays.dropnull! — Method.

dropnull!(X::NullableVector)

Remove null entries of X in-place and return a Vector view of the unwrappedNullable entries.

283

Page 289: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

284 CHAPTER 33. NULLABLEARRAYS

33.5 NullableArrays.dropnull

NullableArrays.dropnull — Method.

dropnull(X::AbstractVector)

Return a vector containing only the non-null entries of X, unwrapping Nullable

entries. A copy is always returned, even when X does not contain any null values.

33.6 NullableArrays.nullify!

NullableArrays.nullify! — Method.

nullify!(X::NullableArray, I...)

This is a convenience method to set the entry of X at index I to be null

33.7 NullableArrays.padnull!

NullableArrays.padnull! — Method.

padnull!(X::NullableVector, front::Integer, back::Integer)

Insert front null entries at the beginning of X and add back null entries atthe end of X. Returns X.

33.8 NullableArrays.padnull

NullableArrays.padnull — Method.

padnull(X::NullableVector, front::Integer, back::Integer)

return a copy of X with front null entries inserted at the beginning of thecopy and back null entries inserted at the end.

Page 290: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 34

ImageMetadata

34.1 ImageCore.data

ImageCore.data — Method.

data(img::ImageMeta) -> array

Extract the data from img, omitting the properties dictionary. array sharesstorage with img, so changes to one affect the other.

See also: properties.

34.2 ImageCore.spatialproperties

ImageCore.spatialproperties — Method.

spatialproperties(img)

Return a vector of strings, containing the names of properties that have beendeclared “spatial” and hence should be permuted when calling permutedims.Declare such properties like this:

img["spatialproperties"] = ["spacedirections"]

34.3 ImageMetadata.copyproperties

ImageMetadata.copyproperties — Method.

copyproperties(img::ImageMeta, data) -> imgnew

Create a new “image,” copying the properties dictionary of img but using thedata of the AbstractArray data. Note that changing the properties of imgnew

does not affect the properties of img.See also: shareproperties.

285

Page 291: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

286 CHAPTER 34. IMAGEMETADATA

34.4 ImageMetadata.properties

ImageMetadata.properties — Method.

properties(imgmeta) -> props

Extract the properties dictionary props for imgmeta. props shares storagewith img, so changes to one affect the other.

See also: data.

34.5 ImageMetadata.shareproperties

ImageMetadata.shareproperties — Method.

shareproperties(img::ImageMeta, data) -> imgnew

Create a new “image,” reusing the properties dictionary of img but using thedata of the AbstractArray data. The two images have synchronized properties;modifying one also affects the other.

See also: copyproperties.

Page 292: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 35

MbedTLS

35.1 MbedTLS.decrypt

MbedTLS.decrypt — Function.

decrypt(cipher, key, msg, [iv]) -> Vector{UInt8}Decrypt a message using the given cipher. The cipher can be specified as

• a generic cipher (like CIPHER AES)

• a specific cipher (like CIPHER AES 256 CBC)

• a Cipher object

key is the symmetric key used for cryptography, given as either a String or aVector{UInt8}. It must be the right length for the chosen cipher; for example,CIPHER AES 256 CBC requires a 32-byte (256-bit) key.

msg is the message to be encoded. It should either be convertible to a Stringor be a Vector{UInt8}.

iv is the initialization vector, whose size must match the block size of thecipher (eg, 16 bytes for AES) and correspond to the iv used by the encryptor.By default, it will be set to all zeros.

35.2 MbedTLS.digest

MbedTLS.digest — Function.

digest(kind::MDKind, msg::Vector{UInt8}, [key::Vector{UInt8}]) ->Vector{UInt8}

Perform a digest of the given type on the given message (a byte array),return a byte array with the digest.

If an optional key is given, perform an HMAC digest.

287

Page 293: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

288 CHAPTER 35. MBEDTLS

35.3 MbedTLS.digest!

MbedTLS.digest! — Function.digest!(kind::MDKind, msg::Vector{UInt8}, [key::Vector{UInt8}, ],

buffer::Vector{UInt8})In-place version of digest that stores the digest to buffer.It is the user’s responsibility to ensure that buffer is long enough to contain

the digest. get size(kind::MDKind) returns the appropriate size.

35.4 MbedTLS.encrypt

MbedTLS.encrypt — Function.encrypt(cipher, key, msg, [iv]) -> Vector{UInt8}Encrypt a message using the given cipher. The cipher can be specified as

• a generic cipher (like CIPHER AES)

• a specific cipher (like CIPHER AES 256 CBC)

• a Cipher object

key is the symmetric key used for cryptography, given as either a String or aVector{UInt8}. It must be the right length for the chosen cipher; for example,CIPHER AES 256 CBC requires a 32-byte (256-bit) key.

msg is the message to be encoded. It should either be convertible to a Stringor be a Vector{UInt8}.

iv is the initialization vector, whose size must match the block size of thecipher (eg, 16 bytes for AES). By default, it will be set to all zeros, which isnot secure. For security reasons, it should be set to a different value for eachencryption operation.

Page 294: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 36

Compose

36.1 Compose.circle

Compose.circle — Function.

circle(x, y, r)

Define a circle with its center at (x,y) and a radius of r.

36.2 Compose.circle

Compose.circle — Function.

circle(xs, ys, rs)

Arguments can be passed in arrays in order to perform multiple drawingoperations.

36.3 Compose.circle

Compose.circle — Method.

circle()

Define a circle in the center of the current context with a diameter equal tothe width of the context.

36.4 Compose.polygon

Compose.polygon — Function.

polygon(points)

Define a polygon. points is an array of (x,y) tuples that specify the cornersof the polygon.

289

Page 295: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

290 CHAPTER 36. COMPOSE

36.5 Compose.rectangle

Compose.rectangle — Function.

rectangle(x0, y0, width, height)

Define a rectangle of size widthxheight with its top left corner at the point(x, y).

36.6 Compose.rectangle

Compose.rectangle — Function.

rectangle(x0s, y0s, widths, heights)

Arguments can be passed in arrays in order to perform multiple drawingoperations at once.

36.7 Compose.rectangle

Compose.rectangle — Method.

rectangle()

Define a rectangle that fills the current context completely.

36.8 Compose.text

Compose.text — Function.

text(xs, ys, values [,halgins::HAlignment [,valgins::VAlignment [,rots::Rotation]]])

Arguments can be passed in arrays in order to perform multiple drawingoperations at once.

36.9 Compose.text

Compose.text — Function.

text(x, y, value [,halgin::HAlignment [,valgin::VAlignment [,rot::Rotation]]])

Draw the text value at the position (x,y) relative to the current context.The default alignment of the text is hleft vbottom. The vertical and hor-

izontal alignment is specified by passing hleft, hcenter or hright and vtop,vcenter or vbottom as values for halgin and valgin respectively.

Page 296: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 37

JuliaWebAPI

37.1 JuliaWebAPI.apicall

JuliaWebAPI.apicall — Method.Calls a remote api cmd with args... and data.... The response is format-

ted as specified by the formatter specified in conn.

37.2 JuliaWebAPI.fnresponse

JuliaWebAPI.fnresponse — Method.extract and return the response data as a direct function call would have

returned but throw error if the call was not successful.

37.3 JuliaWebAPI.fnresponse

JuliaWebAPI.fnresponse — Method.extract and return the response data as a direct function call would have

returned but throw error if the call was not successful.

37.4 JuliaWebAPI.httpresponse

JuliaWebAPI.httpresponse — Method.construct an HTTP Response object from the API response

37.5 JuliaWebAPI.httpresponse

JuliaWebAPI.httpresponse — Method.construct an HTTP Response object from the API response

291

Page 297: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

292 CHAPTER 37. JULIAWEBAPI

37.6 JuliaWebAPI.process

JuliaWebAPI.process — Method.start processing as a server

37.7 JuliaWebAPI.register

JuliaWebAPI.register — Method.Register a function as API call. TODO: validate method belongs to module?

Page 298: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 38

Clustering

38.1 Clustering.dbscan

Clustering.dbscan — Method.

dbscan(points, radius ; leafsize = 20, min_neighbors = 1, min_cluster_size = 1) -> clusters

Cluster points using the DBSCAN (density-based spatial clustering of ap-plications with noise) algorithm.

Arguments

• points: matrix of points

• radius::Real: query radius

Keyword Arguments

• leafsize::Int: number of points binned in each leaf node in the KDTree

• min neighbors::Int: minimum number of neighbors to be a core point

• min cluster size::Int: minimum number of points to be a valid cluster

Output

• Vector{DbscanCluster}: an array of clusters with the id, size core indicesand boundary indices

Example:

[] points = randn(3, 10000) clusters = dbscan(points, 0.05, minneighbors =3,minclustersize =20)clusterswithlessthan20pointswillbediscarded

293

Page 299: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

294 CHAPTER 38. CLUSTERING

38.2 Clustering.mcl

Clustering.mcl — Method.

mcl(adj::Matrix; [keyword arguments])::MCLResult

Identify clusters in the weighted graph using Markov Clustering Algorithm(MCL).

Arguments

• adj::Matrix{Float64}: adjacency matrix that defines the weighted graphto cluster

• add loops::Bool: whether edges of weight 1.0 from the node to itselfshould be appended to the graph (enabled by default)

• expansion::Number: MCL expansion constant (2)

• inflation::Number: MCL inflation constant (2.0)

• save final matrix::Bool: save final equilibrium state in the result, oth-erwise leave it empty; disabled by default, could be useful if MCL doesn’tconverge

• max iter::Integer: max number of MCL iterations

• tol::Number: MCL adjacency matrix convergence threshold

• display::Symbol: :none for no output or :verbose for diagnostic mes-sages

See original MCL implementation.

Page 300: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 39

BufferedStreams

39.1 BufferedStreams.anchor!

BufferedStreams.anchor! — Method.

Set the buffer’s anchor to its current position.

39.2 BufferedStreams.fillbuffer!

BufferedStreams.fillbuffer! — Method.

Refill the buffer, optionally moving and retaining part of the data.

39.3 BufferedStreams.isanchored

BufferedStreams.isanchored — Method.

Return true if the stream is anchored.

39.4 BufferedStreams.peek

BufferedStreams.peek — Method.

Return the next byte from the input stream without advancing the position.

39.5 BufferedStreams.peekbytes!

BufferedStreams.peekbytes! — Function.

Fills buffer with bytes from stream’s buffer without advancing the position.

Unless the buffer is empty, we do not re-fill it. Therefore the number of bytesread is limited to the minimum of nb and the remaining bytes in the buffer.

295

Page 301: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

296 CHAPTER 39. BUFFEREDSTREAMS

39.6 BufferedStreams.takeanchored!

BufferedStreams.takeanchored! — Method.Copy and return a byte array from the anchor up to, but not including the

current position, also removing the anchor.

39.7 BufferedStreams.upanchor!

BufferedStreams.upanchor! — Method.Remove and return a buffer’s anchor.

Page 302: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 40

GLM

40.1 GLM.update!

GLM.update! — Method.

update!{T<:FPVector}(r::GlmResp{T}, linPr::T)

Update the mean, working weights and working residuals, in r given a valueof the linear predictor, linPr.

40.2 GLM.wrkresp

GLM.wrkresp — Method.

wrkresp(r::GlmResp)

The working response, r.eta + r.wrkresid - r.offset.

40.3 StatsBase.deviance

StatsBase.deviance — Method.

deviance(obj::LinearModel)

For linear models, the deviance is equal to the residual sum of squares (RSS).

40.4 StatsBase.nobs

StatsBase.nobs — Method.

nobs(obj::LinearModel)

nobs(obj::GLM)

For linear and generalized linear models, returns the number of rows, or,when prior weights are specified, the sum of weights.

297

Page 303: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

298 CHAPTER 40. GLM

40.5 StatsBase.nulldeviance

StatsBase.nulldeviance — Method.

nulldeviance(obj::LinearModel)

For linear models, the deviance of the null model is equal to the total sumof squares (TSS).

40.6 StatsBase.predict

StatsBase.predict — Method.

predict(mm::AbstractGLM, newX::AbstractMatrix; offset::FPVector=Array(eltype(newX),0))

Form the predicted response of model mm from covariate values newX and,optionally, an offset.

Page 304: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 41

AxisArrays

41.1 AxisArrays.axes

AxisArrays.axes — Method.

axes(A::AxisArray) -> (Axis...)

axes(A::AxisArray, ax::Axis) -> Axis

axes(A::AxisArray, dim::Int) -> Axis

Returns the tuple of axis vectors for an AxisArray. If an specific Axis isspecified, then only that axis vector is returned. Note that when extracting asingle axis vector, axes(A, Axis{1})) is type-stable and will perform betterthan axes(A)[1].

For an AbstractArray without Axis information, axes returns the defaultaxes, i.e., those that would be produced by AxisArray(A).

41.2 AxisArrays.axisdim

AxisArrays.axisdim — Method.

axisdim(::AxisArray, ::Axis) -> Int

axisdim(::AxisArray, ::Type{Axis}) -> Int

Given an AxisArray and an Axis, return the integer dimension of the Axiswithin the array.

41.3 AxisArrays.axisnames

AxisArrays.axisnames — Method.

299

Page 305: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

300 CHAPTER 41. AXISARRAYS

axisnames(A::AxisArray) -> (Symbol...)

axisnames(::Type{AxisArray{...}}) -> (Symbol...)

axisnames(ax::Axis...) -> (Symbol...)

axisnames(::Type{Axis{...}}...) -> (Symbol...)

Returns the axis names of an AxisArray or list of Axises as a tuple of Sym-bols.

41.4 AxisArrays.axisvalues

AxisArrays.axisvalues — Method.

axisvalues(A::AxisArray) -> (AbstractVector...)

axisvalues(ax::Axis...) -> (AbstractVector...)

Returns the axis values of an AxisArray or list of Axises as a tuple of vectors.

Page 306: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 42

ComputationalResources

42.1 ComputationalResources.addresource

ComputationalResources.addresource — Method.

addresource(T)

Add T to the list of available resources. For example, addresource(OpenCLLibs)would indicate that you have a GPU and the OpenCL libraries installed.

42.2 ComputationalResources.haveresource

ComputationalResources.haveresource — Method.

haveresource(T)

Returns true if T is an available resource. For example, haveresource(OpenCLLibs)tests whether the OpenCLLibs have been added as an available resource. Thisfunction is typically used inside a module’s init function.

Example:[] The

initfunctionforMyPackage:functioninit()...otherinitializationcode,possiblysettingtheLOADPATHifhaveresource(OpenCLLibs)@evalusingMyPackageCLaseparatemodulecontainingOpenCLimplementationsendPutadditionalresourcecheckshere...otherinitializationcode,possiblycleaninguptheLOADPATHend

42.3 ComputationalResources.rmresource

ComputationalResources.rmresource — Method.

rmresource(T)

Remove T from the list of available resources. For example, rmresource(OpenCLLibs)would indicate that any future package loads should avoid loading their special-izations for OpenCL.

301

Page 307: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 43

DecisionTree

43.1 DecisionTree.apply adaboost stumps proba

DecisionTree.apply adaboost stumps proba — Method.

apply_adaboost_stumps_proba(stumps::Ensemble, coeffs, features, labels::Vector)

computes P(L=label|X) for each row in features. It returns a N row x

n labels matrix of probabilities, each row summing up to 1.col labels is a vector containing the distinct labels (eg. [“versicolor”, “vir-

ginica”, “setosa”]). It specifies the column ordering of the output matrix.

43.2 DecisionTree.apply forest proba

DecisionTree.apply forest proba — Method.

apply_forest_proba(forest::Ensemble, features, col_labels::Vector)

computes P(L=label|X) for each row in features. It returns a N row x

n labels matrix of probabilities, each row summing up to 1.col labels is a vector containing the distinct labels (eg. [“versicolor”, “vir-

ginica”, “setosa”]). It specifies the column ordering of the output matrix.

43.3 DecisionTree.apply tree proba

DecisionTree.apply tree proba — Method.

apply_tree_proba(::Node, features, col_labels::Vector)

computes P(L=label|X) for each row in features. It returns a N row x

n labels matrix of probabilities, each row summing up to 1.col labels is a vector containing the distinct labels (eg. [“versicolor”, “vir-

ginica”, “setosa”]). It specifies the column ordering of the output matrix.

302

Page 308: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 44

FixedSizeArrays

44.1 FixedSizeArrays.construct similar

FixedSizeArrays.construct similar — Method.

construct_similar(::Type{FSA}, elements::Tuple)

Construct FixedArray as similar as possible to FSA, but with shape given bythe shape of the nested tuple elements and with eltype equal to the promotedelement type of the nested tuple elements.

44.2 FixedSizeArrays.destructure

FixedSizeArrays.destructure — Method.Destructure the elements of an array A to create M=ndims(eltype(A)) ad-

ditional dimensions prepended to the dimensions of A. The returned array is aview onto the original elements; additional dimensions occur first for consistencywith the natural memory ordering.

For example, AbstractArray{F<:FixedArray{T,M,SIZE},N} appears as anAbstractArray{T,M+N} after destructuring.

44.3 FixedSizeArrays.similar type

FixedSizeArrays.similar type — Method.

similar_type(::Type{FSA}, [::Type{T}=eltype(FSA)], [sz=size(FSA)])

Given an array type FSA, element type T and size sz, return a FixedArray

subtype which is as similar as possible. similar type is used in the same spiritas Base.similar to store the results of map() operations, etc. (similar cannotwork here, because the types are generally immutable.)

By default, similar type introspects FSA to determine whether T and sz

can be used; if not a canonical FixedArray container is returned instead.

303

Page 309: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 45

AutoGrad

45.1 AutoGrad.grad

AutoGrad.grad — Function.

grad(fun, argnum=1)

Take a function fun(X...)->Y and return another function gfun(X...)->dXiwhich computes its gradient with respect to positional argument number argnum.The function fun should be scalar-valued. The returned function gfun takes thesame arguments as fun, but returns the gradient instead. The gradient has thesame type and size as the target argument which can be a Number, Array,Tuple, or Dict.

45.2 AutoGrad.gradcheck

AutoGrad.gradcheck — Method.

gradcheck(f, w, x...; kwargs...)

Numerically check the gradient of f(w,x...;o...) with respect to its firstargument w and return a boolean result.

The argument w can be a Number, Array, Tuple or Dict which in turn cancontain other Arrays etc. Only the largest 10 entries in each numerical gradientarray are checked by default. If the output of f is not a number, gradcheckconstructs and checks a scalar function by taking its dot product with a randomvector.

Keywords

• gcheck=10: number of largest entries from each numeric array in gradientdw=(grad(f))(w,x...;o...) compared to their numerical estimates.

• verbose=false: print detailed messages if true.

304

Page 310: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

45.3. AUTOGRAD.GRADLOSS 305

• kwargs=[]: keyword arguments to be passed to f.

• delta=atol=rtol=cbrt(eps(w)): tolerance parameters. See isapprox

for their meaning.

45.3 AutoGrad.gradloss

AutoGrad.gradloss — Function.

gradloss(fun, argnum=1)

Another version of grad where the generated function returns a (gradi-ent,value) pair.

Page 311: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 46

HypothesisTests

46.1 HypothesisTests.pvalue

HypothesisTests.pvalue — Method.[] pvalue(x::HypothesisTest; tail=:both)Compute the p-value for a given significance test.If tail is :both (default), then the p-value for the two-sided test is returned.

If tail is :left or :right, then a one-sided test is performed.

46.2 HypothesisTests.testname

HypothesisTests.testname — Method.[] testname(::HypothesisTest)Returns the string value. E.g. “Binomial test”, “Sign Test”

46.3 StatsBase.confint

StatsBase.confint — Function.[] function confint(x::HypothesisTest, alpha::Float64=0.05; tail=:both, method=:clopperpearson)

Compute a confidence interval with coverage 1-alpha for multinomial pro-portions using one of the following methods. Possible values for method are:

Sison, Glaz intervals :sison glaz (default): Bootstrap intervals :bootstrap :Quesenberry, Hurst intervals :quesenberry hurst : Gold intervals :gold (Asymp-totic simultaneous intervals):

46.4 StatsBase.confint

StatsBase.confint — Function.[] function confint(x::HypothesisTest, alpha::Float64=0.05; tail=:both)

306

Page 312: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

46.4. STATSBASE.CONFINT 307

Compute a confidence interval C with coverage 1-alpha.If tail is :both (default), then a two-sided confidence interval is returned. If

tail is :left or :right, then a one-sided confidence interval is returned

Page 313: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 47

Blosc

47.1 Blosc.compress

Blosc.compress — Function.

compress(data; level=5, shuffle=true, itemsize)

Return a Vector{UInt8} of the Blosc-compressed data, where data is anarray or a string.

The level keyword indicates the compression level (between 0=no compres-sion and 9=max), shuffle indicates whether to use Blosc’s shuffling precondi-tioner, and the shuffling preconditioner is optimized for arrays of binary itemsof size (in bytes) itemsize (defaults to sizeof(eltype(data)) for arrays andthe size of the code units for strings).

47.2 Blosc.compress!

Blosc.compress! — Function.

compress!(dest::Vector{UInt8}, src; kws...)

Like compress(src; kws...), but writes to a pre-allocated array dest ofbytes. The return value is the size in bytes of the data written to dest, or 0 ifthe buffer was too small.

47.3 Blosc.decompress!

Blosc.decompress! — Method.

decompress!(dest::Vector{T}, src::Vector{UInt8})

Like decompress, but uses a pre-allocated destination buffer dest, which isresized as needed to store the decompressed data from src.

308

Page 314: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

47.4. BLOSC.DECOMPRESS 309

47.4 Blosc.decompress

Blosc.decompress — Method.

decompress(T::Type, src::Vector{UInt8})

Return the compressed buffer src as an array of element type T.

Page 315: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 48

HttpServer

48.1 Base.run

Base.run — Method.run starts server

Functionality:

• Accepts incoming connections and instantiates each Client.

• Manages the client.id pool.

• Spawns a new Task for each connection.

• Blocks forever.

Method accepts following keyword arguments:

• host - binding address

• port - binding port

• ssl - SSL configuration. Use this argument to enable HTTPS support.

Can be either an MbedTLS.SSLConfig object that already has associatedcertificates, or a tuple of an MbedTLS.CRT (certificate) and MbedTLS.PKContext(private key)). In the latter case, a configuration with reasonable defaults willbe used.

• socket - named pipe/domain socket path. Use this argument to enableUnix socket support.

It’s available only on Unix. Network options are ignored.Compatibility:

• for backward compatibility use run(server::Server, port::Integer)

310

Page 316: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

48.2. BASE.WRITE 311

Example:

server = Server() do req, res

"Hello world"

end

# start server on localhost

run(server, host=IPv4(127,0,0,1), port=8000)

# or

run(server, 8000)

48.2 Base.write

Base.write — Method.Converts a Response to an HTTP response string

48.3 HttpServer.setcookie!

HttpServer.setcookie! — Function.Sets a cookie with the given name, value, and attributes on the given re-

sponse object.

Page 317: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 49

ImageTransformations

49.1 ImageTransformations.imresize

ImageTransformations.imresize — Method.

imresize(img, sz) -> imgr

Change img to be of size sz. This interpolates the values at sub-pixel loca-tions. If you are shrinking the image, you risk aliasing unless you low-pass filterimg first. For example:

= map((o,n)->0.75*o/n, size(img), sz)

kern = KernelFactors.gaussian() # from ImageFiltering

imgr = imresize(imfilter(img, kern, NA()), sz)

See also restrict.

49.2 ImageTransformations.restrict

ImageTransformations.restrict — Method.

restrict(img[, region]) -> imgr

Reduce the size of img by two-fold along the dimensions listed in region, orall spatial coordinates if region is not specified. It anti-aliases the image as itgoes, so is better than a naive summation over 2x2 blocks.

See also imresize.

312

Page 318: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 50

MacroTools

50.1 MacroTools.isdef

MacroTools.isdef — Method.Test for function definition expressions.

50.2 MacroTools.isexpr

MacroTools.isexpr — Method.

isexpr(x, ts...)

Convenient way to test the type of a Julia expression. Expression heads andtypes are supported, so for example you can call

isexpr(expr, String, :string)

to pick up on all string-like expressions.

50.3 MacroTools.namify

MacroTools.namify — Method.An easy way to get pull the (function/type) name out of expressions like

foo{T} or Bar{T} <: Vector{T}.

50.4 MacroTools.rmlines

MacroTools.rmlines — Method.

rmlines(x)

Remove the line nodes from a block or array of expressions.

313

Page 319: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

314 CHAPTER 50. MACROTOOLS

50.5 MacroTools.unblock

MacroTools.unblock — Method.

unblock(expr)

Remove outer begin blocks from an expression, if the block is redundant(i.e. contains only a single expression).

Page 320: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 51

NearestNeighbors

51.1 NearestNeighbors.injectdata

NearestNeighbors.injectdata — Method.

injectdata(datafreetree, data) -> tree

Returns the KDTree/BallTree wrapped by datafreetree, set up to usedata for the points data.

51.2 NearestNeighbors.inrange

NearestNeighbors.inrange — Function.

inrange(tree::NNTree, points, radius [, sortres=false]) -> indices

Find all the points in the tree which is closer than radius to points. Ifsortres = true the resulting indices are sorted.

51.3 NearestNeighbors.knn

NearestNeighbors.knn — Function.

knn(tree::NNTree, points, k [, sortres=false]) -> indices, distances

Performs a lookup of the k nearest neigbours to the points from the datain the tree. If sortres = true the result is sorted such that the results are inthe order of increasing distance to the point. skip is an optional predicate todetermine if a point that would be returned should be skipped.

315

Page 321: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 52

IJulia

52.1 IJulia.notebook

IJulia.notebook — Method.

notebook(; dir=homedir(), detached=false)

The notebook() function launches the Jupyter notebook, and is equivalentto running jupyter notebook at the operating-system command-line. The ad-vantage of launching the notebook from Julia is that, depending on how Jupyterwas installed, the user may not know where to find the jupyter executable.

By default, the notebook server is launched in the user’s home directory, butthis location can be changed by passing the desired path in the dir keywordargument. e.g. notebook(dir=pwd()) to use the current directory.

By default, notebook() does not return; you must hit ctrl-c or quit Ju-lia to interrupt it, which halts Jupyter. So, you must leave the Julia termi-nal open for as long as you want to run Jupyter. Alternatively, if you runnotebook(detached=true), the jupyter notebook will launch in the back-ground, and will continue running even after you quit Julia. (The only way tostop Jupyter will then be to kill it in your operating system’s process manager.)

316

Page 322: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 53

MappedArrays

53.1 MappedArrays.mappedarray

MappedArrays.mappedarray — Method.

mappedarray(f, A)

creates a view of the array A that applies f to every element of A. The viewis read-only (you can get values but not set them).

53.2 MappedArrays.mappedarray

MappedArrays.mappedarray — Method.

mappedarray((f, finv), A)

creates a view of the array A that applies f to every element of A. The inversefunction, finv, allows one to also set values of the view and, correspondingly,the values in A.

53.3 MappedArrays.of eltype

MappedArrays.of eltype — Method.

of_eltype(T, A)

of_eltype(val::T, A)

creates a view of A that lazily-converts the element type to T.

317

Page 323: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 54

StaticArrays

54.1 StaticArrays.similar type

StaticArrays.similar type — Function.

similar_type(static_array)

similar_type(static_array, T)

similar_type(array, ::Size)

similar_type(array, T, ::Size)

Returns a constructor for a statically-sized array similar to the input array(or type) static array/array, optionally with different element type T or sizeSize. If the input array is not a StaticArray then the Size is mandatory.

This differs from similar() in that the resulting array type may not bemutable (or define setindex!()), and therefore the returned type may need tobe constructed with its data.

Note that the (optional) size must be specified as a static Size object (sothe compiler can infer the result statically).

New types should define the signature similar type{A<:MyType,T,S}(::Type{A},::Type{T},::Size{S})if they wish to overload the default behavior.

318

Page 324: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 55

Mustache

55.1 Mustache.render

Mustache.render — Method.Render a set of tokens with a view, using optional io object to print or store.Arguments

• io::IO: Optional IO object.

• tokens: Either Mustache tokens, or a string to parse into tokens

• view: A view provides a context to look up unresolved symbols demar-cated by mustache braces. A view may be specified by a dictionary, amodule, a composite type, a vector, or keyword arguments.

55.2 Mustache.render from file

Mustache.render from file — Method.Renders a template from filepath and view. If it has seen the file before

then it finds the compiled MustacheTokens in TEMPLATES rather than callingparse a second time.

319

Page 325: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 56

ImageAxes

56.1 ImageAxes.istimeaxis

ImageAxes.istimeaxis — Method.

istimeaxis(ax)

Test whether the axis ax corresponds to time.

56.2 ImageAxes.timeaxis

ImageAxes.timeaxis — Method.

timeaxis(A)

Return the time axis, if present, of the array A, and nothing otherwise.

56.3 ImageCore.timedim

ImageCore.timedim — Method.

timedim(img) -> d::Int

Return the dimension of the array used for encoding time, or 0 if not usingan axis for this purpose.

Note: if you want to recover information about the time axis, it is generallybetter to use timeaxis.

320

Page 326: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 57

HttpParser

57.1 HttpParser.http method str

HttpParser.http method str — Method.Returns a string version of the HTTP method.

57.2 HttpParser.http parser execute

HttpParser.http parser execute — Method.Run a request through a parser with specific callbacks on the settings in-

stance.

57.3 HttpParser.http parser init

HttpParser.http parser init — Function.Intializes the Parser object with the correct memory.

57.4 HttpParser.parse url

HttpParser.parse url — Method.Parse a URL

321

Page 327: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 58

TiledIteration

58.1 TiledIteration.padded tilesize

TiledIteration.padded tilesize — Function.

padded_tilesize(T::Type, kernelsize::Dims, [ncache=2]) -> tilesize::Dims

Calculate a suitable tile size to approximately maximize the amount of pro-ductive work, given a stencil of size kernelsize. The element type of the arrayis T. Optionally specify ncache, the number of such arrays that you’d like tohave fit simultaneously in L1 cache.

This favors making the first dimension larger, since the first dimension cor-responds to individual cache lines.

Examplesjulia> padded tilesize(UInt8, (3,3)) (768,18)julia> padded tilesize(UInt8, (3,3), 4) (512,12)julia> padded tilesize(Float64, (3,3)) (96,18)julia> padded tilesize(Float32, (3,3,3)) (64,6,6)

322

Page 328: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 59

Juno

59.1 Juno.input

Juno.input — Method.

input() -> "..."

Prompt the user to input some text, and return it.

59.2 Juno.selector

Juno.selector — Method.

selector([xs...]) -> x

Allow the user to select one of the xs.xs should be an iterator of strings. Currently there is no fallback in other

environments.

59.3 Juno.structure

Juno.structure — Method.

structure(x)

Display x’s underlying representation, rather than using its normal displaymethod. For example, structure(:(2x+1)) displays the Expr object with itshead and args fields instead of printing the expression.

323

Page 329: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 60

ObjFileBase

60.1 ObjFileBase.sectionaddress

ObjFileBase.sectionaddress — Method.The address of the section in virtual memory.

60.2 ObjFileBase.sectionoffset

ObjFileBase.sectionoffset — Method.The offset of the section in the file.

60.3 ObjFileBase.sectionsize

ObjFileBase.sectionsize — Method.The size of the actual data contained in the section. This should exclude

any padding mandated by the file format e.g. due to alignment rules

324

Page 330: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 61

HttpCommon

61.1 HttpCommon.escapeHTML

HttpCommon.escapeHTML — Method.escapeHTML(i::AbstractString)Returns a string with special HTML characters escaped: &, <, >, “, ’

61.2 HttpCommon.parsequerystring

HttpCommon.parsequerystring — Method.parsequerystring(query::AbstractString)Convert a valid querystring to a Dict:

q = "foo=bar&baz=%3Ca%20href%3D%27http%3A%2F%2Fwww.hackershool.com%27%3Ehello%20world%21%3C%2Fa%3E"

parsequerystring(q)

# Dict{ASCIIString,ASCIIString} with 2 entries:

# "baz" => "<a href=’http://www.hackershool.com’>hello world!</a>"

# "foo" => "bar"

325

Page 331: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 62

Media

62.1 Media.getdisplay

Media.getdisplay — Method.

getdisplay(T)

Find out what output device T will display on.

62.2 Media.media

Media.media — Method.media(T) gives the media type of the type T. The default is Textual.

media(Gadfly.Plot) == Media.Plot

62.3 Media.setdisplay

Media.setdisplay — Method.

setdisplay([input], T, output)

Display T objects using output when produced by input.T is an object type or media type, e.g. Gadfly.Plot or Media.Graphical.

display(Editor(), Image, Console())

326

Page 332: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 63

Rotations

63.1 Rotations.isrotation

Rotations.isrotation — Function.

isrotation(r)

isrotation(r, tol)

Check whether r is a 33 rotation matrix, where r * r is within tol of theidentity matrix (using the Frobenius norm). (tol defaults to 1000 * eps(eltype(r)).)

63.2 Rotations.rotation between

Rotations.rotation between — Method.

rotation_between(from, to)

Compute the quaternion that rotates vector from so that it aligns with vectorto, along the geodesic (shortest path).

327

Page 333: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 64

Loess

64.1 Loess.loess

Loess.loess — Method.

loess(xs, ys, normalize=true, span=0.75, degreee=2)

Fit a loess model.Args: xs: A n by m matrix with n observations from m independent predic-

tors ys: A length n response vector. normalize: Normalize the scale of eachpredicitor. (default true when m > 1) span: The degree of smoothing, typi-cally in [0,1]. Smaller values result in smaller local context in fitting. degree:Polynomial degree.

Returns: A fit LoessModel.

328

Page 334: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 65

Parameters

65.1 Parameters.reconstruct

Parameters.reconstruct — Method.Make a new instance of a type with the same values as the input type except

for the fields given in the associative second argument or as keywords.[] type A; a; b end a = A(3,4) b = reconstruct(a, [(:b, 99)]) ==A(3,99)

65.2 Parameters.type2dict

Parameters.type2dict — Method.Transforms a type-instance into a dictionary.

julia> type T

a

b

end

julia> type2dict(T(4,5))

Dict{Symbol,Any} with 2 entries:

:a => 4

:b => 5

329

Page 335: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 66

LineSearches

66.1 LineSearches.bt3!

LineSearches.bt3! — Function.backtracking! is a backtracking line-search that uses a quadratic or cubic

interpolant to determine the reduction in step-size. E.g., if f() > f(0) + c f’(0),then the quadratic interpolant of f(0), f’(0), f() has a minimiser ’ in the openinterval (0, ). More strongly, there exists a factor = (c) such that ’ .

This is a modification of the algorithm described in Nocedal Wright (2nded), Sec. 3.5.

330

Page 336: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 67

WoodburyMatrices

67.1 WoodburyMatrices.liftFactor

WoodburyMatrices.liftFactor — Method.

liftFactor(A)

More stable version of inv(A). Returns a function which computs the inverseon evaluation, i.e. liftFactor(A)(x) is the same as inv(A)*x.

331

Page 337: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 68

Requests

68.1 Requests.save

Requests.save — Function.save(r::Response, path=".")

Saves the data in the response in the directory path. If the path is a direc-tory, then the filename is automatically chosen based on the response headers.

Returns the full pathname of the saved file.

332

Page 338: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 69

SimpleTraits

69.1 SimpleTraits.istrait

SimpleTraits.istrait — Method.This function checks whether a trait is fulfilled by a specific set of types.

istrait(Tr1{Int,Float64}) => return true or false

333

Page 339: JuliaPro v0.5.1.1 API Manual - Julia Computing · JuliaPro v0.5.1.1 API Manual March 8, 2017 Julia Computing Inc. info@juliacomputing.com

Chapter 70

Iterators

70.1 Iterators.ncycle

Iterators.ncycle — Method.

ncycle(iter, n)

An iterator that cycles through iter n times.

334