BioSim2D – Reference Guide

This guide is for versions 1.0 RC2+ (Release Candidate)

Source code

Class BioSim2D

    2D simulations of diffusion and reactions
    
nameargumentsreturns
__init__x_bins :int, y_bins: int, chem_data=None, reaction_handler=None
        :param x_bins:          The bin size in the x-coordinates.  Notice that this is the number of COLUMNS in the data matrix
        :param y_bins:          The bin size in the y-coordinates.  Notice that this is the number of ROWS in the data matrix
        :param chem_data:       [OPTIONAL] Object of class "ChemData";
                                    if not specified, it will get extracted
                                    from the "UniformCompartment" class (if passed to the next argument)
        :param reaction_handler:[OPTIONAL] Object of class "UniformCompartment";
                                    if not specified, it'll get instantiated here
        

VIEW SYSTEM

nameargumentsreturns
system_size(int, int)
        Return a pair of integers with the system sizes in the x- and y-dimensions
        Note: the bin numbers start with 0

        :return:    The pair (x-dimension, y-dimension)
        
nameargumentsreturns
get_system_timefloat
        Return the current system time
nameargumentsreturns
get_chem_data

        :return:    An Object of type "ChemData"
        
nameargumentsreturns
get_reactions
        Return all the associated reactions

        :return:    Object ot type "Reactions" (with data about all the reactions)
        
nameargumentsreturns
system_snapshot_arr_xychem_label=None, chem_index=Nonenp.ndarray
        Return a snapshot of all the concentrations of the given chemical species,
        across ALL BINS, as a Numpy array in XY coordinates.
        IMPORTANT: the rows of the matrix store the x-coordinates, and the columns store the y-coordinates;
                   so, this matrix is the TRANSPOSE of the X-Y cartesian representation
        If a Pandas dataframe is desired, for a single chemical, use system_snapshot()

        :param chem_label:  String with the label to identify the chemical of interest
        :param chem_index:  Integer to identify the chemical of interest.  Cannot specify both chem_label and chem_index
        :return:            A 2-D Numpy array of concentration values in XY coordinates
        
nameargumentsreturns
system_snapshotchem_label=None, chem_index=None, cartesian=Truepd.DataFrame
        Return a snapshot of all the concentrations of the given chemical species,
        across ALL BINS, in a grid XY coordinate system, as a Pandas dataframe.
        The columns of the dataframe are the x-coordinates, increasing to the right.
        The rows of the the dataframe are the y-coordinates, by default increasing in the up direction (earlier rows)

        :param chem_label:  String with the label to identify the chemical of interest
        :param chem_index:  Integer to identify the chemical of interest.  Cannot specify both chem_label and chem_index
        :param cartesian:   If True (default) a Cartesian grid coordinate is used, with y-bin numbers increasing up
        :return:            A Pandas dataframe with the concentration data for the single specified chemical;
                            rows and columns correspond to the system's rows and columns
        
nameargumentsreturns
bin_concentrationbin_address: (int, int), species_index=None, species_label=Nonefloat
        Return the concentration at the requested bin of the specified chemical species

        :param bin_address:     A pair of integers identifying the bin of interest
        :param species_index:   The index order of the chemical species of interest
        :param species_label:   [OPTIONAL] If provided, it over-rides the value for species_index
        :return:                A concentration value at the indicated bin, for the requested species
        
nameargumentsreturns
describe_statecartesian=TrueNone
        A minimalist view of all the chemical concentrations across the 2D system.
        For each chemical species, show its name (or index, if name is missing),
        followed by the matrix of its concentrations values

        :param cartesian:   If True (default) a Cartesian grid coordinate is used, with y-bin numbers increasing up
        :return:            None
        
nameargumentsreturns
lookup_speciesspecies_index=None, species_name=None, copy=Falsenp.array
        Return the NumPy array of concentration values across ALL THE BINS
        (from top to bottom, and then left to right),
        for the single specified chemical species.
        NOTE: what is being returned NOT a copy, unless specifically requested

        :param species_index:   The index order of the chemical species of interest
        :param species_name:    (OPTIONAL) If provided, it over-rides the value for species_index
        :param copy:            If True, an independent numpy array will be returned: a *copy* rather than a view
        :return:                A NumPy 2-D array of concentration values across the bins
                                    (from top to bottom, and then left to right);
                                    the size of the array is (n_bins_y x n_bins_x)
        
nameargumentsreturns
bin_snapshot_arraybin_address: (int, int)np.array
        Extract the concentrations of all the chemical species at the specified bin,
        as a Numpy array in the index order of the species
        EXAMPLE: np.array([10., 50.)]

        :param bin_address:     A pair with the zero-based bin numbers of the desired cell, in the x- and y-coordinates
        :return:                A Numpy array  of concentration values, in the index order of the species
        
nameargumentsreturns
selected_concentrationsbins, chem_labels=Nonedict
        Extract and return the concentration values of one or more (use None for all) chemicals,
        in one or more bins.
        The value is returned as a dictionary where the keys are bin addresses, and the values are dicts of
        concentration values for the various chemicals (identified by their labels)
            EXAMPLE:
                    {   (0,0): {"A": 1.3, "B": 3.9},
                        (3,5): {"A": 4.6, "B": 2.7}
                    }

        :param bins:    Bin address (pair of integers), or list of bin addresses. Use None to indicate all
        :param chem_labels:  Chemical label, or list of labels. Use None to indicate all
        :return:        A dict indexed by bin address
        

UPDATE SYSTEM

nameargumentsreturns
assert_valid_binbin_address: (int,int)None
        Raise an Exception if the given bin address isn't valid

        :param bin_address: A pair of integers identifying a bin in the 2D system
        :return:            None
        
nameargumentsreturns
set_bin_concbin_address: (int, int), chem_label :str, conc: floatNone
        Assign the requested concentration value to the bin with the given address,
        for the specified chemical species

        :param bin_address: A pair with the zero-based bin numbers of the desired cell, in the x- and y-coordinates
        :param chem_label:  String with the label to identify the chemical of interest
        :param conc:        The desired concentration value to assign to the specified location
        :return:            None
        
nameargumentsreturns
inject_conc_to_binbin_address: (int, int), chem_index: int, delta_conc: float, zero_clip = FalseNone
        Add the requested concentration to the cell with the given address, for the specified chemical species

        :param bin_address: A pair with the zero-based bin numbers of the desired cell, in the x- and y-coordinates
        :param chem_index:  Zero-based index to identify a specific chemical species
        :param delta_conc:  The concentration to add to the specified location
        :param zero_clip:   If True, any requested increment causing a concentration dip below zero, will make the concentration zero;
                                otherwise, an Exception will be raised
        :return:                None
        
nameargumentsreturns
set_bin_conc_all_speciesbin_address: (int, int), conc_list: [float]None
        Assign the requested concentration values to the cell with the given index,
        for all the chemical species in their index order

        :param bin_address: A pair with the zero-based bin numbers of the desired cell, in the x- and y-coordinates
        :param conc_list:   A list with the desired concentration values to assign to the specified location
        :return:            None
        
nameargumentsreturns
set_species_concconc_data: Union[list, tuple, np.ndarray], species_index=None, species_name=NoneNone
        For the single specified chemical species, assign the requested list of concentration values to all the bins,
        in row order first (top to bottom) and then in column order.

        EXAMPLE:  set_species_conc([[1, 2, 3], [4, 5, 6]], species_index=0)
                  will set the system state, for the specified chemical, to:
                            [1, 2, 3]
                            [4, 5, 6]

        :param conc_data:       A list, tuple or Numpy array with the desired concentration values
                                    to assign to all the bins.
                                    The dimensions must match the system's dimensions.
        :param species_index:   Zero-based index to identify a specific chemical species
        :param species_name:    (OPTIONAL) If provided, it over-rides the value for species_index
        :return:                None
        

UTILITIES

nameargumentsreturns
check_mass_conservationexpected :float, chem_label=None, chem_index=Nonebool
        Check whether the sum of all the concentrations of the specified chemical,
        across all bins, adds up to the passed value

        :param expected:
        :param chem_label:  String with the label to identify the chemical of interest
        :param chem_index:  Integer to identify the chemical of interest.  Cannot specify both chem_label and chem_index

        :return:
        

HISTORY

nameargumentsreturns
enable_historybins=None, frequency=1, chem_labels=None, take_snapshot=FalseNone
        Request history capture, with the specified parameters.
        If history was already enabled, this function can be used to alter its capture parameters.

        :param bins:            Bin address (pair of integers), or list of bin addresses. Use None to indicate all
        :param frequency:
        :param chem_labels:     [OPTIONAL] List of chemicals to include in the history;
                                    if None (default), include them all.
        :param take_snapshot:   If True, a snapshot of the system's current configuration is added to the history

        :return:                None
        
nameargumentsreturns
get_bin_historybin_address :(int,int)pd.DataFrame
        Get the concentration history at the given bin(s) of all the chemicals
        whose history was requested by a call of enable_history()

        :param bin_address: A single bin address (a pair of integers)
        :return:            A Pandas data frame
        
nameargumentsreturns
capture_snapshotstep_count=NoneNone
        Add to the system history (if enabled) a snapshot of (part of) the current data

        :param step_count:
        :return:            None
        

SIMULATIONS

nameargumentsreturns
diffusetotal_duration=None, time_step=None, n_steps=None, h=1, algorithm="5_point"dict
        Uniform-step diffusion, with 2 out of 3 criteria specified:
            1) until reaching, or just exceeding, the desired time duration
            2) using the given time step
            3) carrying out the specified number of steps

        :param total_duration:  The overall time advance (i.e. time_step * n_steps)
        :param time_step:       The size of each time step
        :param n_steps:         The desired number of steps
        :param h:               Distance between consecutive bins in both the x- and y-directions
                                    (For now, they must be equal)
        :param algorithm:       (OPTIONAL) String with a name specifying the method to use to solve the diffusion equation.
                                    Currently available options: "5_point"
        :return:                A dictionary with data about the status of the operation
                                    (for now, just the number of steps run; key: "steps")
        
nameargumentsreturns
diffuse_steptime_step, h=1, algorithm="5_point"None
        Diffuse all the species for the given time step, across all bins;
        clear the delta_diffusion array, and then re-compute it from all the species.

        IMPORTANT: the actual system concentrations are NOT changed.

        :param time_step:   Time step over which to carry out the diffusion
                            If too large - as determined by the method is_excessive() - an Exception will be raised
        :param h:           Distance between consecutive bins in both the x- and y-directions
                                (for now, they must be equal)
        :param algorithm:   String with a name specifying the method to use to solve the diffusion equation.
                                Currently available options: "5_point"
        :return:            None (the array in the class variable "delta_diffusion" gets set)
        
nameargumentsreturns
diffuse_step_single_speciestime_step: float, h: float, species_index=0, algorithm="5_point"np.array
        Diffuse the specified single chemical species, for the given time step, across all bins,
        and return a 2-D array of the changes in concentration ("Delta concentration")
        for the given species across all bins.

        IMPORTANT: the actual system concentrations are NOT changed.

        We're assuming an isolated environment, with nothing diffusing thru the "walls"

        EXPLANATION of the methodology:  https://life123.science/diffusion

        :param time_step:       Delta time over which to carry out this single diffusion step
        :param species_index:   ID (in the form of an integer index) of the chemical species under consideration
        :param h:               Distance between consecutive bins, ASSUMED the same in both directions
        :param algorithm:       String with a name specifying the method to use to solve the diffusion equation.
                                    Currently available options: "5_point"

        :return:                A 2-D Numpy array with the CHANGE in concentration for the given species across all bins
        
nameargumentsreturns
convolution_5_point_stencilincrement_matrix, species_index, effective_diffNone
        Carry out a 2-D convolution operation on increment_matrix,
        with a tile of size 3 that implements a 5-point stencil

        :param increment_matrix:A Numpy matrix of the correct size
        :param species_index:   Integer to identify the chemical of interest
        :param effective_diff:
        :return:                None (increment_matrix gets modified)
        
nameargumentsreturns
reacttotal_duration=None, time_step=None, n_steps=NoneNone
        Update the system concentrations as a result of all the reactions in all bins.
        CAUTION : NO diffusion is taken into account.

        The duration and granularity of the reactions is specified with 2 out of the 3 parameters:
            total_duration, time_step, n_steps

        For each bin, process all the reactions in it - based on
        the INITIAL concentrations (prior to this reaction step),
        which are used as the basis for all the reactions.

        :param total_duration:  The overall time advance (i.e. time_step * n_steps)
        :param time_step:       The size of each time step
        :param n_steps:         The desired number of steps
        :return:                None
        
nameargumentsreturns
reaction_stepdelta_time: floatNone
        Compute and store the incremental concentration changes in all bins,
        from all reactions,
        for a single time step of duration delta_time.

        The incremental concentration changes are stored in the class variable
        "delta_reactions", which contains a Numpy array that gets cleared and set.

        IMPORTANT: the actual system concentrations are NOT changed.

        For each bin, process all the reactions in it - based on
        the INITIAL concentrations (prior to this reaction step),
        which are used as the basis for all the reactions.

        :param delta_time:  The time duration of the reaction step - assumed to be small enough that the
                            concentration won't vary significantly during this span
        :return:            None (note: the class variable "delta_reactions" gets updated)
        
nameargumentsreturns
react_diffusetotal_duration=None, time_step=None, n_steps=None, h = 1None
        It expects 2 out of the following 3 arguments:  total_duration, time_step, n_steps
        Perform a series of reaction and diffusion constant time steps.

        :param total_duration:  The overall time advance (i.e. time_step * n_steps)
        :param time_step:       The size of each constant time step
        :param n_steps:         The desired number of constant steps
        :param h:               Distance between consecutive bins in both the x- and y-directions
                                    (for now, they must be equal)
        :return:                None
        

VISUALIZATION

nameargumentsreturns
heatmap_single_chem_greyscalechem_label :str, title_prefix = "", width=None, height=550, cartesian=Truepgo.Figure
        Create and return a greyscale heatmap (a Plotly Figure object) of the 2D concentrations
        of the specified single chemical, using the current system data.

        :param chem_label:  Label to identify the chemical of interest
        :param title_prefix:[OPTIONAL] A string to prefix to the auto-generated Heatmap title
        :param width:       [OPTIONAL] If not specified, all the available space width is used
        :param height:      [OPTIONAL] Height of the heatmap graphics
        :param cartesian:   If True (default) a Cartesian grid coordinate is used, with y-bin numbers increasing up
        :return:            A Plotly "Figure" object
        
nameargumentsreturns
heatmap_single_chemchem_label :str, title_prefix = "", width=None, height=550, color=None, cartesian=Truepgo.Figure
        Create and return a heatmap (a Plotly Figure object) of the 2D concentration
        of the specified single chemical, using the current system data.
        A gradient of the specified color is used (grayscale if not color specified.)

        Note: if requesting a greyscale, this function is almost identical to heatmap_single_chem_greyscale(),
              but shows a little more info when the mouse hovers over the heatmap bins

        :param chem_label:  Label to identify the chemical of interest
        :param title_prefix:[OPTIONAL] A string to prefix to the auto-generated Heatmap title
        :param height:      [OPTIONAL] Height of the heatmap graphics
        :param width:       [OPTIONAL] If not specified, all the available space width is used
        :param color:       [OPTIONAL] The standard (CSS) name of the color to use for the gradient;
                                if not specified, a grayscale is used
        :param cartesian:   If True (default) a Cartesian grid coordinate is used, with y-bin numbers increasing up
        :return:            A Plotly "Figure" object
        
nameargumentsreturns
system_heatmapschem_labels=None, title_prefix = "", height=None, colors=None, cartesian=Truepgo.Figure
        Prepare and return a Plotly Figure object containing a grid of heatmaps (up to a max of 12)

        :param chem_labels: [OPTIONAL] List of Labels to identify the chemicals of interest;
                                if not specified, it means ALL chemicals.
                                The max number of heatmaps that can be shown together is 12
        :param title_prefix:[OPTIONAL] A string to prefix to the auto-generated title for the grid of heatmaps
        :param height:      [OPTIONAL] Height of the overall grid of heatmaps
        :param colors:      [OPTIONAL] List of CSS color names for each of the heatmaps.
                                If provided, its length must match that of the data;
                                if None, then use the registered colors (if specified),
                                or the hardwired defaults as a last resort
        :param cartesian:   If True (default) a Cartesian grid coordinate is used, with y-bin numbers increasing up
        :return:            A Plotly "Figure" object
        
nameargumentsreturns
plot_history_single_binbin_address :(int,int), colors=None, title=None, smoothed=Falsepgo.Figure
        Using plotly, draw the plots of chemical concentration values over time at the specified bin,
        based on historical data that was saved when running simulations.
        The plotting will involve the chemicals for which history-keeping was requested for this given bin.

        Note: if this plot is to be later combined with others, use PlotlyHelper.combine_plots()
              EXAMPLE:
                    from life123 import PlotlyHelper
                    p1 = plot_history(various args, show=False)
                    p2 = plot_history(various args, show=False)
                    PlotlyHelper.combine_plots([p1, p2], other optional args)

        :param bin_address: A single bin address (a pair of integers)
        :param colors:      [OPTIONAL] List of CSS color names for each of the heatmaps.
                                If provided, its length must match that of the data;
                                    if None, then use the registered colors (if specified),
                                    or the hardwired defaults as a last resort
        :param title:       [OPTIONAL] Label for the top of the plot.  If not passed, a default is used
        :param smoothed:    [OPTIONAL] If True, a spline is used to smooth the lines;
                                otherwise (default), line segments are used
        :return:            A plotly "Figure" object; an Exception is raised if no historical data is found