Engee documentation
Notebook

Documentation and documentation in Engee

Good documentation is the key to a good understanding and use of the code.
The Julia language makes it convenient to use and create documentation out of the box.

This notebook will cover:

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

A way to create and connect 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 in the documentation, and a syntax hint.

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

@doc sqrt

Getting help on the command line

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

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 string containing the information about the function itself before the function name.

If the function description is long, it is recommended to use triple double кавычки.

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 look at why in order to use symbols \ and $ мы используем raw - литерал необработанных строк:

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

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

Therefore "$\nu$" it cannot be executed correctly. However, this problem can be solved by using raw-lines

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, keep in mind about the questions производительности and their expediency использования

Let's consider the case when several global variables can be documented with a single reference at once.

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 reference exists for two variables at once.:

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

@doc g_Earth

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

@doc g_Moon

Please note that const it means that the type of the variable is constant, but not its value.

  • When changing the type, an ERROR will be caused.**
  • When changing to a value of the same type, a WARNING will be displayed.
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

Let's have a set of identical shapes.

The task is to arrange the shapes on the plane in the most compact way. Then the structure will contain the center of mass and the angle of rotation of the figure relative to the horizontal.
As the [default constructor](https://ru.wikipedia.org/wiki/Constructor by silence) select GeomteryShape((x=0,y=0),α=0). You can read more about constructors in the 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

Please note that the objects of our structure are immutable after they are constructed. If mutable objects are required, they must be of the [mutable struct] type (https://engee.com/helpcenter/stable/ru/julia/manual/types.html#изменяемые-составные-типы ).

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

The TemperatureScales.jl file is located in the folder with this example. This file contains a module TemperatureScales.

To access its functions and variables, you must

  1. go to the folder using the command cd(path), where the executable file is located (documentating.ngscript) (@__DIR__). 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 running the command include("Filename.jl") julia will "include" the text from the file Filename.jl into our current script and executes it. (Look at the 1st line of the file TemperatureScales.jl). This means that objects from this file will become objects of 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 a keyword module, and is used with using or import.

In [ ]:
using .TemperatureScales

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

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 indicates 2 methods. The first is when the argument is a number, and the second is when the argument is a string.

Now go to the command prompt and run

? fahr2cels

Pay attention to the last line:
Extended help is available with ??.

Now exit the help mode (by deleting ?)

And now enter

?? fahr2cels

Now we have received EXTENDED help.

Conclusions

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

The inclusion of a custom module in the script was considered.