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, and syntax highlighting in the documentation.

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

@doc sqrt

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

@doc user_greeting

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

В LaTex мы используем $\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]:

@doc foo

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

@doc g_Earth

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

@doc g_Moon

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

@doc GeometricShape

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

@doc @hellouser

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

@doc TemperatureScales

Let's find out how fahr2cels functions work:

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

@doc fahr2cels

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

Now we have an EXPANDED reference 😊😊😊😊.

Conclusions

Documentation in Engee is very flexible (Markdown, ) 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.