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
13
14
15
16
17
18
19
20
21
22
23
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
47
48
49
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
57
58
59
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
32
33
34
35
36
37
38
39
40
41
42
43
44
def paragraph(title: str) -> str:
    """Formats a subsection header with bold blue text while keeping
    quoted text unformatted.
    """
    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
26
27
28
29
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
52
53
54
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

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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.
    """
    dest_path = pathlib.Path(destination)
    file_path = dest_path / file_name
    if file_path.exists():
        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."))
            file_path.unlink()

    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,
    )

fetch_tutorial_list()

Return a list of available tutorial notebook filenames from the GitHub release that matches the installed version of easydiffraction, if possible. If the version-specific release is unavailable, falls back to the latest release.

This function does not fetch or display the tutorials themselves; it only lists the notebook filenames (e.g., '01-intro.ipynb', ...) found inside the 'tutorials.zip' asset of the appropriate GitHub release.

Returns:

Type Description
list[str]

list[str]: A sorted list of tutorial notebook filenames (without

list[str]

directories) extracted from the corresponding release's

list[str]

tutorials.zip, or an empty list if unavailable.

Source code in src/easydiffraction/utils/utils.py
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
def fetch_tutorial_list() -> list[str]:
    """Return a list of available tutorial notebook filenames from the
    GitHub release that matches the installed version of
    `easydiffraction`, if possible. If the version-specific release is
    unavailable, falls back to the latest release.

    This function does not fetch or display the tutorials themselves; it
    only lists the notebook filenames (e.g., '01-intro.ipynb', ...)
    found inside the 'tutorials.zip' asset of the appropriate GitHub
    release.

    Returns:
        list[str]: A sorted list of tutorial notebook filenames (without
        directories) extracted from the corresponding release's
        tutorials.zip, or an empty list if unavailable.
    """
    version_str = stripped_package_version('easydiffraction')
    tag = f'v{version_str}' if version_str is not None else None
    release_info = _get_release_info(tag)
    # Fallback to latest if tag fetch failed and tag was attempted
    if release_info is None and tag is not None:
        print(error('Falling back to latest release info...'))
        release_info = _get_release_info(None)
    if release_info is None:
        return []
    tutorial_asset = _get_tutorial_asset(release_info)
    if not tutorial_asset:
        print(error("'tutorials.zip' not found in the release."))
        return []
    download_url = tutorial_asset.get('browser_download_url')
    if not download_url:
        print(error("'browser_download_url' not found for tutorials.zip."))
        return []
    return _extract_notebooks_from_asset(download_url)

fetch_tutorials()

Download and extract the tutorials ZIP archive from the GitHub release matching the installed version of easydiffraction, if available. If the version-specific release is unavailable, falls back to the latest release.

The archive is extracted into the current working directory and then removed.

Source code in src/easydiffraction/utils/utils.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def fetch_tutorials() -> None:
    """Download and extract the tutorials ZIP archive from the GitHub
    release matching the installed version of `easydiffraction`, if
    available. If the version-specific release is unavailable, falls
    back to the latest release.

    The archive is extracted into the current working directory and then
    removed.

    Args:
        None
    """
    version_str = stripped_package_version('easydiffraction')
    tag = f'v{version_str}' if version_str is not None else None
    release_info = _get_release_info(tag)
    # Fallback to latest if tag fetch failed and tag was attempted
    if release_info is None and tag is not None:
        print(error('Falling back to latest release info...'))
        release_info = _get_release_info(None)
    if release_info is None:
        print(error('Unable to fetch release info.'))
        return
    tutorial_asset = _get_tutorial_asset(release_info)
    if not tutorial_asset:
        print(error("'tutorials.zip' not found in the release."))
        return
    file_url = tutorial_asset.get('browser_download_url')
    if not file_url:
        print(error("'browser_download_url' not found for tutorials.zip."))
        return
    file_name = 'tutorials.zip'
    # Validate URL for security
    _validate_url(file_url)

    print('📥 Downloading tutorial notebooks...')
    with _safe_urlopen(file_url) as resp:
        pathlib.Path(file_name).write_bytes(resp.read())

    print('📦 Extracting tutorials to "tutorials/"...')
    with zipfile.ZipFile(file_name, 'r') as zip_ref:
        zip_ref.extractall()

    print('🧹 Cleaning up...')
    pathlib.Path(file_name).unlink()

    print('✅ Tutorials fetched successfully.')

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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
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 pathlib.Path(file_path).open('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_colab()

Determines if the current environment is Google Colab.

Returns:

Name Type Description
bool bool

True if running in Google Colab PyCharm, False otherwise.

Source code in src/easydiffraction/utils/utils.py
401
402
403
404
405
406
407
408
409
410
def is_colab() -> bool:
    """Determines if the current environment is Google Colab.

    Returns:
        bool: True if running in Google Colab PyCharm, False otherwise.
    """
    try:
        return importlib.util.find_spec('google.colab') is not None
    except ModuleNotFoundError:
        return False

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

bool

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

Source code in src/easydiffraction/utils/utils.py
413
414
415
416
417
418
419
420
421
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

bool

otherwise.

Source code in src/easydiffraction/utils/utils.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
    if is_pycharm():  # Running inside PyCharm
        return False
    if is_colab():  # Running inside Google Colab
        return True

    try:
        # get_ipython is only defined inside IPython environments
        shell = get_ipython().__class__.__name__  # type: ignore[name-defined]
        if shell == 'ZMQInteractiveShell':  # Jupyter notebook or qtconsole
            return True
        if shell == 'TerminalInteractiveShell':  # Terminal running IPython
            return False
        # Fallback for any other shell type
        return False
    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
392
393
394
395
396
397
398
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'

list_tutorials()

List available tutorial notebooks.

Source code in src/easydiffraction/utils/utils.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def list_tutorials():
    """List available tutorial notebooks.

    Args:
        None
    """
    tutorials = fetch_tutorial_list()
    columns_data = [[t] for t in tutorials]
    columns_alignment = ['left']

    released_ed_version = stripped_package_version('easydiffraction')

    print(paragraph(f'📘 Tutorials available for easydiffraction v{released_ed_version}:'))
    render_table(
        columns_data=columns_data,
        columns_alignment=columns_alignment,
        show_index=True,
    )

package_version(package_name)

Get the installed version string of the specified package.

Parameters:

Name Type Description Default
package_name str

The name of the package to query.

required

Returns:

Type Description
str | None

str | None: The raw version string (may include local part,

str | None

e.g., '1.2.3+abc123'), or None if the package is not installed.

Source code in src/easydiffraction/utils/utils.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def package_version(package_name: str) -> str | None:
    """Get the installed version string of the specified package.

    Args:
        package_name (str): The name of the package to query.

    Returns:
        str | None: The raw version string (may include local part,
        e.g., '1.2.3+abc123'), or None if the package is not installed.
    """
    try:
        return version(package_name)
    except PackageNotFoundError:
        return None

render_cif(cif_text, paragraph_title)

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

Parameters:

Name Type Description Default
cif_text

The CIF text to display.

required
paragraph_title

The title to print above the table.

required
Source code in src/easydiffraction/utils/utils.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
def render_cif(cif_text, paragraph_title) -> None:
    """Display the CIF text as a formatted table in Jupyter Notebook or
    terminal.

    Args:
        cif_text: The CIF text to display.
        paragraph_title: The title to print above the table.
    """
    # 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
display_handle

Optional display handle for updating in Jupyter.

None
Source code in src/easydiffraction/utils/utils.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
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.
        display_handle: Optional display handle for updating in Jupyter.
    """
    # 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,
                strict=True,
            )
        }

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

        # Add 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, strict=True):
                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)

show_version()

Print the installed version of the easydiffraction package.

Source code in src/easydiffraction/utils/utils.py
355
356
357
358
359
360
361
362
def show_version() -> None:
    """Print the installed version of the easydiffraction package.

    Args:
        None
    """
    current_ed_version = package_version('easydiffraction')
    print(paragraph(f'📘 Current easydiffraction v{current_ed_version}'))

stripped_package_version(package_name)

Get the installed version of the specified package, stripped of any local version part.

Returns only the public version segment (e.g., '1.2.3' or '1.2.3.post4'), omitting any local segment (e.g., '+d136').

Parameters:

Name Type Description Default
package_name str

The name of the package to query.

required

Returns:

Type Description
str | None

str | None: The public version string, or None if the package

str | None

is not installed.

Source code in src/easydiffraction/utils/utils.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def stripped_package_version(package_name: str) -> str | None:
    """Get the installed version of the specified package, stripped of
    any local version part.

    Returns only the public version segment (e.g., '1.2.3' or
    '1.2.3.post4'), omitting any local segment (e.g., '+d136').

    Args:
        package_name (str): The name of the package to query.

    Returns:
        str | None: The public version string, or None if the package
        is not installed.
    """
    v_str = package_version(package_name)
    if v_str is None:
        return None
    try:
        v = Version(v_str)
        return str(v.public)
    except Exception:
        return v_str

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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
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
        # Stack roots for comparison
        roots = np.stack((root_1, root_2), axis=0)
        # Replace non-finite or negative roots with NaN
        roots = np.where(np.isfinite(roots) & (roots > 0), roots, np.nan)
        # Choose the smallest positive root or NaN if none are valid
        chosen = np.nanmin(roots, axis=0)

        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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
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