### Import libraries and define selected genes Source: https://simtissue.readthedocs.io/en/latest/tutorial/tissue_simulation.html Imports necessary libraries and defines a list of genes to simulate. This is the initial setup for the tissue simulation tutorial. ```python from pathlib import Path import tifffile import numpy as np from simtissue.arbitrary_shape import generate_ellipse import time import random from tqdm import tqdm from scipy import ndimage as ndi from skimage.segmentation import watershed from matplotlib import pyplot as plt from scipy import sparse import pandas import scanpy from simtissue.control_expression import filter_simulation, sim_spots_from_ref_anndata from simtissue.tissue import simulate_single_cell_mask ### LIST OF GENE TO SIMULATE selected_gene = ['Atp6v0d2', 'Abcg1',# AM 'Rtkn2', 'Igfbp2', #AT1 'Sftpc','Cxcl15', #AT2, 'Cd79a', #B_cells 'Ms4a2', 'Fcer1a', #Basophils 'Ccdc153', #Ciliated 'Scgb3a2', 'Scgb1a1',#Club 'Cst3',#DC 'Cdh5', 'Clec14a', #EC 'Inmt', 'Pcolce2', # Fibroblasts 'C1qc', 'C1qa', 'C1qb', # 'C3ar1', #IM 'Upk3b',# Mesotheliocytes 'Ifitm6','Plac8',# Monocytes 'Ms4a4b', 'Ccl5', 'Hcst', # NK_T_cells 'Gzma', 'Ncr1',# NK_cells 'S100a9',# Neutrophils 'Mmrn1',#Platelets 'Acta2','Myh11', # SMC 'Cd3g', 'Cd3d' #T_cells ] ref_anndata = scanpy.read('/media/tom/T7/simulation/test_set_simulation/test_anndata.h5ad') ``` -------------------------------- ### Sample transcriptomic profile with sim_spots_from_ref_anndata() Source: https://simtissue.readthedocs.io/en/latest/tutorial/tissue_simulation.html Loops over cell mask files, calls sim_spots_from_ref_anndata() to generate anndata and dataframe, then saves them to specified paths. Uses scaling_factor=3 and remove_neighbors=True with max_dist=0.3. ```python path_to_save_anndata = "/media/tom/T7/simulation/test_set_simulation/anndata/" path_to_save_df = "/media/tom/T7/simulation/test_set_simulation/dataframe/" list_anndata = [] for path_ic in Path(path_save_ind_cyto).glob("*.npy"): cell_mask = np.load(path_ic) anndata, df_spots = sim_spots_from_ref_anndata( ref_anndata = ref_anndata, cell_mask = cell_mask, image_name = 'test', annotation_column = "cell_ID", selected_gene = selected_gene, remove_neighbors = True, max_dist = 0.3, dict_scale = {"x":0.103, 'y':0.103, "z":0.300}, scaling_factor=3 ) list_anndata.append(anndata) anndata.write_h5ad(str(Path(path_to_save_anndata) /(path_ic.stem + '.h5ad'))) df_spots.to_csv(Path(path_to_save_df) /(path_ic.stem + '.npy')) ``` -------------------------------- ### Import libraries for checkerboard simulation Source: https://simtissue.readthedocs.io/en/latest/tutorial/checkerboard_shape.html Imports required for the tutorial: numpy, matplotlib, scipy.ndimage, scikit-image, sklearn's sample_without_replacement, and scipy.sparse.csr_array. ```python import numpy as np from matplotlib import pyplot as plt from scipy import ndimage as ndi import skimage from sklearn.utils.random import sample_without_replacement from scipy.sparse import csr_array ``` -------------------------------- ### Import simtissue modules Source: https://simtissue.readthedocs.io/en/latest/tutorial/checkerboard_shape.html Imports simtissue modules and functions used in the tutorial: checkerboard_mask, generate_ellipse, add_sphere_nuclei, plot_contour, create_fix_profile, simulate_arbritrary_expression, and get_dict_coord_map. ```python import sys import simtissue from simtissue.arbitrary_shape import checkerboard_mask, generate_ellipse, add_sphere_nuclei from simtissue.plot import plot_contour from simtissue.control_expression import create_fix_profile, simulate_arbritrary_expression from simtissue.utils import get_dict_coord_map ``` -------------------------------- ### Load simulation with pickle Source: https://simtissue.readthedocs.io/en/latest/tutorial/checkerboard_shape.html Loads the previously saved simulation from the pickle file and displays the AnnData object. The output shows the same structure as before. ```python file_pi2 = open(filename, 'rb') anndata = pickle.load(file_pi2) anndata ``` -------------------------------- ### Save simulation with pickle Source: https://simtissue.readthedocs.io/en/latest/tutorial/checkerboard_shape.html Saves the simulated AnnData object to a pickle file named 'simulated_image.h5ad' using pickle.dump with protocol -1. ```python import pickle from pathlib import Path filename = "simulated_image.h5ad" with open(filename, 'wb') as handle: pickle.dump(anndata, handle, -1) ``` -------------------------------- ### Generate cytoplasm masks with simulate_single_cell_mask() Source: https://simtissue.readthedocs.io/en/latest/tutorial/tissue_simulation.html Loop over nuclei mask TIFF files, crop them to the cytoplasm, then run `simulate_single_cell_mask()` to produce individual cytoplasm masks. Uses `limiter`tiffile` and `numpy`, and saves results as `.npy` files. ```python path_folder_mask_nuclei = "/media/tom/T7/simulation/test_set_simulation/mask_nuclei" path_folder_cytoplasm = "/media/tom/T7/simulation/test_set_simulation/cytoplasm_mask" path_save_ind_cyto = "/media/tom/T7/simulation/test_set_simulation/individual_cytoplasm" for path_mask_nuclei in Path(path_folder_mask_nuclei).glob('*.tiff'): print(path_mask_nuclei) ##load nuclei center_nuclei = tifffile.imread(path_mask_nuclei)[20:35, 200:1000, :1200] ## load cytoplasm mask_cyto = np.load(Path(path_folder_cytoplasm) / (path_mask_nuclei.name + ".npy"))[20:35, 200:1000, :1200] ## ind_cyto = simulate_single_cell_mask( mask_nuclei, cyto = mask_cyto, scale=np.array([3, 1.03, 1.03]), intervals_speed=[[0.5, 0.8], [1.3, 4]], median_kernel=7, random_seed = None ) np.save(Path(path_save_ind_cyto) / path_mask_nuclei.stem, ind_cyto) ``` -------------------------------- ### simtissue.control_expression.sim_spots_from_ref_anndata Source: https://simtissue.readthedocs.io/en/latest/api/control_expression.html Simulates the expression of a list of genes in a cell mask by sampling RNA profiles from a reference anndata object. RNA molecules are then sampled from a uniform spatial distribution in each cell. ```APIDOC ## sim_spots_from_ref_anndata ### Description This function simulate the expression of a list of genes in a mask of cytoplasm. It sample each RNA profile from a reference anndata object. The RNA molecule are then sampled from a uniform spatial distribution in each cell. ### Parameters - **ref_anndata** (anndata object) - Required - andata object with the reference expression profile to sample. - **cell_mask** (np.ndarray) - Required - Cell mask. - **selected_gene** (list) - Required - List of genes to simulate. Example: ['gene1', 'gene2'] from the reference anndata. - **image_name** (str) - Optional - Name of the image to add in annData. Default: ''. - **annotation_column** (str) - Optional - Column name of the cell type in the reference anndata. Default: 'cell_ID'. - **remove_neighbors** (bool) - Optional - If True remove the RNA molecules that are too close. Default: True. - **max_dist** (float) - Optional - Max distance between spots to merge if remove_neighbors is True. Default: 0.3. - **dict_scale** (dict) - Optional - Scale of the image in z,y,x in µm. Default: {'x': 0.103, 'y': 0.103, 'z': 0.3}. - **random_indice** (list) - Optional - If not None, list of cell index to sample from the reference anndata. Default: None. - **scaling_factor** (int) - Optional - Scaling factor. Default: 3. ### Returns - an **anndata object** (not explicitly stated) with simulated expression. ``` -------------------------------- ### simtissue.control_expression.create_fix_profile Source: https://simtissue.readthedocs.io/en/latest/api/control_expression.html Associates each cell index to a fixed RNA profile based on a dictionary of profiles and a cell type distribution. It takes two dictionaries and returns an RNA, while also returning an expression vector for each cell. ```APIDOC ## create_fix_profile ### Description Associates each cell index to a fixed RNA profile. ### Parameters - **dict_profile** (dict) - Required - Dictionary defining the RNA profile of each cell type. Example: {'typeA': [120, 0], 'typeB': [0, 10]} - **cell_type_distribution** (dict) - Required - Dictionary of the cell type distribution. Example: {'typeA': list(range(0, 110, 2)), 'typeB': list(range(1, 110, 2))} ### Returns - **dict_cell_type_label_rna** - {cell_type : {cell_id : expression vector}} - **dico_cell_index** - {cell_id : {type: cell_type, rnaseq : expression vector}} ``` -------------------------------- ### Plot final simulation with expression spots Source: https://simtissue.readthedocs.io/en/latest/tutorial/checkerboard_shape.html Plots the final simulation contour with nuclei and expression spots. Uses dico_color to map gene A to red and gene B to blue, with spot_size=3. The output includes the same warning as before. ```python plot_contour(mask_cyto = mask_cyto, mask_nuclei = mask_nuclei, figsize = (15,15), anndata = anndata, dico_color = {"A" : "r", "B": "b"}, spot_size = 3) ``` -------------------------------- ### generate_ellipse(masks: ndarray, cell_id: int, radius_zyx: list = None, rad_min: float = 0.5, rad_max: float = 2) Source: https://simtissue.readthedocs.io/en/latest/api/arbitrary_shape.html Generates nuclei as an ellipse in the chosen cell. Returns the ellipse mask and ellipse parameters. ```APIDOC ## generate_ellipse(masks: ndarray, cell_id: int, radius_zyx: list = None, rad_min: float = 0.5, rad_max: float = 2) ### Description Generate nuclei as ellipse in the chosen cell. ### Parameters - **masks** (np.ndarray) - Required - Cell mask. - **cell_id** (int) - Required - Index of the chosen cell. - **radius_zyx** (list) - Optional - List [Rz, Ry, Rx] of the fixed parameters of the ellipse. Leave it None to choose these parameters randomly between rad_min and rad_max. - **rad_min** (float) - Optional - Minimum value of the radius if radius_zyx is None. Default is 0.5. - **rad_max** (float) - Optional - Maximum value of the radius if radius_zyx is None. Default is 2. ### Returns - **ellipse mask** - The generated ellipse mask. - **ellipse parameter** - The parameters of the ellipse. ``` -------------------------------- ### add_sphere_nuclei(mask_cyto: ndarray, cube_square_size: int = 100, nuclei_radius: int = 25, list_nuclei: list = []) Source: https://simtissue.readthedocs.io/en/latest/api/arbitrary_shape.html Adds nuclei as spheres in the chosen cell. Returns the mask of the nuclei. ```APIDOC ## add_sphere_nuclei(mask_cyto: ndarray, cube_square_size: int = 100, nuclei_radius: int = 25, list_nuclei: list = []) ### Description Add nuclei as sphere in the chosen cell. ### Parameters - **mask_cyto** (np.ndarray) - Required - Cell mask. - **cube_square_size** (int) - Optional - Size of the cube in pixels. Default is 100. - **nuclei_radius** (float) - Optional - Radius of the nuclei in pixels as a percentage of cube_square_size. Default is 25. - **list_nuclei** (list) - Optional - List of nuclei to add. Default is empty list. ### Returns - **mask of the nuclei** - The generated nuclei mask. ``` -------------------------------- ### Simulate arbitrary cell expression with simulate_arbritrary_expression Source: https://simtissue.readthedocs.io/en/latest/tutorial/checkerboard_shape.html Simulates arbitrary cell expression using simulate_arbritrary_expression. Defines RNA profiles for two cell types (typeA: [50,0], typeB: [0,200]), assigns even indices to typeA and odd to typeB, and creates an AnnData object with 110 observations and 2 variables. ```python ### generate_anndata ## RNA profile of each cell type genes_list_to_simulate = ['A', 'B'] dict_profile = {'typeA': [50, 0], 'typeB': [0, 200] } ## cell type of each cell index cell_index_typeA = [i for i in range(1, 111) if i % 2 == 0] cell_index_typeB = [i for i in range(1, 111) if i % 2 == 1] cell_type_distribution={'typeA': cell_index_typeA, 'typeB': cell_index_typeB,} image_name = "image0" ## get the anndata with simulate_arbritrary_expression() anndata = simulate_arbritrary_expression(dict_profile, cell_type_distribution, mask_cyto = mask_cyto, genes_list_to_simulate = ['A', 'B'], image_name = "image0" ) anndata ``` -------------------------------- ### Plot final simulation with matplotlib Source: https://simtissue.readthedocs.io/en/latest/tutorial/tissue_simulation.html Reads the saved dataframe, loads a nuclei mask TIFF, and plots the spots for each selected gene over the nuclei image. Uses gist_gray colormap and scatter with s=1. ```python from matplotlib import colors import pandas as pd df_spots = pd.read_csv(Path(path_to_save_df) /(path_ic.stem + '.npy')) mask_nuclei = tifffile.imread(Path(path_folder_mask_nuclei) / (path_ic.stem + '.tiff'))[20:35, 200:1000, :1200] mip_nuclei = np.amax(mask_nuclei, 0) dico_spots_pos = {} for gene in selected_gene: y = df_spots[df_spots["gene"] == gene]["y"] x = df_spots[df_spots["gene"] == gene]["x"] dico_spots_pos[gene] = list(zip( y, x)) fig, ax = plt.subplots(figsize = (15,15)) ax.imshow(mip_nuclei > 0, cmap='gist_gray', alpha = 0.8) ax.imshow(mip_nuclei, cmap='gist_gray', alpha = 0.8) for gene in dico_spots_pos.keys(): if len(dico_spots_pos[gene]) == 0: continue ax.scatter(np.array(dico_spots_pos[gene])[:,1], np.array(dico_spots_pos[gene])[:,0], cmap="Pastel1", # gene_color_dico[gene], #'#%02X%02X%02X' % (r(),r(),r()), s=1) plt.show() ``` -------------------------------- ### elbow_grid_cube() Source: https://simtissue.readthedocs.io/en/latest/api/arbitrary_shape.html Generates a grid of elbow shapes with hard-coded dimensions. Returns mask_cyto and mask_nuclei. ```APIDOC ## elbow_grid_cube() ### Description Function to generate grid of elbow shape. The size of the cell mask is hard coded to 1800x1600 and the size square cell is 100 pixel, the size of nuclei is 25 pixel. ### Parameters None. ### Returns - **mask_cyto** - The cell mask. - **mask_nuclei** - The nuclei mask. ``` -------------------------------- ### simtissue.control_expression.simulate_arbritrary_expression Source: https://simtissue.readthedocs.io/en/latest/api/control_expression.html Simulates the expression of a list of genes in a cytoplasm mask. The RNA positions are sampled from a uniform spatial distribution in the cytoplasm. ```APIDOC ## simulate_arbritrary_expression ### Description This function simulate the expression of a list of genes in a mask of cytoplasm. The rna position are sample from a uniform spatial distribution in the cytoplasm. ### Parameters - **dict_profile** (dict) - Required - Dictionary of the expression profile of each cell type. Example: {'typeA': [120, 0], 'typeB': [0, 10]} - **cell_type_distribution** (dict) - Required - Dictionary of the cell type distribution. Example: {'typeA': list(range(0, 110, 2)), 'typeB': list(range(1, 110, 2))} - **mask_cyto** (np.ndarray) - Required - Cytoplasm mask. - **genes_list_to_simulate** - Required - List of genes to simulate. Example: ['gene1', 'gene2'] - **image_name** (str) - Optional - Name of the image to add in annData. Default: 'img0' ### Returns - **anndata object** - anndata object with the simulated expression profile and coordinates. ``` -------------------------------- ### checkerboard_mask(shape=[54, 1000, 1100], cube_square_size=100) Source: https://simtissue.readthedocs.io/en/latest/api/arbitrary_shape.html Generates a checkerboard cell mask with specified dimensions and cube size. Returns the checkerboard mask. ```APIDOC ## checkerboard_mask(shape=[54, 1000, 1100], cube_square_size=100) ### Description Generate checkerboard cell mask. ### Parameters - **shape** (list[int]) - Optional - Dimension of the mask [z, y, x]. Default is [54, 1000, 1100]. - **cube_square_size** (int) - Optional - Size of the cube in pixels. Default is 100. ### Returns - **checkerboard mask** - The generated checkerboard mask. ``` -------------------------------- ### simtissue.control_expression.filter_simulation Source: https://simtissue.readthedocs.io/en/latest/api/control_expression.html Merges overlapping spots as a single spot. It takes a list of spots positions and merges them based on a maximum distance. ```APIDOC ## filter_simulation ### Description This function Merge overlapping spots as a single spot. ### Parameters - **spots_position** (list) - Required - List of spots position. - **max_dist** (float) - Optional - Max distance between spots to merge in the scale of dict_scale. Default: 3. - **dict_scale** (dict) - Optional - Scale dictionary. Default: {'x': 1, 'y': 1, 'z': 1}. ### Returns - **list of spots position with merged spots** - list of the spots positions after merging. ``` -------------------------------- ### simtissue.tissue.simulate_single_cell_mask() Source: https://simtissue.readthedocs.io/en/latest/api/tissue.html Generates a single cell mask from a nuclei segmentation mask. Individual cytoplasms are defined by growing cells from segmented nuclei, with each cell growing at a random speed to add irregularity in cell size. ```APIDOC ## simulate_single_cell_mask() ### Description Generates a single cell mask from a nuclei segmentation mask. Individual cytoplasms are defined by growing cells from segmented nuclei, with each cell growing at a random speed to add irregularity in cell size. ### Function Signature simtissue.tissue.simulate_single_cell_mask(mask_nuclei: ndarray, cyto: ndarray = None, scale: ndarray = array([3., 1.03, 1.03]), intervals_speed: list = [[0.5, 0.8], [1.3, 4]], median_kernel = 7, random_seed = None) ### Parameters - **mask_nuclei** (np.ndarray) - Required - Nuclei segmentation mask. - **cyto** (np.ndarray) - Optional - Cytoplasm segmentation mask to simulate area without cell. - **scale** (np.ndarray) - Optional - Scale of the image in z, y, x. Default: array([3., 1.03, 1.03]). - **intervals_speed** (list) - Optional - Speed range of the cell growth. Default: [[0.5, 0.8], [1.3, 4]]. - **median_kernel** (int) - Optional - Median kernel size to smooth the cell mask. Default: 7. - **random_seed** (int) - Optional - Random seed for reproducibility. ### Returns - **cell mask** - The generated cell mask. ``` -------------------------------- ### remove_nuclei(mask_nuclei: ndarray, percent_to_remove: float = 0.5, list_nuc_to_keep: list = None) Source: https://simtissue.readthedocs.io/en/latest/api/arbitrary_shape.html Removes nuclei from the existing nuclei mask to generate cells without nuclei, as in smFISH experiments. Returns the mask of nuclei with some removed. ```APIDOC ## remove_nuclei(mask_nuclei: ndarray, percent_to_remove: float = 0.5, list_nuc_to_keep: list = None) ### Description Remove nuclei from the existing nuclei mask to generate cell without nuclei like in smFISH experiment. ### Parameters - **mask_nuclei** (np.ndarray) - Required - Nuclei mask. - **percent_to_remove** (float) - Optional - Percent of nuclei to remove. Default is 0.5. - **list_nuc_to_keep** (list) - Optional - List of nuclei to keep. Default is None. ### Returns - **mask of the nuclei without some nuclei** - The resulting nuclei mask. ``` -------------------------------- ### Generate checkerboard mask and plot contour Source: https://simtissue.readthedocs.io/en/latest/tutorial/checkerboard_shape.html Generates a checkerboard mask of shape [1, 1000, 1100] with cube_square_size=100 and plots its contour. The output includes a warning 'list index out of range' and 'no contour for cell 110.0'. ```python mask_cyto = checkerboard_mask(shape = [1, 1000, 1100], cube_square_size = 100) plot_contour(mask_cyto = mask_cyto, figsize = (5,5)) ``` -------------------------------- ### Remove percentage of nuclei with remove_nuclei Source: https://simtissue.readthedocs.io/en/latest/tutorial/tissue_simulation.html Loop over nuclei masks, load each, then call `remove_nuclei` to randomly remove a percentage of its nuclei. The result is saved the same way as the original. Note: `libreria` `plural` argument is `percent_to_remove` (0.1 meaning 10%). ```python path_folder_mask_nuclei_remove = "/media/tom/T7/simulation/test_set_simulation/mask_nuclei" Path(path_folder_mask_nuclei_remove, exist_ok=True) from simtissue.arbitrary_shape import remove_nuclei for path_mask_nuclei in Path(path_folder_mask_nuclei).glob('*.tiff'): print(path_mask_nuclei) print(path_mask_nuclei.name + ".npy") ##load nuclei mask_nuclei = tifffile.imread(path_mask_nuclei)[20:35, 200:1000, :1200] new_mask_nuclei = remove_nuclei( mask_nuclei, percent_to_remove = 0.1, list_nuc_to_keep = None) np.save(Path(path_folder_mask_nuclei_remove) / path_mask_nuclei.stem, ind_cyto) ``` -------------------------------- ### Add nuclei to checkerboard mask Source: https://simtissue.readthedocs.io/en/latest/tutorial/checkerboard_shape.html Adds nuclei to the checkerboard mask. It leaves 20% of cells without nuclei by sampling 80% of unique cell indices, then calls add_sphere_nuclei with nuclei_radius=25 and plots the contour. The output includes the same warning as before. ```python ## leave 20% of the cells without cytoplasm list_nuclei_unique = np.unique(mask_cyto) index = sample_without_replacement(len(list_nuclei_unique), int(0.80 * len(list_nuclei_unique))) list_nuclei = list_nuclei_unique[index] mask_nuclei = add_sphere_nuclei(mask_cyto = mask_cyto, cube_square_size = 100, nuclei_radius = 25, list_nuclei = list_nuclei) plot_contour(mask_cyto = mask_cyto, mask_nuclei = mask_nuclei, figsize = (5,5)) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.