Skip to content

utils

formatting

chapter(title)

Formats a chapter header with bold magenta text, uppercase, and padding.

Source code in src/easydiffraction/utils/formatting.py
11
12
13
14
15
16
17
18
19
def chapter(title: str) -> str:
    """Formats a chapter header with bold magenta text, uppercase, and padding."""
    full_title = f' {title.upper()} '
    pad_len = (WIDTH - len(full_title)) // 2
    padding = SYMBOL * pad_len
    line = f'{Fore.LIGHTMAGENTA_EX + Style.BRIGHT}{padding}{full_title}{padding}{Style.RESET_ALL}'
    if len(line) < WIDTH:
        line += SYMBOL
    return f'\n{line}'

error(title)

Formats an error message with red text.

Source code in src/easydiffraction/utils/formatting.py
43
44
45
def error(title: str) -> str:
    """Formats an error message with red text."""
    return f'\n{Fore.LIGHTRED_EX}Error{Style.RESET_ALL}\n{title}'

info(title)

Formats an info message with cyan text.

Source code in src/easydiffraction/utils/formatting.py
53
54
55
def info(title: str) -> str:
    """Formats an info message with cyan text."""
    return f'\nℹ️ {Fore.LIGHTCYAN_EX}Info{Style.RESET_ALL}\n{title}'

paragraph(title)

Formats a subsection header with bold blue text while keeping quoted text unformatted.

Source code in src/easydiffraction/utils/formatting.py
28
29
30
31
32
33
34
35
36
37
38
39
40
def paragraph(title: str) -> str:
    """Formats a subsection header with bold blue text while keeping quoted text unformatted."""
    import re

    parts = re.split(r"('.*?')", title)
    formatted = f'{Fore.LIGHTBLUE_EX + Style.BRIGHT}'
    for part in parts:
        if part.startswith("'") and part.endswith("'"):
            formatted += Style.RESET_ALL + part + Fore.LIGHTBLUE_EX + Style.BRIGHT
        else:
            formatted += part
    formatted += Style.RESET_ALL
    return f'\n{formatted}'

section(title)

Formats a section header with bold green text.

Source code in src/easydiffraction/utils/formatting.py
22
23
24
25
def section(title: str) -> str:
    """Formats a section header with bold green text."""
    full_title = f'*** {title.upper()} ***'
    return f'\n{Fore.LIGHTGREEN_EX + Style.BRIGHT}{full_title}{Style.RESET_ALL}'

warning(title)

Formats a warning message with yellow text.

Source code in src/easydiffraction/utils/formatting.py
48
49
50
def warning(title: str) -> str:
    """Formats a warning message with yellow text."""
    return f'\n⚠️ {Fore.LIGHTYELLOW_EX}Warning{Style.RESET_ALL}\n{title}'

utils

General utilities and helpers for easydiffraction.

download_from_repository(file_name, branch=None, destination='data', overwrite=False)

Download a data file from the EasyDiffraction repository on GitHub.

Parameters:

Name Type Description Default
file_name str

The file name to fetch (e.g., "NaCl.gr").

required
branch str | None

Branch to fetch from. If None, uses DATA_REPO_BRANCH.

None
destination str

Directory to save the file into (created if missing).

'data'
overwrite bool

Whether to overwrite the file if it already exists. Defaults to False.

False
Source code in src/easydiffraction/utils/utils.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def download_from_repository(
    file_name: str,
    branch: str | None = None,
    destination: str = 'data',
    overwrite: bool = False,
) -> None:
    """Download a data file from the EasyDiffraction repository on GitHub.

    Args:
        file_name: The file name to fetch (e.g., "NaCl.gr").
        branch: Branch to fetch from. If None, uses DATA_REPO_BRANCH.
        destination: Directory to save the file into (created if missing).
        overwrite: Whether to overwrite the file if it already exists. Defaults to False.
    """
    file_path = os.path.join(destination, file_name)
    if os.path.exists(file_path):
        if not overwrite:
            print(warning(f"File '{file_path}' already exists and will not be overwritten."))
            return
        else:
            print(warning(f"File '{file_path}' already exists and will be overwritten."))
            os.remove(file_path)

    base = 'https://raw.githubusercontent.com'
    org = 'easyscience'
    repo = 'diffraction-lib'
    branch = branch or DATA_REPO_BRANCH  # Use the global branch variable if not provided
    path_in_repo = 'tutorials/data'
    url = f'{base}/{org}/{repo}/refs/heads/{branch}/{path_in_repo}/{file_name}'

    pooch.retrieve(
        url=url,
        known_hash=None,
        fname=file_name,
        path=destination,
    )

get_value_from_xye_header(file_path, key)

Extracts a floating point value from the first line of the file, corresponding to the given key.

Parameters:

Name Type Description Default
file_path str

Path to the input file.

required
key str

The key to extract ('DIFC' or 'two_theta').

required

Returns:

Name Type Description
float

The extracted value.

Raises:

Type Description
ValueError

If the key is not found.

Source code in src/easydiffraction/utils/utils.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
def get_value_from_xye_header(file_path, key):
    """
    Extracts a floating point value from the first line of the file, corresponding to the given key.

    Parameters:
        file_path (str): Path to the input file.
        key (str): The key to extract ('DIFC' or 'two_theta').

    Returns:
        float: The extracted value.

    Raises:
        ValueError: If the key is not found.
    """
    pattern = rf'{key}\s*=\s*([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)'

    with open(file_path, 'r') as f:
        first_line = f.readline()

    match = re.search(pattern, first_line)
    if match:
        return float(match.group(1))
    else:
        raise ValueError(f'{key} not found in the header.')

is_github_ci()

Determines if the current process is running in GitHub Actions CI.

Returns:

Name Type Description
bool bool

True if the environment variable GITHUB_ACTIONS is set

bool

(Always "true" on GitHub Actions), False otherwise.

Source code in src/easydiffraction/utils/utils.py
104
105
106
107
108
109
110
111
112
def is_github_ci() -> bool:
    """
    Determines if the current process is running in GitHub Actions CI.

    Returns:
        bool: True if the environment variable ``GITHUB_ACTIONS`` is set
        (Always "true" on GitHub Actions), False otherwise.
    """
    return os.environ.get('GITHUB_ACTIONS') is not None

is_notebook()

Determines if the current environment is a Jupyter Notebook.

Returns:

Name Type Description
bool bool

True if running inside a Jupyter Notebook, False otherwise.

Source code in src/easydiffraction/utils/utils.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def is_notebook() -> bool:
    """
    Determines if the current environment is a Jupyter Notebook.

    Returns:
        bool: True if running inside a Jupyter Notebook, False otherwise.
    """
    if IPython is None:
        return False

    try:
        shell = get_ipython().__class__.__name__  # noqa: F821
        if shell == 'ZMQInteractiveShell':
            return True  # Jupyter notebook or qtconsole
        elif shell == 'TerminalInteractiveShell':
            return False  # Terminal running IPython
        else:
            return False  # Other type (unlikely)
    except NameError:
        return False  # Probably standard Python interpreter

is_pycharm()

Determines if the current environment is PyCharm.

Returns:

Name Type Description
bool bool

True if running inside PyCharm, False otherwise.

Source code in src/easydiffraction/utils/utils.py
 94
 95
 96
 97
 98
 99
100
101
def is_pycharm() -> bool:
    """
    Determines if the current environment is PyCharm.

    Returns:
        bool: True if running inside PyCharm, False otherwise.
    """
    return os.environ.get('PYCHARM_HOSTED') == '1'

render_cif(cif_text, paragraph_title)

Display the CIF text as a formatted table in Jupyter Notebook or terminal.

Source code in src/easydiffraction/utils/utils.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def render_cif(cif_text, paragraph_title) -> None:
    """
    Display the CIF text as a formatted table in Jupyter Notebook or terminal.
    """
    # Split into lines and replace empty ones with a '&nbsp;'
    # (non-breaking space) to force empty lines to be rendered in
    # full height in the table. This is only needed in Jupyter Notebook.
    if is_notebook():
        lines: List[str] = [line if line.strip() else '&nbsp;' for line in cif_text.splitlines()]
    else:
        lines: List[str] = [line for line in cif_text.splitlines()]

    # Convert each line into a single-column format for table rendering
    columns: List[List[str]] = [[line] for line in lines]

    # Print title paragraph
    print(paragraph_title)

    # Render the table using left alignment and no headers
    render_table(columns_data=columns, columns_alignment=['left'])

render_table(columns_data, columns_alignment, columns_headers=None, show_index=False, display_handle=None)

Renders a table either as an HTML (in Jupyter Notebook) or ASCII (in terminal), with aligned columns.

Parameters:

Name Type Description Default
columns_data list

List of lists, where each inner list represents a row of data.

required
columns_alignment list

Corresponding text alignment for each column (e.g., 'left', 'center', 'right').

required
columns_headers list

List of column headers.

None
show_index bool

Whether to show the index column.

False
Source code in src/easydiffraction/utils/utils.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def render_table(
    columns_data,
    columns_alignment,
    columns_headers=None,
    show_index=False,
    display_handle=None,
):
    """
    Renders a table either as an HTML (in Jupyter Notebook) or ASCII (in terminal),
    with aligned columns.

    Args:
        columns_data (list): List of lists, where each inner list represents a row of data.
        columns_alignment (list): Corresponding text alignment for each column (e.g., 'left', 'center', 'right').
        columns_headers (list): List of column headers.
        show_index (bool): Whether to show the index column.
    """

    # Use pandas DataFrame for Jupyter Notebook rendering
    if is_notebook():
        # Create DataFrame
        if columns_headers is None:
            df = pd.DataFrame(columns_data)
            df.columns = range(df.shape[1])  # Ensure numeric column labels
            columns_headers = df.columns.tolist()
            skip_headers = True
        else:
            df = pd.DataFrame(columns_data, columns=columns_headers)
            skip_headers = False

        # Force starting index from 1
        if show_index:
            df.index += 1

        # Replace None/NaN values with empty strings
        df.fillna('', inplace=True)

        # Formatters for data cell alignment and replacing None with empty string
        def make_formatter(align):
            return lambda x: f'<div style="text-align: {align};">{x}</div>'

        formatters = {col: make_formatter(align) for col, align in zip(columns_headers, columns_alignment)}

        # Convert DataFrame to HTML
        html = df.to_html(
            escape=False,
            index=show_index,
            formatters=formatters,
            border=0,
            header=not skip_headers,
        )

        # Add inline CSS to align the entire table to the left and show border
        html = html.replace(
            '<table class="dataframe">',
            '<table class="dataframe" '
            'style="'
            'border-collapse: collapse; '
            'border: 1px solid #515155; '
            'margin-left: 0.5em;'
            'margin-top: 0.5em;'
            'margin-bottom: 1em;'
            '">',
        )

        # Manually apply text alignment to headers
        if not skip_headers:
            for col, align in zip(columns_headers, columns_alignment):
                html = html.replace(f'<th>{col}', f'<th style="text-align: {align};">{col}')

        # Display or update the table in Jupyter Notebook
        if display_handle is not None:
            display_handle.update(HTML(html))
        else:
            display(HTML(html))

    # Use tabulate for terminal rendering
    else:
        if columns_headers is None:
            columns_headers = []

        indices = show_index
        if show_index:
            # Force starting index from 1
            indices = range(1, len(columns_data) + 1)

        table = tabulate(
            columns_data,
            headers=columns_headers,
            tablefmt='fancy_outline',
            numalign='left',
            stralign='left',
            showindex=indices,
        )

        print(table)

tof_to_d(tof, offset, linear, quad, quad_eps=1e-20)

Convert time-of-flight (TOF) to d-spacing using a quadratic calibration.

Model

TOF = offset + linear * d + quad * d²

The function
  • Uses a linear fallback when the quadratic term is effectively zero.
  • Solves the quadratic for d and selects the smallest positive, finite root.
  • Returns NaN where no valid solution exists.
  • Expects tof as a NumPy array; output matches its shape.

Parameters:

Name Type Description Default
tof ndarray

Time-of-flight values (µs). Must be a NumPy array.

required
offset float

Calibration offset (µs).

required
linear float

Linear calibration coefficient (µs/Å).

required
quad float

Quadratic calibration coefficient (µs/Ų).

required
quad_eps float

Threshold to treat quad as zero. Defaults to 1e-20.

1e-20

Returns:

Type Description
ndarray

np.ndarray: d-spacing values (Å), NaN where invalid.

Raises:

Type Description
TypeError

If tof is not a NumPy array or coefficients are not real numbers.

Source code in src/easydiffraction/utils/utils.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def tof_to_d(
    tof: np.ndarray,
    offset: float,
    linear: float,
    quad: float,
    quad_eps=1e-20,
) -> np.ndarray:
    """Convert time-of-flight (TOF) to d-spacing using a quadratic calibration.

    Model:
        TOF = offset + linear * d + quad * d²

    The function:
      - Uses a linear fallback when the quadratic term is effectively zero.
      - Solves the quadratic for d and selects the smallest positive, finite root.
      - Returns NaN where no valid solution exists.
      - Expects ``tof`` as a NumPy array; output matches its shape.

    Args:
        tof (np.ndarray): Time-of-flight values (µs). Must be a NumPy array.
        offset (float): Calibration offset (µs).
        linear (float): Linear calibration coefficient (µs/Å).
        quad (float): Quadratic calibration coefficient (µs/Ų).
        quad_eps (float, optional): Threshold to treat ``quad`` as zero. Defaults to 1e-20.

    Returns:
        np.ndarray: d-spacing values (Å), NaN where invalid.

    Raises:
        TypeError: If ``tof`` is not a NumPy array or coefficients are not real numbers.
    """
    # Type checks
    if not isinstance(tof, np.ndarray):
        raise TypeError(f"'tof' must be a NumPy array, got {type(tof).__name__}")
    for name, val in (('offset', offset), ('linear', linear), ('quad', quad), ('quad_eps', quad_eps)):
        if not isinstance(val, (int, float, np.integer, np.floating)):
            raise TypeError(f"'{name}' must be a real number, got {type(val).__name__}")

    # Output initialized to NaN
    d_out = np.full_like(tof, np.nan, dtype=float)

    # 1) If quadratic term is effectively zero, use linear formula:
    #    TOF ≈ offset + linear * d =>
    #    d ≈ (tof - offset) / linear
    if abs(quad) < quad_eps:
        if linear != 0.0:
            d = (tof - offset) / linear
            # Keep only positive, finite results
            valid = np.isfinite(d) & (d > 0)
            d_out[valid] = d[valid]
        # If B == 0 too, there's no solution; leave NaN
        return d_out

    # 2) If quadratic term is significant, solve the quadratic equation:
    #    TOF = offset + linear * d + quad * d² =>
    #    quad * d² + linear * d + (offset - tof) = 0
    discr = linear**2 - 4 * quad * (offset - tof)
    has_real_roots = discr >= 0

    if np.any(has_real_roots):
        sqrt_discr = np.sqrt(discr[has_real_roots])

        root_1 = (-linear + sqrt_discr) / (2 * quad)
        root_2 = (-linear - sqrt_discr) / (2 * quad)

        # Pick smallest positive, finite root per element
        roots = np.stack((root_1, root_2), axis=0)  # Stack roots for comparison
        roots = np.where(np.isfinite(roots) & (roots > 0), roots, np.nan)  # Replace non-finite or negative roots with NaN
        chosen = np.nanmin(roots, axis=0)  # Choose the smallest positive root or NaN if none are valid

        d_out[has_real_roots] = chosen

    return d_out

twotheta_to_d(twotheta, wavelength)

Convert 2-theta to d-spacing using Bragg's law.

Parameters:

Name Type Description Default
twotheta float or ndarray

2-theta angle in degrees.

required
wavelength float

Wavelength in Å.

required

Returns:

Name Type Description
d float or ndarray

d-spacing in Å.

Source code in src/easydiffraction/utils/utils.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def twotheta_to_d(twotheta, wavelength):
    """
    Convert 2-theta to d-spacing using Bragg's law.

    Parameters:
        twotheta (float or np.ndarray): 2-theta angle in degrees.
        wavelength (float): Wavelength in Å.

    Returns:
        d (float or np.ndarray): d-spacing in Å.
    """
    # Convert twotheta from degrees to radians
    theta_rad = np.radians(twotheta / 2)

    # Calculate d-spacing using Bragg's law
    d = wavelength / (2 * np.sin(theta_rad))

    return d