Engee documentation
Notebook

Documentation and documentation in Engee

Good documentation is the key to quality understanding and use of code. The Julia language makes it easy to use and create documentation out-of-the-box.

This notebook will cover:

  • getting help in .ngscript
  • getting help on the command line
  • creating your own documentation for
    • functions
    • global variables
    • structures
    • modules

The method of creating and connecting your own module will also be considered.

Getting Help in .ngscript

To get help in .ngscript you need to use the macro @doc

Consider getting help for sqrt.

Note the use of Markdown, $\LaTeX$ and syntax highlighting in the documentation.

In [ ]:
@doc sqrt
Out[0]:
sqrt(x)

Возвращает $\sqrt{x}$. Выдает ошибку DomainError при отрицательных аргументах типа Real. Используйте вместо этого комплексные отрицательные аргументы. Префиксный оператор эквивалентен sqrt.

См. также описание hypot.

Примеры

jldoctest;
julia> sqrt(big(81))
9.0

julia> sqrt(big(-81))
ERROR: DomainError with -81.0:
NaN result for non-NaN input.
Stacktrace:
 [1] sqrt(::BigFloat) at ./mpfr.jl:501
[...]

julia> sqrt(big(complex(-81)))
0.0 + 9.0im

julia> .√(1:4)
4-element Vector{Float64}:
 1.0
 1.4142135623730951
 1.7320508075688772
 2.0
sqrt(A::AbstractMatrix)

Если матрица A не имеет отрицательных вещественных собственных значений, вычисляет натуральный квадратный корень матрицы A, то есть уникальную матрицу $X$ с собственными значениями, имеющими положительную вещественную часть, так что $X^2 = A$. В противном случае возвращается ненатуральный квадратный корень.

Если матрица A является симметричной или эрмитовой, для вычисления квадратного корня используется ее разложение по собственным значениям (eigen) . Для таких матриц собственные значения λ, которые из-за ошибок округления кажутся слегка отрицательными, рассматриваются как нулевые. Более точно, матрицы со всеми собственными значениями ≥ -rtol*(max |λ|) рассматриваются как полубесконечные (выдающие эрмитов квадратный корень), а отрицательные собственные значения принимаются за нуль. rtol является именованным аргументом для sqrt (только для эрмитовых или вещественно-симметричных матриц), который по умолчанию имеет машинную точность, масштабированную на size(A,1).

В противном случае квадратный корень определяется с помощью метода Бьорка-Хаммарлинга [^BH83], который вычисляет комплексную форму Шура (schur), а затем — комплексный квадратный корень треугольного множителя. Если вещественный квадратный корень существует, используется расширение этого метода [^H87], которое вычисляет вещественную форму Шура, а затем — вещественный квадратный корень квазитреугольного множителя.

[^BH83]: Åke Björck and Sven Hammarling, "A Schur method for the square root of a matrix", Linear Algebra and its Applications, 52-53, 1983, 127-140. doi:10.1016/0024-3795(83)80010-X80010-X)

[^H87]: Nicholas J. Higham, "Computing real square roots of a real matrix", Linear Algebra and its Applications, 88-89, 1987, 405-430. doi:10.1016/0024-3795(87)90118-290118-2)

Примеры

jldoctest
julia> A = [4 0; 0 4]
2×2 Matrix{Int64}:
 4  0
 0  4

julia> sqrt(A)
2×2 Matrix{Float64}:
 2.0  0.0
 0.0  2.0

Getting help at the command line

Use a question mark to get help on the command line: ?

screenshot_2024_11_21_135151.png

😊😊😊😊😊 if you want to expand your knowledge about using the command line - read the document to the end 😊😊😊.

Creating your own documentation

Documenting functions.

In order to add your own documentation to a function, you must add a line containing the information about the function before the function name.

If the function description is long, it is recommended to use triple double quotes.

In [ ]:
"Краткое описание функции, здоровающейся с пользователем"
function user_greeting(username::String)
    return "Hello, $(username)!"
end
Out[0]:
user_greeting
In [ ]:
@doc user_greeting
Out[0]:

Краткое описание функции, здоровающейся с пользователем

Let's briefly consider why we need to use the characters \ and $ мы используем raw - литерал необработанных строк:

В LaTex мы используем $\nu$ для обозначения символа ню: $\{nu$

Здесь сразу может возникнуть множество проблем. Внутри " "

Therefore. "$\nu$" will not be able to be executed correctly. However, this problem can be solved by using raw-strings

In [ ]:
# "$\nu$" # вызовет ошибки
In [ ]:
@show raw"$\nu$";
raw"$\nu$" = "\$\\nu\$"
In [ ]:
@doc raw"""
Документация, содержащая:

1. Markdown:
    - маркеры списка
    - [внешние ссылки](https://engee.com/helpcenter/stable/ru/julia/stdlib/Markdown.html)

2. Встроенный $\LaTeX$ (inline) $\frac{\sqrt{\pi}}{2}$  и отдельной формулой:
```math
\int \limits_{-\infty}^\infty e^{-x^2}\,dx = \sqrt{\pi}
```
## Смотреть также

[`документирование`](https://engee.com/helpcenter/stable/ru/julia/manual/documentation.html
), [`функции`](https://engee.com/helpcenter/stable/ru/julia/manual/functions.html)
"""
function foo()
    return nothing
end
Out[0]:
foo
In [ ]:
@doc foo
Out[0]:

Документация, содержащая:

  1. Markdown:

  2. Встроенный $\LaTeX$ (inline) $\frac{\sqrt{\pi}}{2}$ и отдельной формулой:

$$ \int \limits_{-\infty}^\infty e^{-x^2}\,dx = \sqrt{\pi} $$

Смотреть также

документирование, функции

Documenting global variables

When using global variables, be aware of performance issues and the appropriateness of their use

Consider the case where multiple global variables can be documented with a single reference

In [ ]:
"Ускорение свободного падения"
g_Earth, g_Moon
const g_Earth::Float64 = 9.81
const g_Moon::Float64 = 1.62
Out[0]:
1.62

Now let's check that the same help exists for two variables at once:

In [ ]:
@doc g_Earth
Out[0]:

Ускорение свободного падения

In [ ]:
@doc g_Moon
Out[0]:

Ускорение свободного падения

Note that const means the constancy of the variable's type, but not its value.

  • If the type is changed, an ** ERROR** will be invoked
  • When changing to a value of the same type, WARNING will be called.
In [ ]:
# g_Moon = "Moon"
In [ ]:
println(g_Earth)
g_Earth = 32.
println(g_Earth)
9.81
32.0
WARNING: redefinition of constant Main.g_Earth. This may fail, cause incorrect answers, or produce other errors.

Documenting Structures

Suppose there is a set of identical shapes. The problem is to arrange the figures on the plane in the most compact way. Then the structure will contain centre of mass and angle of rotation of the figure relative to the horizontal. As default constructor we will choose GeomteryShape((x=0,y=0),α=0). You can read more about constructors in documentation.

In [ ]:
@doc """
GeometricShape((x=X,y=Y),α)

    Геометрическая фигура
- `center_of_mass`: (x=X,y=Y) - кортеж координат центра масс
- `orientation`: α - угол поворота фигуры относительно горизонтали
## Пример:
GeometricShape((x=1., y=2.), 3.)

## Возможные ошибки
1.
```julia-repl
julia> GeometricShape((4.,5.),6.)
ERROR: MethodError: no method matching GeometricShape(::Tuple{Float64, Float64}, ::Float64)

Closest candidates are:
  GeometricShape(::@NamedTuple{x::Float64, y::Float64}, ::Any)
```
**Решение:** в кортеже нужно явно указать имена полей: `GeometricShape((x=4., y=5.), 6.)`
2. 
```julia-repl
julia> GeometricShape((x=1,y=2),3.)
ERROR: MethodError: no method matching GeometricShape(::@NamedTuple{x::Int64, y::Int64}, ::Float64)

Closest candidates are:
  GeometricShape(::@NamedTuple{x::Float64, y::Float64}, ::Any)
```
**Решение:** передавайте в качетсве параметров значения типа `Float64`, а не `Int64`: GeometricShape((x=1.,y=2.),3.)
"""
struct GeometricShape
    center_of_mass::NamedTuple{(:x,:y),Tuple{Float64,Float64}}
    orientation::Float64
    GeometricShape() = new((x=0,y=0),0)  # конструктор по умолчанию
    GeometricShape((X,Y)::NamedTuple{(:x,:y),Tuple{Float64,Float64}},α)=new((x=X,y=Y),α)
end
GeometricShape
In [ ]:
GeometricShape((x=4.,y=5.),6.)
GeometricShape((x = 4.0, y = 5.0), 6.0)
In [ ]:
@doc GeometricShape

GeometricShape((x=X,y=Y),α)

Геометрическая фигура
  • center_of_mass: (x=X,y=Y) - кортеж координат центра масс
  • orientation: α - угол поворота фигуры относительно горизонтали

Пример:

GeometricShape((x=1., y=2.), 3.)

Возможные ошибки

julia> GeometricShape((4.,5.),6.)
ERROR: MethodError: no method matching GeometricShape(::Tuple{Float64, Float64}, ::Float64)

Closest candidates are:
  GeometricShape(::@NamedTuple{x::Float64, y::Float64}, ::Any)

Решение: в кортеже нужно явно указать имена полей: GeometricShape((x=4., y=5.), 6.)

julia> GeometricShape((x=1,y=2),3.)
ERROR: MethodError: no method matching GeometricShape(::@NamedTuple{x::Int64, y::Int64}, ::Float64)

Closest candidates are:
  GeometricShape(::@NamedTuple{x::Float64, y::Float64}, ::Any)

Решение: передавайте в качетсве параметров значения типа Float64, а не Int64: GeometricShape((x=1.,y=2.),3.)

In [ ]:
GeometricShape()
GeometricShape((x = 0.0, y = 0.0), 0.0)
In [ ]:
first_shape = GeometricShape((x=1.,y=2.),3.)
first_shape.center_of_mass.y
2.0

Note that objects of our structure are immutable after their construction. If the use of mutable objects is required, they must be of type mutable struct.

In [ ]:
# first_shape.orientation = 4. # ОШИБКА: нельзя менять уже созданный объект

Documenting macros

In [ ]:
"Макрос, здоровающийся с пользователем"
macro hellouser(username)  # создание макроса
println("Hello, $(username)!")
end

@hellouser "Peter"  # применение макроса
Hello, Peter!

To get help for a macro, you must first write @, and then enter the macro name: @macrosname

In [ ]:
@doc @hellouser
Out[0]:

Макрос, здоровающийся с пользователем

Creating and documenting a module

In the folder along with this example is the file TemperatureScales.jl. This file contains the module TemperatureScales.

To access its functions and variables, you need to

  1. Go to the folder using the command cd(path), where the executable file (documentating.ngscript) (@__DIR__) is located. The same path contains TemperatureScales.jl:
In [ ]:
@__DIR__
Out[0]:
"/user/Engee/Demos/Engee/Documentating"
In [ ]:
cd(@__DIR__)
  1. Include this module in our script: By executing the command include("Filename.jl"), julia will "include" the text from the file Filename.jl into our current script and execute it. (Look at the 1st line of the file TemperatureScales.jl). This means that objects from this file will become objects in our file.
In [ ]:
include("TemperatureScales.jl")
Greeting from TemperatureScales.jl!
Out[0]:
Main.TemperatureScales
In [ ]:
println(variable_from_TemperatureScales)
3

But our task is to use the module from this file. The module is created using the keyword module, and used using using or import.

In [ ]:
using .TemperatureScales

To find out what exactly this module does, let's call the module help:

In [ ]:
@doc TemperatureScales
Out[0]:

Модуль перевода температур. Поддерживает шкалы:

  • Фаренгейта
  • Цельсия

Основные функции:

fahr2cels, cels2fahr,

Let's find out how fahr2cels functions work:

In [ ]:
@doc fahr2cels
Out[0]:
fahr2cels(t_f::Real)

Преобразует число t_f из шкалы Фаренгейта в шкалу Цельсия по формуле

$$ \frac{5}{9}(t_f+32) $$

fahr2cels(t_f::String)

Сначала преобразует строку в число, затем конвертирует.

Extended help

Здесь мы можем указать более подробную документацию

As you can see, the fahr2cels help specifies 2 methods. The first when the argument is a number, and the second when the argument is a string.

Now go to the command prompt and run

? fahr2cels

Note the last line: Extended help is available from ??.

Now exit help mode (by deleting ?)

And now enter

?? fahr2cels

We now have an EXPANDED reference 😊😊😊😊.

Conclusions

Documentation in Engee is very flexible (Markdown, $\LaTeX$) and supports a large list of objects to be documented: functions, variables, structures, macros and modules.

The inclusion of a custom module in a script was examined.