\section{Introduction}

\subsection{Texture Tomography}
Texture tomography is a way of inverting tomographic X-ray diffraction data into local
orientation distribution functions (ODF) of diffracting crystallites.
It relies on a priori-knowledge of the crystal structure and from there
models diffraction patterns for comparision with the . For parameter optimization it refines
the coefficients of harmonic basis functions constructing the ODF.
This approach is particularly suited for polycrystalline materials
with relatively wide orientation distributions, such as biomineralized tissue.

For a detailed description of mathematical model and the experimental procedure
refer to 
Frewein, M. P. K., Mason, J., Maier, B., Colfen, H., Medjahed, A., Burghammer, 
M., Allain, M. \& Grünewald, T. A. (2024). IUCrJ, 11, 809-820. https://doi.org/10.1107/S2052252524006547

and references therein.

\subsection{Installation}

TexTOM was written and tested in Python 3.11 and in principle requires only a python installation (3.9 to 3.12) and a terminal.
It is conceived to be used in iPython through a terminal, but can be imported into scripts or jupyter notebooks.

The TexTOM core for reconstructions currently depends on external packages such as Scipy, Numba, H5py, Orix, pyFAI and Mumott.
We experienced issues with parallelisation due to multiple BLAS installations by Numpy and Scipy. We therefore recommend
properly setting up a single openblas installation as indicated below.

We recommend creating conda environment and installing the package via pip.
Install Anaconda or Miniconda (https://docs.anaconda.com/miniconda/install/) 
\begin{verbatim}
    conda create --name textom python=3.11
    conda activate textom
    conda install numpy scipy openblas
\end{verbatim}
then
\begin{verbatim}
    pip install textom
\end{verbatim}

We encountered crashes during visualization using matplotlib using the tkinter backend,
therefore we recommend using the qt backend if possible. It is available by installing e.g.
\begin{verbatim}
    pip install pyqt5
\end{verbatim}

\subsubsection{GPU drivers}
Two of the packages (pyFAI and Mumott) provide GPU support for their functionalities.
These require additional drivers such as Cudatoolkit for Nvidia graphics cards, which
can be installed via 
\begin{verbatim}
    conda install cudatoolkit
\end{verbatim}
for alignment via Mumott and
\begin{verbatim}
    pip install pyopencl
\end{verbatim}
for integration via pyFAI.
Please refer to the documentations of the respective packages and your hardware
to find out what drivers are required.
In case no drivers are found, the software will fall back to computation via CPU.

\subsubsection{Start}
To start TexTOM in iPython mode, make sure your environment is active and type \texttt{textom}.
All TexTOM core functions (sec \ref{sec:functions}) will be available in the namespace.

You can also import them into a script or jupyter notebook:
\begin{verbatim}
    from textom.textom import *
\end{verbatim}
Note that textom currently does not support graphical input via jupyter notebooks!

TexTOM Source code is available on:
\url{https://gitlab.fresnel.fr/textom/textom/}.



\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Configuration}
After installing or updating TexTOM, we recommend opening the configuration file primarily to set how many CPUs your machine has
for data processing. Type \texttt{textom\_config} in your terminal and it will open the config file in your standard
text editor. A standard config file will look like the following:
\begin{verbatim}
    import numpy as np # don't delete this line
    ##################################################

    # Define how many cores you want to use 
    # If this number is higher than the available cores on your system, 
    # it will fall back to the maximum number
    n_threads = 128 

    # Choose if you want to use a GPU for alignment
    use_gpu = False
    # needs cudatoolkit: pip install cudatoolkit

    # Choose your precision
    # recommended np.float64 for double or np.float32 for single precision
    # this mainly concerns data handling, critical parts of the code always use double precision
    data_type = np.float32

    # turn on wise phrases at the start of TexTOM
    fun_mode = False
\end{verbatim}
If \texttt{n\_threads} is larger than the available number, it will fall back to the maximum number of threads/cores available.
After making your changes, you can save the file and close it.
\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Handling of the TexTOM software}

TexTOM is conceived as a command line software in iPython.
Its high-level library (section \ref{sec:functions}) is aimed to be usable without
advanced knowledge in python programming.
Part of its user-interface consist of files created in the sample directory. In this directory
TexTOM organises intermediate results automatically. Any part of the analysis can therefore be
revisited and retraced.
Upon startup, TexTOM assumes that the sample directory is the one where the program is started,
so the recommended way is to type
\begin{verbatim}
    cd /path/to/my/sample/directory/
\end{verbatim}
prior to starting TexTOM via the command line.
Alternatively, you can set the sample directory globally via the command \texttt{set\_path('path')} 
after starting or importing TexTOM.

\begin{figure}[h!]
    \includegraphics[width=\textwidth]{graphics/textom_chart.pdf}
    \centering
    \caption{Structure of the sample directory and relevant functions.}
\end{figure}
The following chart shows the structure of the sample directory and its subdirectories (red).
It is recommended to start the analysis in an empty directory, the subdirectories will be
created automatically.

Blue files are .h5 data containers, created during the workflow. For compatibility it is not
recommended to create or modify these other than through the TexTOM pipeline.

White files are human-legible text files, that can be created or modified using a text editor or
a custom script. They will be created through user input during the execution of the function
in the main line in the graphic. 
If a .py or .txt file is present in the directory prior to calling the corresponding function,
the present file will be used instead of asking for user input. This is handy for analysing
a series of samples that share experimental parameters.

Green files are images for direct usage or export into other software for further analysis or visualization,
such as Paraview, Avizo, Dragonfly or standard image viewers.

The functions on the right hand side are printed in the order of a suggested workflow, as the arrows indicate.
There is some freedom in the order of doing these steps, as long as the requirements as shown
by the red arrows are respected. The state of the analysis can be checked either by
manually inspecting the directory or through the function \texttt{check\_state()}.

A help-menu is available directly in the command line. Typing \texttt{help('function\_name')} will
produce the docstring with instructions on the usage of the respective function.

Relevant functions:
\hyperref[fun:setpath]{set\_path('path')},
\hyperref[fun:checkstate]{check\_state()},
\hyperref[fun:help]{help('function\_name')}

\begin{flushright}
    \hyperref[toc]{ToC}
\end{flushright}

\newpage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Workflow}

\subsection{Data acquisition}
Recording data for texture tomography is a great challenge and can only be done at appropriate synchrotron beamlines.
This package contains a few scripts for the experiments but we recommend contacting 
a beamline scientist experienced in tensor/texture tomography or 
3D-XRD in order to create acquisition scripts suitable for the beamline.

Make sure to collect all necessary metadata for the analysis and store them together with the data in
container files such as \texttt{.h5}.

\begin{flushright}
    \hyperref[toc]{ToC}
\end{flushright}

\subsection{Data integration}\label{sec:integration}
The first step in data processing is integration, i.e. azimutal rebinning ("caking") of the 2D-carthesian detector images.
Here we rely on the pyFAI package (\url{https://pyfai.readthedocs.io}) but in principle other packages can be used as well,
if a similarly structure output h5 file is created.
This part already requires good knowledge of your data, as you do not want to miss any diffraction peaks when choosing the
integration range. We recommend to do a test-integration during the experiment, to set up the correct
.poni-file which is needed for the integration. This file defines the geometry of the experiment and can be
created using the command pyFAI-calib2. Make sure to also collect the correct detector mask and optionally files
for flatfield and darkcurrent correction if your detector requires them.

To start the integration, in your terminal navigate to a directory which will further contain all 
TexTOM analysis data (further labelled \texttt{sample\_dir}).
\begin{verbatim}
    cd /path/to/textom/sample_dir
\end{verbatim}
Then start TexTOM by typing textom in your terminal.
You can start the integration using the command \texttt{integrate()}, upon which a file containing all necessary
parameters will open:
\begin{verbatim}
    # Data path and names
    path_in = 'path/to/your/experiment/overview_file.h5' # .h5 file with links to the data
    h5_proj_pattern = 'mysample*.1' # projection names, * is a placeholder
    # .h5 internal paths:
    h5_data_path = 'measurement/eiger'
    h5_tilt_angle_path = 'instrument/positioners/tilt' # tilt angle
    h5_rot_angle_path = 'instrument/positioners/rot' # rotation angle
    h5_ty_path = 'measurement/dty' # horizontal position
    h5_tz_path = 'measurement/dtz' # vertical position
    h5_nfast_path = 'technique/dim0' # fast axis number of points
    h5_nslow_path = 'technique/dim1' # slow axis number of points
    h5_ion_path = 'measurement/ion' # photon counter if present else None
    
    # Parameters for pyFAI azimuthal integration
    rad_range = [0.01, 37] # radial range
    rad_unit = 'q_nm^-1' # radial parameter and unit ('q_nm^-1', ''2th_deg', etc)
    azi_range = [-180, 180] # azimuthal range in degree
    npt_rad = 100 # number of points radial direction
    npt_azi = 120 # number of points azimuthal direction
    npt_rad_1D = 2000 # number of points radial direction
    int_method=('bbox','csr','cython') # pyFAI integration methods
        # for GPU change 'cython' to 'opencl'
    poni_path = 'path/to/your/poni_file.poni'
    mask_path = 'path/to/your/mask.edf'
    polarisation_factor= 0.95 # polarisation factor, usually 0.95 or 0.99
    solidangle_correction = True
    flatfield_correction = None #or /path/to/file
    darkcurrent_correction = None #or /path/to/file
    
    # Integration mode
    mode = 2 # 1: 1D, 2: 2D, 3: both
    
    # Parallelisation
    n_tasks = 8 # number of integrations performed in parallel
    cores_per_task = 16 # size of the cluster that performs a single integration
    # set both values to 1 if GPU is used
\end{verbatim}
The first part contains information about your data. We assume that these are stored in \texttt{.h5} files as common practice
at the ESRF. The first line is the overview file that contains links to all datasets. In the second line you can
specify which files should be integrated using a pattern with a * serving as a placeholder for other characters.
In the following there are the \texttt{.h5} internal paths to the necessary metadata for TexTOM, which will be carried into the
integrated files. \texttt{h5\_nfast\_path} and \texttt{h5\_nslow\_path} are only relevant if the experiment was performed in scanning mode,
upon which all data of one projection will be in the same data array with the horizontal and vertical position not specified.
If the experiment was performed in continuous rotation (controt) mode, these parameters should be set to None.
The last parameter is optional for the measurement of an ionisation chamber or diode, which records the incoming photon
flux during the respective measurement.

Then choose the integration mode, 2D is required for TexTOM, 1D can be done additionally e.g. for diffraction tomography.

In the next block declare on how many CPUs you want to work parallely, the \texttt{n\_tasks} specifies how many files will be integrated
at the same time, \texttt{cores\_per\_task} means how many CPUs work on each task.

The last block are parameters for pyFAI, of particular importance are the radial range, which should cover your peaks
and the number of points (npt\_rad), which should be enough to resolve the individual peaks (although the code will
also handle overlapping peaks or peaks which are in a single bin to the cost of some information loss due to their averaging).
The required angular resolution depends on the sharpness of the features in the data in azimuthal direction,
keep in mind that it is recommended to use a similar angular resolution for the construction of orientation
distribution functions and diffractlets, where the computation time will scale with the power of 3 of the number
of angular sampling points \texttt{npt\_azi}.  
Furthermore, point to the data files you have recorded during your beam time and specify angular resolution etc.
File paths should be complete paths and don't need to be in the sample directory, nor need to be accessible
during the following steps.

Relevant functions:
\hyperref[fun:integrate]{integrate()}

\begin{flushright}
    \hyperref[toc]{ToC}
\end{flushright}

\subsection{Alignment}
% Data is aligned fully automatically using the function:
% \begin{verbatim}
%     align_data( 
%         pattern='.h5', sub_data='data_integrated', 
%         q_index_range=(0,5), q_range = False,
%         mode='optical_flow', crop_image=False, 
%         regroup_max=16,
%         redo_import=False, flip_fov=False, 
%         align_horizontal=True, align_vertical=True,
%         pre_rec_it = 5, pre_max_it = 5,
%         last_rec_it = 40, last_max_it = 5,
%           )
% \end{verbatim}
The first step of the alignment is the sorting of the data. 

Go to the \texttt{data\_integrated/} or \texttt{data\_integrated\_1d/} directory created by the integration script
and make sure that all .h5 files are valid datasets, which you 
want to use for the reconstruction (other file extensions will be ignored). 
Move files that you don't want to use to a subfolder (e.g. named excluded).
The program uses all data in the \texttt{sub\_data directory} with pattern in the filename.
By default it uses data in \texttt{data\_integrated/}, you can use others by typing e.g. \texttt{align\_data(sub\_data='data\_integrated\_1d'})

Next, choose the q-range you want to use for alignment. You can use array indices to select a range
using the \texttt{q\_index\_range parameter} or give a \texttt{q-range} directly in the units specified in the \texttt{radial\_units}
field in the data (this parameter has priority if specified). TexTOM will average over all data in this range 
and treat them as scalar tomographic data for alignment. We recommend using either the SAXS region of 
the sample or an intense peak with little azimuthal variation.

TexTOM uses the alignment code from the Mumott tensor tomography package, which contains 2 pipelines.
By default we use the optical flow alignment, but you can choose phase matching alignment in the parameters.
If you want to crop the projections, set the \texttt{crop\_image} parameter to the desired borders (e.g. ((0,-1),(10,-10))
for the full image in x-direction, while cropping 10 points at the top and bottom)
Take note that cropping only works with the phase matching alignment, which will be chosen automatically if 
crop\_image is defined.

The TexTOM alignment pipeline will downsample the data until arriving at the 
sampling defined by \texttt{regroup\_max}, by default 16, corresponding to a downsampling to blocks of 16x16 pixels.
Then the alignment will start at the lowest sampling, take the found values and proceed to the next highest until it reaches the
original sampling. This approach has proven efficient even for large samples, but can be omitted by setting \texttt{regroup\_max=1}.
For the remaining parameters see the description \hyperref[fun:aligndata]{below}.

When you start the alignment using \hyperref[fun:aligndata]{align\_data(...)}, it will open a file labelled geometry.py, which contains information about the
experimental setup. Most parameters are equivalent to the Mumott notation (\url{https://mumott.org/tutorials/inspect_data.html#Geometry}),
which defines the arrangement of sample, detector, rotation and tilt angles.

\begin{verbatim}
    ### base coordinate system: ###
    beam_direction = (1,0,0) # p in mumott
    transverse_horizontal = (0,1,0) # j in mumott
    transverse_vertical = (0,0,1) # k in mumott
    ################################ don't change

    # detector geometry: 
    flip_detector_ud=False 
    flip_detector_lr=False
    detector_direction_origin = (0,-1,0) # this conforms to standard pyFAI output
    detector_direction_positive_90 = (0,0,-1) # this conforms to standard pyFAI output

    # sample movements:
    inner_axis = (0,0,1) # inner rotation axis
    outer_axis = (0,1,0) # outer rotation axis
    scan_mode = 'line' #'column' # 'line_snake' # 'column_snake'
    flip_fov=False # flip fast and slow axis argument (for the case it was defined the reverse way in the integrated data files)

    # For calculating projectors:
    Dbeam = 0.3 # beam size in um (FWHM)
    Dstep = 0.5 # scanning step size in um
\end{verbatim}

When you close and save the file, it will be automatically stored in \texttt{sample\_dir/analysis/ geometry.py} and in the following,
this file will be used. You can also create a geometry file in \texttt{sample\_dir/analysis/} prior to starting the alignment,
then this file will directly be used (e.g. when you have several samples from the same beamtime, copy the geometry file after
defining it for the first sample.). The default values are given for the configuration published in Frewein et al. IUCRJ (2024), an experiment
carried out at the ESRF, ID13 EH3 nanobeam instrument.

After aligning, the function will create the file \texttt{analysis/alignment\_result.h5} in the sample directory, which contains the shifts found
in the process. Refer to this file for checking sinograms and tomograms after alignment.
You can also use the function \texttt{check\_alignment\_consistency()} to check if there are projections which deviate from the
model. Inspect them and their agreement with the data using \texttt{check\_alignment\_projection(g)}, where g is an integer number
corresponding to the projection number. This number \texttt{g} is assigned after sorting the data files alphabetically.
The x-axis label in the plot shown by \texttt{check\_alignment\_consistency()} uses the same labelling.

If you choose to add, remove or change data or changing the q-range after doing an alignment, redo the alignment with the
setting redo\_import=True.
Else it will use the changes you made. If you just want to change the number of integrations or the regrouping,
this is not necessary.

Relevant functions:
\hyperref[fun:aligndata]{align\_data(...)}, 
\hyperref[fun:checkalignmentconsistency]{check\_alignment\_consistency()},
\hyperref[fun:checkalignmentprojection]{check\_alignment\_projection(g)}

\begin{flushright}
    \hyperref[toc]{ToC}
\end{flushright}

\subsection{Model}
Next you have to calculate the model, which consists of 2 parts: Diffractlets and Projectors.

Diffractlets are calculated from the crystal structure given by a \texttt{.cif} file, you have to provide.
When you start the model calculation using \texttt{make\_model()}, you will receive another file to edit (\texttt{crystal.py}), containing
information about the location of your \texttt{.cif} file, X-ray energy, $q$-range and desired angular resolution.
Save the file and it will be copied to \texttt{sample\_dir/analysis/ crystal.py}.
The function will create the file diffractlets\_hsh.h5, containing the diffractlets. 
If \texttt{sample\_dir/analysis/} contains already a \texttt{diffractlets\_hsh.h5} file, it will use this without asking.

If you start calculating diffractlets, a window will appear with a simulated powder pattern and the integrated intensity
over one projection as comparison. Check if the powder pattern corresponds to your data and adapt the cif file accordingly
if it is not the case. In particular, it might be necessary to adapt lattice parameters in case of a heavily strained sample.
You can adapt some parameters in the crystal.py file for better visibility and to adapt the powder pattern:
\texttt{q\_range} lets you cut away the SAXS region, which might give you a too high y-limit in the figure.
Increasing \texttt{cutoff\_structure\_factor} allows you to exclude low intensity peaks.
You might need to adapt \texttt{max\_hkl} if you expect peaks with higher Miller indices than the given number.

Note that all visible peaks in this window will be calculated as diffractlets. Later, you will be able to choose
which ones will actually be used for optimization.

Once you adapted the parameters, you can close the figure and state that you're not happy and it will replot the window.

\begin{verbatim}
    import numpy as np
    ## Define diffraction-related parameters:
    # x-ray energy in keV
    E_keV = 15.2
    # q range for fitting: (lower,upper) boundary in nm^-1
    q_range = (10,35)
    # path to crystal cif file
    cifPath = 'BaCO3.cif'
    # parameters for diffractlet calculation
    cutoff_structure_factor=1e-4
    max_hkl=4

    odf_mode = 'hsh' # 'grid' # 
    grid_resolution = 15 # degree # ignored if hsh
    hsh_max_order = 12 # ignored if gridbased
\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

The projectors contain information on which voxels contribute to which pixel in the data and
are thus depend on a finished alignment. Once you finished the alignment you can start calculating the projectors,
which requires some more user input for masking the sample. The program will open a histogram of voxels based on the
tomogram resulting from alignment. Choose the lower cutoff to mask out voxels with low or zero density of crystallites,
upon which the resulting object will automatically be smoothed and holes inside the structure will be filed.
You will be shown a 3D outline of the sample.

After processing, this will create a file \texttt{analysis/projectors.h5}, which is used in further processing of this specific sample.

\begin{figure}[h!]
    \includegraphics[width=\textwidth]{graphics/textom_input_projectors.pdf}
    \centering
    \caption{Textom input for masking during calculation of projectors. 
        a) choose the smallest region that surrounds your sample.
        b) choose the threshold in the tomogram below which you only expect background.
        }
\end{figure}

Note that choosing a threshold and thereby masking voxels can lead to artifacts, especially on the surface and in regions
with low crystalline material. It can be advantageous to choose a low threshold a the cost of longer processing times.

Relevant functions:
\hyperref[fun:makemodel]{make\_model()}
\hyperref[fun:checkpowderpattern]{check\_powder\_pattern()}
\hyperref[fun:showsampleoutline]{show\_sample\_outline()}
\hyperref[fun:listsamplerotations]{list\_sample\_rotations()}

\begin{flushright}
    \hyperref[toc]{ToC}
\end{flushright}

\subsection{Data Pre-processing}

When the model is ready, the data has to pass through a pre-processing step \hyperref[fun:preprocessdata]{preprocess\_data(...)}, 
where it is rebinned for each individual peak and outliers are removed. 
You will be asked to choose the q-ranges
around the peaks you would like to use for optimization, and to define the detector mask.
Text files will be created, these can be re-used for other samples and will be automatically chosen if present
in the \texttt{analysis/} directory.

\begin{figure}[h!]
    \includegraphics[width=\textwidth]{graphics/textom_input_data_import.pdf}
    \centering
    \caption{Textom input for choosing $q$-regions and masking pixels in the integrated images.
        a) Averaged data and calculated powder pattern with 5 peak regions marked for processing.
        b) Averaged data, azimuthally resoled. c) Data as before with pixels masked (red)
        }
\end{figure}

Also background subtraction is crucial. We provide several baseline subtraction schemes:

\texttt{'linear'} draws a straight line below each of the chosen peaks, from the last unmasked point to the next one.
In case of overlapping peaks, it will draw the line for all overlapping ones together, if all are chosen for the refinement.

\texttt{'chebyshev'} draws a Chebyshev polynomial baseline, fitting all data that are not masked as a peak.
This mode fails in some cases if not all peaks are chosen.
In this case, one can use \texttt{'chebyshev\_auto'}, which automatically masks peaks and draws the baseline.
For these modes, one might have to adapt the parameters in the \texttt{background\_subtraction.py} file to get the best results.

If no background subtraction is required, \texttt{'none'} is also an option.

To choose the appropriate background model, the program provides a selection of fits in a window before processing the data.
Upon inspecting the baselines, you can adapt the parameters in \texttt{background\_subtraction.py} and state that you are not happy,
to replot with the new parameters.

Relevant functions:
\hyperref[fun:preprocessdata]{preprocess\_data()}
\hyperref[fun:checkbaselines]{check\_baselines()}
\hyperref[fun:maskpeakregions]{mask\_peak\_regions()}
\hyperref[fun:maskdetectorpixels]{mask\_detector\_pixels()}

\begin{flushright}
    \hyperref[toc]{ToC}
\end{flushright}

\subsection{Optimization}
If all previous steps have been performed, you can start an optimization.
The basic function that starts a TexTOM optimization is simply called \hyperref[fun:optimize]{optimize()} and
performs a gradient-based optimization of the ODF parameters in each voxel.
It will save a \texttt{.h5} file with the found parameters and metadata on the optimization in the directory
\texttt{analysis/fits/}. Already performed optimizations can be loaded via \hyperref[fun:loadopt]{load\_opt(...)}.
An optimization can be stopped via \texttt{ctrl+c} anytime and will save the last values.

Relevant functions:
\hyperref[fun:optimize]{optimize()},

\hyperref[fun:listopt]{list\_opt()},
\hyperref[fun:loadopt]{load\_opt(...)},

\hyperref[fun:checklossfunction]{check\_lossfunction()},
\hyperref[fun:checkfitaverage]{check\_fit\_average()},
\hyperref[fun:checkfitrandom]{check\_fit\_random(...)},
\hyperref[fun:checkresiduals]{check\_residuals()},

\hyperref[fun:checkprojectionsaverage]{check\_projection\_average()},
\hyperref[fun:checkprojectionsresiduals]{check\_projection\_residuals()},
\hyperref[fun:checkprojectionsorientations]{check\_projection\_orientations()}

\begin{flushright}
    \hyperref[toc]{ToC}
\end{flushright}

\subsection{Analysis}
Upon obtaining a fit, you can \hyperref[fun:calculateorientationstatistics]{calculate\_orientation\_statistics()},
which will fill the preferred orientation (\texttt{g\_pref}, the orientation in axis-angle parameters; 
\texttt{a\_pref/b\_pref/c\_pref} are the corresponding unit cell directional vectors)
and standard deviation (\texttt{std}) per voxel into a global \texttt{results} dictionary.
It will also contain the (\texttt{scaling}) parameter, which corresponds to the amount of crystalline material
in the voxel.
You can check its current content via \hyperref[fun:listresultsloaded]{list\_results\_loaded()}.
There is also a simple segmentation algoritm \hyperref[fun:calculatesegments]{calculate\_segments(...)},
which calculates the misorientation between neighboring voxels
and segments on this base. The misorientation (\texttt{mori}) and indices of the segments will be saved
into results.

If your sample obeys a fibre texture or similar, with one of the axes aligned along a certain direction, you can
calculate nematic order parameters characterize them using \texttt{calculate\_order\_parameters(axis=(0,0,1))}.
Nematic directors and order parameters will be added to results.

Using the function \hyperref[fun:saveresults]{save\_results()} is necessary to save them to the hard drive.
They can later be inspected \hyperref[fun:listresults]{list\_results()} and reloaded \hyperref[fun:loadresults]{load\_results(...)}
for visualization.

There is also the possibility to export a file that is compatible with the fortran-style geometry used in paraview,
using the command \texttt{export\_paraview()}. The resulting \texttt{.xdmf}-file can be opened with paraview using the
"XDMF Reader" (just drag and drop the file into paraview and choose this one).

Relevant functions:
\hyperref[fun:calculateorientationstatistics]{calculate\_orientation\_statistics()},
\hyperref[fun:calculateorderparameters]{calculate\_order\_parameters(axis=(0,0,1))},
\hyperref[fun:calculatesegments]{calculate\_segments(...)},

\hyperref[fun:saveresults]{save\_results()},
\hyperref[fun:listresults]{list\_results()},
\hyperref[fun:listresultsloaded]{list\_results\_loaded()},
\hyperref[fun:loadresults]{load\_results(...)}
\hyperref[fun:exportparaview]{export\_paraview()}

\begin{flushright}
    \hyperref[toc]{ToC}
\end{flushright}

\subsection{Visualization}
The TexTOM package also contains some basic tool to visualize texture, in particular
one can show tomograms of all scalar quantities using \hyperref[fun:showvolume]{show\_volume('scalar',...)}.
This function gives the possibility inspect local ODFs upon clicking on a voxel.

Preferred orientations can be analogously visualized via inverse polefigures \hyperref[fun:showvolume]{show\_volume\_ipf(...)}

To show pole figures \hyperref[fun:showvoxelpolefigure]{show\_voxel\_polefigure(x,y,z,(h,k,l))}, it is necessary to know 
the indices of the desired voxels, to be found out via the former functions. You also have to provide the
Miller indices as an argument.

Refer to the documentation of the individual functions for saving and further processing.

Relevant functions:
\hyperref[fun:showvolume]{show\_volume('scalar',...)},
\hyperref[fun:showvolumeipf]{show\_volume\_ipf(...)},
\hyperref[fun:showsliceipf]{show\_slice\_ipf(...)},
\hyperref[fun:showvoxelodf]{show\_voxel\_odf(...)},
\hyperref[fun:showvoxelpolefigure]{show\_voxel\_polefigure(x,y,z,(h,k,l))},
\hyperref[fun:showhistogram]{show\_histogram(...)},
\hyperref[fun:showcorrelations]{show\_correlations(...)},
\hyperref[fun:saveimages]{save\_images(...)}

\section{Other Advices}
\subsection{Running TexTOM via a SSH connection}
You can use TexTOM through an SSH connection either with a script or via the iPython mode.
Input will be requested via text files and matplotlib figures.

To enable editing text files, a terminal based editor (e.g. Vim) will be used.
Familiarize yourself with its handling.

Make sure you enable graphical output by running 
\begin{verbatim}
    ssh -Y profile@server
\end{verbatim}

\section{Troubleshooting}

\subsection{I cannot write into the command line}
Sometimes a figure blocks the command line and will request more input after it is closed.
Try closing all figures to continue.

Never close any figures if a calculation is running, as it might lead to a crash of the program!


\begin{flushright}
    \hyperref[toc]{ToC}
\end{flushright}