API Reference
Pattern
- class xypattern.pattern.Pattern(x: ndarray = None, y: ndarray = None, name: str = '')[source]
Bases:
objectA Pattern represents a set of x and y values for scientific data analysis.
The Pattern class provides a comprehensive set of tools for working with x-y data, such as those collected in x-ray diffraction, spectroscopy, or other scientific measurements. It supports loading from and saving to various file formats, background subtraction, data manipulation, and mathematical operations.
Key features: - Loading and saving patterns from/to various file formats (.xy, .chi, .fxye) - Applying scaling, offset, and smoothing to patterns - Background subtraction (manual or automatic) - Pattern manipulation (limiting, extending, deleting ranges) - Mathematical operations (addition, subtraction, multiplication) - Pattern transformation (x-axis transformation) - Pattern rebinning - Pattern serialization to/from dictionaries
- Parameters:
x – x values of the pattern (numpy array)
y – y values of the pattern (numpy array)
name – name of the pattern (string)
- __init__(x: ndarray = None, y: ndarray = None, name: str = '')[source]
Create a new Pattern object.
Initializes a Pattern with the provided x and y data arrays. If no data is provided, default values will be generated: x as a linear space from 0.1 to 15 with 100 points, and y as a function of x.
- Parameters:
x – Array of x values. If None, default values will be generated.
y – Array of y values. If None, default values will be generated.
name – Name identifier for the pattern. Useful for display and when working with multiple patterns.
- Raises:
ValueError – If x and y arrays have different lengths.
Example
>>> # Create a pattern with custom data >>> x = np.linspace(0, 10, 100) >>> y = np.sin(x) >>> pattern = Pattern(x, y, name="Sine Wave") >>> >>> # Create a pattern with default data >>> default_pattern = Pattern()
- load(filename: str, skiprows: int = 0)[source]
Load pattern data from a file.
Reads x-y data from various file formats and updates the current Pattern object. Supported formats: - .xy: Simple two-column text file with x values in the first column and y values in the second - .chi: Standard format used in X-ray diffraction, automatically skips 4 header rows - Other text-based formats with columns of x-y data
The pattern name will be set to the filename (without extension).
- Parameters:
filename – Path to the file to load
skiprows – Number of header rows to skip when loading the data (automatically set to 4 for .chi files)
- Raises:
ValueError – If the file format is incorrect or file cannot be read
Example
>>> pattern = Pattern() >>> pattern.load("data.xy") >>> # For a file with header rows: >>> pattern.load("data_with_header.xy", skiprows=2)
- static from_file(filename: str, skiprows: int = 0) Pattern[source]
Create a new Pattern object by loading data from a file.
This is a convenience static method that creates a new Pattern instance and loads data from the specified file.
Supported formats: - .xy: Simple two-column text file with x values in the first column and y values in the second - .chi: Standard format used in X-ray diffraction, automatically skips 4 header rows - Other text-based formats with columns of x-y data
- Parameters:
filename – Path to the file to load
skiprows – Number of header rows to skip when loading the data (automatically set to 4 for .chi files)
- Returns:
A new Pattern object containing the loaded data
- Raises:
ValueError – If the file format is incorrect or file cannot be read
Example
>>> # Create a pattern directly from a file: >>> pattern = Pattern.from_file("data.xy") >>> >>> # For a file with header rows: >>> pattern = Pattern.from_file("data_with_header.xy", skiprows=2)
- save(filename, header='', subtract_background=False, unit='2th_deg')[source]
Save pattern data to a file.
Writes the pattern’s x-y data to a file in various formats. The format is determined by the file extension: - .xy: Simple two-column text file - .chi: Standard format used in X-ray diffraction, includes header information - .fxye: Format with x, y, and error values (errors calculated as sqrt(|y|))
- param filename:
Path where the file should be saved
- param header:
Optional header text to include in the file
- param subtract_background:
If True, saves the background-subtracted data; if False, saves the original data
- param unit:
X-axis unit descriptor used in the .chi file header (only used for .chi format)
- Example:
>>> pattern = Pattern(x, y) >>> # Save as .xy file: >>> pattern.save("data.xy") >>> >>> # Save as .chi file with background subtraction: >>> pattern.save("data.chi", subtract_background=True, unit="q_A^-1") >>> >>> # Save with custom header: >>> pattern.save("data.xy", header="# X Y data
# Measured on 2023-01-01”)
- property background_pattern: Pattern
Get or set the background pattern for this Pattern.
The background pattern is used for background subtraction during data processing. When a background pattern is set, its y values will be subtracted from this pattern’s y values during the recalculation process. If the x values of the background pattern don’t match this pattern’s x values, interpolation will be used.
When a background pattern is set, it will be connected to this pattern’s recalculation process, so any changes to the background pattern will automatically trigger a recalculation of this pattern.
- Returns:
The current background Pattern object or None if no background is set
Example
>>> # Create a main pattern and a background pattern >>> main_pattern = Pattern(x_data, y_data, name="sample") >>> background = Pattern(x_data, background_data, name="background") >>> >>> # Set the background pattern >>> main_pattern.background_pattern = background >>> >>> # Remove the background pattern >>> main_pattern.background_pattern = None
- rebin(bin_size: float) Pattern[source]
Creates a new pattern with data rebinned to the specified bin size.
Rebinning is the process of combining adjacent data points into bins of a specified size, which can be useful for reducing noise or matching the resolution of different patterns. This method uses histogram-based rebinning, which preserves the total intensity.
This method does not modify the current pattern but returns a new Pattern object.
- Parameters:
bin_size – Size of the bins in the same units as the x-axis
- Returns:
A new Pattern object with rebinned data
Example
>>> pattern = Pattern(x_data, y_data) >>> # Rebin to 0.1 unit bins >>> rebinned = pattern.rebin(0.1) >>> # Rebin to coarser 0.5 unit bins >>> coarse_rebinned = pattern.rebin(0.5)
- recalculate_pattern()[source]
Recalculates the pattern data based on the current settings. Applies background subtraction, auto background, scaling, offset, and smoothing. This method is called automatically when any of these settings are changed.
- property data: tuple[ndarray, ndarray]
Returns the data of the pattern. If a background pattern is set, the background will be subtracted from the pattern. If smoothing is set, the pattern will be smoothed.
- Returns:
Tuple of x and y values
- property original_data: tuple[ndarray, ndarray]
Returns the original data of the pattern without any background subtraction or smoothing.
- Returns:
tuple of x and y values
- property scaling: float
Get or set the scaling factor applied to the pattern’s y values.
The scaling factor is a multiplicative factor applied to the y values during pattern recalculation. This allows for adjusting the intensity of the pattern without modifying the original data.
The scaling is applied before the offset and after any background subtraction.
- Returns:
The current scaling factor (default: 1.0)
Example
>>> pattern = Pattern(x_data, y_data) >>> pattern.scaling = 2.0 # Double the intensity >>> pattern.scaling = 0.5 # Halve the intensity
- property offset: float
Get or set the vertical offset applied to the pattern’s y values.
The offset is an additive value applied to the y values during pattern recalculation. This allows for shifting the pattern up or down without modifying the original data.
The offset is applied after the scaling factor and after any background subtraction.
- Returns:
The current offset value (default: 0.0)
Example
>>> pattern = Pattern(x_data, y_data) >>> pattern.offset = 100 # Shift the pattern up by 100 units >>> pattern.offset = -50 # Shift the pattern down by 50 units
- property smoothing: float
Get or set the smoothing factor applied to the pattern’s y values.
The smoothing factor controls the amount of Gaussian smoothing applied to the pattern data during recalculation. A value of 0 means no smoothing is applied. Higher values result in more smoothing.
The smoothing is implemented using scipy’s gaussian_filter1d function, where the smoothing value represents the standard deviation of the Gaussian kernel.
Smoothing is applied after background subtraction, scaling, and offset.
- Returns:
The current smoothing factor (default: 0.0)
Example
>>> pattern = Pattern(x_data, y_data) >>> pattern.smoothing = 0.0 # No smoothing >>> pattern.smoothing = 0.5 # Light smoothing >>> pattern.smoothing = 2.0 # Stronger smoothing
- property auto_bkg: AutoBackground | None
Get or set the automatic background extraction algorithm.
This property allows you to specify an algorithm for automatic background extraction. When set to a valid AutoBackground implementation (such as SmoothBrucknerBackground), the algorithm will be applied during pattern recalculation to automatically extract and subtract a background from the pattern data.
The automatic background is calculated within the region specified by auto_bkg_roi if provided, otherwise it uses the full pattern range.
Setting this property to None disables automatic background extraction.
- Returns:
The current AutoBackground object or None if automatic background extraction is disabled
Example
>>> pattern = Pattern(x_data, y_data) >>> # Enable automatic background extraction with SmoothBrucknerBackground >>> pattern.auto_bkg = SmoothBrucknerBackground( ... smooth_width=0.2, ... iterations=30, ... cheb_order=20 ... ) >>> # Disable automatic background extraction >>> pattern.auto_bkg = None
- property auto_bkg_roi: list[float] | None
Get or set the region of interest for automatic background extraction.
This property defines the x-range (region of interest) within which the automatic background extraction algorithm will operate. It should be a list of two float values [min_x, max_x] specifying the lower and upper bounds of the region.
If set to None, the full pattern range will be used for background extraction.
- Returns:
A list of two float values [min_x, max_x] or None if no specific region is defined
Example
>>> pattern = Pattern(x_data, y_data) >>> pattern.auto_bkg = SmoothBrucknerBackground() >>> # Set region of interest for background extraction >>> pattern.auto_bkg_roi = [10.0, 60.0] >>> # Use the full pattern range >>> pattern.auto_bkg_roi = None
- property auto_background_pattern: Pattern
Get the automatically calculated background pattern.
This property provides access to the background pattern that was automatically calculated using the auto_bkg algorithm (if enabled). This is different from the manually set background_pattern property.
The auto background is calculated during the recalculate_pattern method when auto_bkg is not None. The calculation uses the specified auto_bkg algorithm and auto_bkg_roi (region of interest) if provided.
- Returns:
The automatically calculated background Pattern object or None if auto background calculation is not enabled or hasn’t been performed yet
Example
>>> pattern = Pattern(x_data, y_data) >>> pattern.auto_bkg = AutoBackgroundBruckner(width=5, iterations=10) >>> # After recalculation, access the auto background pattern: >>> auto_bkg = pattern.auto_background_pattern >>> # Plot the auto background >>> plt.plot(auto_bkg.x, auto_bkg.y)
- property auto_background_before_subtraction_pattern: Pattern
Returns the pattern before the auto background subtraction :return: background Pattern
- limit(x_min: float, x_max: float) Pattern[source]
Creates a new pattern limited to a specific x-range.
This method extracts a subset of the pattern data that falls within the specified x-range boundaries. Only data points where x_min < x < x_max will be included in the resulting pattern.
This method does not modify the current pattern but returns a new Pattern object.
- Parameters:
x_min – Lower limit of the x-range (exclusive)
x_max – Upper limit of the x-range (exclusive)
- Returns:
A new Pattern object containing only data within the specified range
Example
>>> pattern = Pattern(x_data, y_data) >>> # Extract data between x=10 and x=20 >>> limited_pattern = pattern.limit(10.0, 20.0) >>> # Extract a small region of interest >>> roi_pattern = pattern.limit(15.5, 16.5)
- extend_to(x_value: float, y_value: float) Pattern[source]
Creates a new pattern by extending the current pattern to a specified x-value.
This method extends the pattern’s x-range by adding new data points with the specified y-value. The extension can be either to a lower x-value than the current minimum or to a higher x-value than the current maximum. The step size of the extension is determined by the average step size of the current pattern.
This method is useful for padding patterns to match ranges, creating baseline extensions, or preparing data for operations that require matching x-ranges.
This method does not modify the current pattern but returns a new Pattern object.
- Parameters:
x_value – Target x-value to extend to. Should be smaller than the minimum x-value or larger than the maximum x-value of the current pattern.
y_value – Y-value to use for all extension points
- Returns:
A new Pattern object with the extended x-range
Example
>>> pattern = Pattern(x_data, y_data) # x-range: [10, 50] >>> # Extend to lower x-values >>> extended_low = pattern.extend_to(5.0, 0.0) # x-range: [5, 50] >>> # Extend to higher x-values >>> extended_high = pattern.extend_to(60.0, 0.0) # x-range: [10, 60]
- to_dict() dict[source]
Converts the pattern to a dictionary representation.
This method serializes the pattern and all its properties into a dictionary format, which can be used for JSON serialization, storage, or transmission. The dictionary includes all essential properties of the pattern: - name: The pattern name - x, y: The original x and y data arrays (converted to lists) - scaling, offset, smoothing: The pattern’s transformation parameters - bkg_pattern: The background pattern (if any), also converted to a dictionary - auto_bkg: Information about automatic background extraction settings (if any)
- Returns:
A dictionary containing all pattern properties and data
Example
>>> pattern = Pattern(x_data, y_data, name="sample") >>> pattern_dict = pattern.to_dict() >>> # Save to JSON >>> import json >>> with open("pattern.json", "w") as f: >>> json.dump(pattern_dict, f)
- static from_dict(json_dict: dict) Pattern[source]
Creates a new Pattern object from a dictionary representation.
This static method deserializes a dictionary (typically created by the to_dict method) back into a Pattern object, restoring all properties and data. It handles: - Basic pattern data (x, y arrays, name) - Transformation parameters (scaling, offset, smoothing) - Background pattern (if present in the dictionary) - Automatic background extraction settings (if present)
This method is the counterpart to to_dict() and is useful for loading patterns from JSON files or other serialized formats.
- Parameters:
json_dict – A dictionary containing pattern data and properties
- Returns:
A new Pattern object with all properties restored
Example
>>> # Load from a dictionary >>> pattern = Pattern.from_dict(pattern_dict) >>> >>> # Load from a JSON file >>> import json >>> with open("pattern.json", "r") as f: >>> pattern_dict = json.load(f) >>> pattern = Pattern.from_dict(pattern_dict)
- delete_range(x_range: list) Pattern[source]
Creates a new pattern with data points within a specified x-range removed.
This method is useful for removing unwanted regions from a pattern, such as detector artifacts, spurious peaks, or regions with known interference.
This method does not modify the current pattern but returns a new Pattern object.
- Parameters:
x_range – A list of two float values [min_x, max_x] defining the range of x-values to remove from the pattern
- Returns:
A new Pattern object with the specified range removed
Example
>>> pattern = Pattern(x_data, y_data) >>> # Remove data between x=15 and x=20 >>> filtered_pattern = pattern.delete_range([15.0, 20.0]) >>> >>> # Remove a detector gap >>> no_gap_pattern = pattern.delete_range([41.2, 42.8])
See also
delete_ranges: For removing multiple ranges at once
- delete_ranges(x_ranges: list) Pattern[source]
Creates a new pattern with data points within multiple specified x-ranges removed.
This method is similar to delete_range but allows for removing multiple ranges at once, which is more efficient than calling delete_range multiple times. It’s useful for removing multiple artifacts, gaps, or unwanted regions from a pattern.
This method does not modify the current pattern but returns a new Pattern object.
- Parameters:
x_ranges – A list of lists, where each inner list contains two float values [min_x, max_x] defining a range of x-values to remove
- Returns:
A new Pattern object with all specified ranges removed
Example
>>> pattern = Pattern(x_data, y_data) >>> # Remove multiple ranges >>> filtered_pattern = pattern.delete_ranges([ >>> [15.0, 20.0], # Remove first region >>> [41.2, 42.8], # Remove detector gap >>> [55.0, 60.0] # Remove third region >>> ])
See also
delete_range: For removing a single range
- transform_x(fcn: callable) Pattern[source]
Transforms the x-values of the pattern using the provided function.
This method applies a transformation function to all x-values in the pattern, which is useful for converting between different units or scales (e.g., 2θ to q-space, wavelength to energy, etc.). The method takes care of also updating any associated background patterns and automatic background parameters to maintain consistency.
Unlike most other methods in this class, this method modifies the pattern in-place and returns self for method chaining.
- Parameters:
fcn – A callable function that takes an array of x-values and returns a transformed array of the same shape
- Returns:
Self (the current Pattern object) with transformed x-values
Example
>>> pattern = Pattern(x_data, y_data) # x in degrees 2θ >>> >>> # Convert from 2θ to q-space (Å⁻¹) >>> from math import pi, sin >>> wavelength = 0.3344 # Å >>> pattern.transform_x(lambda x: 4 * pi * sin(x * pi / 360) / wavelength) >>> >>> # Convert from eV to keV >>> pattern.transform_x(lambda x: x / 1000)
- __sub__(other: Pattern) Pattern[source]
Subtracts another pattern from this pattern (self - other).
This operator allows for pattern subtraction, which is useful for background subtraction, reference subtraction, or differential analysis. The method handles two cases:
If both patterns have identical x-values: Direct subtraction is performed
If patterns have different x-values: The other pattern is linearly interpolated to match the x-values of this pattern, but only in the overlapping x-range
This method does not modify either pattern but returns a new Pattern object.
- Parameters:
other – The Pattern object to subtract from this pattern
- Returns:
A new Pattern object representing the difference
- Raises:
BkgNotInRangeError – If there is no overlap between the x-ranges of the two patterns
Example
>>> sample = Pattern(x_data, sample_data) >>> background = Pattern(x_data, background_data) >>> # Subtract background from sample >>> subtracted = sample - background >>> >>> # Works even with different x-ranges (where they overlap) >>> wide_range = Pattern(x_wide, y_wide) # x: [0, 100] >>> narrow_range = Pattern(x_narrow, y_narrow) # x: [20, 80] >>> result = wide_range - narrow_range # Result has x-range [20, 80]
- __add__(other: Pattern) Pattern[source]
Adds another pattern to this pattern (self + other).
This operator allows for pattern addition, which is useful for combining patterns, merging datasets, or creating composite patterns. The method handles two cases:
If both patterns have identical x-values: Direct addition is performed
If patterns have different x-values: The other pattern is linearly interpolated to match the x-values of this pattern, but only in the overlapping x-range
This method does not modify either pattern but returns a new Pattern object.
- Parameters:
other – The Pattern object to add to this pattern
- Returns:
A new Pattern object representing the sum
- Raises:
BkgNotInRangeError – If there is no overlap between the x-ranges of the two patterns
Example
>>> pattern1 = Pattern(x_data1, y_data1) >>> pattern2 = Pattern(x_data2, y_data2) >>> # Add patterns together >>> combined = pattern1 + pattern2 >>> >>> # Works even with different x-ranges (where they overlap) >>> low_range = Pattern(x_low, y_low) # x: [0, 50] >>> high_range = Pattern(x_high, y_high) # x: [40, 100] >>> result = low_range + high_range # Result has x-range [40, 50]
- __rmul__(other: float) Pattern[source]
Multiplies this pattern by a scalar value (other * self).
This operator enables scalar multiplication of patterns, which is useful for scaling, normalization, or applying weighting factors. The multiplication affects only the y-values; x-values remain unchanged.
This is the right multiplication operator, allowing expressions like: 2.5 * pattern (where pattern is a Pattern object).
This method does not modify the current pattern but returns a new Pattern object.
- Parameters:
other – A scalar value to multiply the pattern’s y-values by
- Returns:
A new Pattern object with scaled y-values
Example
>>> pattern = Pattern(x_data, y_data) >>> # Scale the pattern by a factor of 2 >>> doubled = 2.0 * pattern >>> # Scale the pattern by a factor of 0.5 >>> halved = 0.5 * pattern
- __eq__(other: Pattern) bool[source]
Checks if this pattern is equal to another pattern (self == other).
Two patterns are considered equal if they have identical x and y data arrays. Other properties like name, scaling, offset, etc. are not considered in the equality check.
- Parameters:
other – The Pattern object to compare with
- Returns:
True if the patterns have identical data, False otherwise
Example
>>> pattern1 = Pattern(x_data, y_data) >>> pattern2 = Pattern(x_data, y_data) >>> pattern3 = Pattern(x_data, different_y_data) >>> >>> pattern1 == pattern2 # Returns: True >>> pattern1 == pattern3 # Returns: False >>> pattern1 == "not a pattern" # Returns: False
- __len__()[source]
Returns the number of data points in the pattern.
This method allows using the built-in len() function with Pattern objects.
- Returns:
The number of data points (length of the x and y arrays)
Example
>>> pattern = Pattern(x_data, y_data) >>> num_points = len(pattern) # Get the number of data points
- __str__()[source]
Returns a string representation of the pattern.
This method provides a human-readable description of the pattern when it is printed or converted to a string.
- Returns:
A string describing the pattern name and number of data points
Example
>>> pattern = Pattern(x_data, y_data, name="sample") >>> print(pattern) # Outputs: "Pattern 'sample' with 1000 points" >>> str(pattern) # Returns: "Pattern 'sample' with 1000 points"
- copy() Pattern[source]
Creates a deep copy of the pattern.
This method creates a completely independent copy of the pattern with all its properties and data. The copy includes: - Original x and y data arrays (copied, not referenced) - Pattern name - Transformation parameters (scaling, offset, smoothing) - Background pattern (if present, also deeply copied) - Automatic background extraction settings (if present)
Deep copying is useful when you need to modify a pattern without affecting the original, or when you need to preserve a pattern state.
- Returns:
A new Pattern object that is a deep copy of this pattern
Example
>>> original = Pattern(x_data, y_data, name="original") >>> original.scaling = 2.0 >>> >>> # Create a deep copy >>> copy = original.copy() >>> >>> # Modify the copy without affecting the original >>> copy.scaling = 1.5 >>> copy.name = "modified" >>> >>> print(original.scaling) # Still 2.0 >>> print(copy.scaling) # Now 1.5
- property changed: Signal
Signal that is emitted whenever the pattern data changes.
This signal allows other objects to react to changes in this pattern’s data. It is emitted after any operation that modifies the pattern data, such as: - Setting a new background pattern - Changing scaling, offset, or smoothing - Modifying x or y data - Applying automatic background subtraction
When emitted, this signal passes the pattern itself (self) as an argument to all connected callbacks, allowing them to directly access the pattern that changed.
The signal can be connected to callback functions that will be executed when the pattern changes. This is particularly useful for implementing reactive UI updates or for chaining pattern processing steps.
Example
>>> pattern = Pattern(x_data, y_data) >>> >>> # Connect a callback to the changed signal >>> def on_pattern_changed(pattern): >>> print(f"Pattern '{pattern.name}' has changed") >>> print(f"New max value: {pattern.y.max()}") >>> >>> pattern.changed.connect(on_pattern_changed) >>> >>> # Now when we modify the pattern, our callback will be called with the pattern as argument >>> pattern.scaling = 2.0 # Triggers callback with pattern as argument >>> >>> # Disconnect the callback when no longer needed >>> pattern.changed.disconnect(on_pattern_changed)
See also
The Signal class in xypattern.util.signal for more details on connecting and disconnecting callbacks.
Auto Background
- class xypattern.auto_background.AutoBackground[source]
Bases:
objectAbstract base class for automatic background extraction algorithms.
This class defines the interface for background extraction algorithms. Concrete implementations should override the extract_background method to provide specific background extraction functionality.
- abstractmethod extract_background(pattern: Pattern)[source]
Extracts the background from a pattern.
This method should be implemented by subclasses to provide specific background extraction functionality.
- Parameters:
pattern – Pattern object from which to extract the background
- Returns:
numpy array of y values representing the extracted background
- class xypattern.auto_background.SmoothBrucknerBackground(smooth_width=0.1, iterations=50, cheb_order=50)[source]
Bases:
AutoBackgroundBackground extraction using Bruckner smoothing and Chebyshev polynomial fitting.
This algorithm performs background extraction in two steps: 1. Applies Bruckner smoothing to the input pattern 2. Fits a Chebyshev polynomial to the smoothed data
The Bruckner smoothing algorithm is particularly effective for extracting backgrounds from patterns with sharp peaks, such as X-ray diffraction data.
Standard parameters are optimized for synchrotron XRD data but can be adjusted for other types of data.
- Parameters:
smooth_width – Width of the window in x-units used for Bruckner smoothing. Larger values result in smoother backgrounds.
iterations – Number of iterations for the Bruckner smoothing algorithm. More iterations typically result in better background fitting.
cheb_order – Order of the fitted Chebyshev polynomial. Higher orders can fit more complex background shapes.
- extract_background(pattern: Pattern)[source]
Extract background from a pattern using Bruckner smoothing and Chebyshev polynomial fitting.
The method first applies Bruckner smoothing to the pattern data, then fits a Chebyshev polynomial to the smoothed data to create a continuous background.
- Parameters:
pattern – Pattern object from which to extract the background
- Returns:
numpy array of y values representing the extracted background
- transform_x(fcn: callable)[source]
Transform x-dependent parameters when the x-axis is transformed.
This method adjusts the smooth_width parameter when the x-axis is transformed, ensuring that the background extraction behaves consistently after transformation.
- Parameters:
fcn – Function to transform the x-variable
Combine
- xypattern.combine.stitch_patterns(patterns: list[Pattern], binning=None) Pattern[source]
Stitch together multiple patterns into a single continuous pattern.
This function concatenates the x and y values from all patterns and then applies rebinning to create a uniform x-spacing. The patterns should be properly scaled before stitching (see scale_patterns function).
- Parameters:
patterns – List of Pattern objects to be stitched together
binning – Bin size for the output pattern. If None, the bin size of the first pattern will be used.
- Returns:
A new Pattern object containing the stitched data
Example
>>> p1 = Pattern.from_file('low_angle.xy') >>> p2 = Pattern.from_file('high_angle.xy') >>> scale_patterns([p1, p2]) # Scale patterns to match each other >>> stitched = stitch_patterns([p1, p2])
- xypattern.combine.scale_patterns(patterns: list[Pattern])[source]
Scale multiple patterns to match each other in overlapping regions.
This function scales patterns in place by modifying their scaling attribute. The first pattern (after sorting by x[0]) is used as the reference with a scaling of 1.0. Each subsequent pattern is scaled to match the previous one in their overlapping region.
The patterns must have overlapping x-ranges for scaling to work properly.
- Parameters:
patterns – List of Pattern objects to be scaled
- Raises:
ValueError – If no overlap is found between adjacent patterns
Example
>>> p1 = Pattern.from_file('low_angle.xy') >>> p2 = Pattern.from_file('high_angle.xy') >>> scale_patterns([p1, p2]) >>> # p1.scaling will be 1.0, p2.scaling will be adjusted to match p1
- xypattern.combine.find_overlap(p1: Pattern, p2: Pattern) tuple[float, float] | None[source]
Find the overlapping x-range between two patterns.
- Parameters:
p1 – First Pattern object
p2 – Second Pattern object
- Returns:
Tuple of (x_min, x_max) for the overlapping region, or None if no overlap exists
Example
>>> overlap = find_overlap(pattern1, pattern2) >>> if overlap: >>> x_min, x_max = overlap >>> print(f"Patterns overlap from {x_min} to {x_max}") >>> else: >>> print("No overlap between patterns")
- xypattern.combine.find_scaling(p1: Pattern, p2: Pattern) float | None[source]
Calculate the scaling factor to match p2 to p1 in their overlapping region.
This function finds the average ratio of y-values between p1 and p2 in their overlapping x-range. If the x-values don’t exactly match, linear interpolation is used to estimate the y-values at matching x-positions.
- Parameters:
p1 – Reference Pattern object
p2 – Pattern object to be scaled
- Returns:
Scaling factor to apply to p2 to match p1, or None if no overlap exists
Example
>>> scaling = find_scaling(reference_pattern, pattern_to_scale) >>> if scaling is not None: >>> pattern_to_scale.scaling = scaling
Utilities
Utility functions and classes for the xypattern package.
This package contains various utility functions and classes used by the xypattern package, including:
Signal: A simple implementation of the observer pattern for event handling
smooth_bruckner: Implementation of the Bruckner smoothing algorithm for background extraction (available in both Cython and pure Python versions)