### CellChat Basic Setup Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_multiomics_data.html Basic setup for CellChat analysis, including loading the library and creating a CellChat object. Assumes a Seurat object is available. ```r library(CellChat) # Load the Seurat object # seurat_obj <- readRDS("path/to/your/seurat_object.rds") # Create CellChat object # cellchat <- createCellChat(object = seurat_obj, group.by = "cell_type_column") # Set the database directory # CellChatDB <- CellChatDB.mouse # showDatabaseCategory(CellChatDB) # Use CellChatDB.mouse or CellChatDB.human # Set the organism # CellChat <- setVariable(CellChat, organism = "mouse") # Subset the database by cell-cell communication pathways # CellChat <- subsetData(CellChat, assay = "RNA", slot = "data") # options($=TRUE) # CellChat <- identifyOverExpressedGenes(CellChat) # CellChat <- identifyOverExpressedInteractions(CellChat) # project data and compute cell-cell communication probabilities # CellChat <- computeCommunProb(CellChat, raw.use = TRUE) # Filter out the cell-cell communication that are inferred as global # CellChat <- filterCommunication(CellChat, min.cells = 10) # Infer the signaling pathway # CellChat <- inferPathway(CellChat) # Compute communication probability and 통계 # CellChat <- computeCommunProbPathway(CellChat) # Calculate the aggregated cell-cell communication network # CellChat <- aggregateNet(CellChat) # Plot all the interactions ofany signaling pathway # groupSize <- as.numeric(table(CellChat@idents)) # par(mfrow = c(3,4), xpd = TRUE) # netVisual_circle(CellChat@net$count, vertex.weight = groupSize, weight.scale = T, label.edge= F, title.name = "Number of interactions") # netVisual_circle(CellChat@net$weight, vertex.weight = groupSize, weight.scale = T, label.edge= F, title.name = "Interaction weights/strength") # Plot aggregated cell-cell communication network # mat <- CellChat@net$weight # par(mfrow = c(3,4), xpd = TRUE) # for (i in 1:nrow(mat)) { # # ietwork for each ligand-receptor pair # netVisual_heatmap(CellChat, signaling = rownames(mat)[i], color.heatmap = "Reds") # } # Save CellChat object # saveRDS(CellChat, file = "cellchat_object.rds") # Load CellChat object # cellchat <- readRDS("cellchat_object.rds") ``` -------------------------------- ### Create a New CellChat Database (Example) Source: https://github.com/jinworks/cellchat/blob/main/tutorial/Update-CellChatDB.html Demonstrates creating a new CellChat database object from scratch. This example defines new interaction data and metadata. ```R new_data = data.frame(interaction_type = "paracrine", Ev = "ligand", De = "receptor", Evidence = "literature", PPI = "protein_protein_interaction", Annotation = "annotation", Evidence_novel = "novel", annotated_complex = "complex") new_meta = data.frame(CellGroup = "cell_type", CellID = "cell_id") new_cellchatdb = list(data = new_data, meta = new_meta) # Create a new CellChat database new_cellchatdb = list(data = new_data, meta = new_meta) ``` -------------------------------- ### Install CellChat Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_multiomics_data.html Install the CellChat package using BiocManager. Ensure you have R and BiocManager installed. ```r if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("CellChat") ``` -------------------------------- ### Install BiocNeighbors R Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Install the BiocNeighbors package using BiocManager if you encounter installation issues with Spatial CellChat. ```r BiocManager::install("BiocNeighbors") ``` -------------------------------- ### Initialize Affix Plugin Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_multiomics_data.html Initializes the affix plugin for Bootstrap. Use this to make elements stick to the viewport when scrolling. ```javascript +function(a) { "use strict"; function b(b) { return this.each(function() { var d = a(this), e = d.data("bs.affix"), f = "object" == typeof b && b; e || d.data("bs.affix", e = new c(this, f)), "string" == typeof b && e[b]() }) } var c = function(b, d) { this.options = a.extend({}, c.DEFAULTS, d), this.$target = a(this.options.target).on("scroll.bs.affix.data-api", a.proxy(this.checkPosition, this)).on("click.bs.affix.data-api", a.proxy(this.checkPositionWithEventLoop, this)), this.$element = a(b), this.affixed = null, this.unpin = null, this.pinnedOffset = null, this.checkPosition() }; c.VERSION = "3.3.5", c.RESET = "affix affix-top affix-bottom", c.DEFAULTS = { offset: 0, target: window }, c.prototype.getState = function(a, b, c, d) { var e = this.$target.scrollTop(), f = this.$element.offset(), g = this.$target.height(); if (null != c && "top" == this.affixed) return c > e ? "top" : !1; if ("bottom" == this.affixed) return null != c ? e + this.unpin <= f.top ? !1 : "bottom" : a - d >= e + g ? !1 : "bottom"; var h = null == this.affixed, i = h ? e : f.top, j = h ? g : b; return null != c && c >= e ? "top" : null != d && i + j >= a - d ? "bottom" : !1 }, c.prototype.getPinnedOffset = function() { if (this.pinnedOffset) return this.pinnedOffset; this.$element.removeClass(c.RESET).addClass("affix"); var a = this.$target.scrollTop(), b = this.$element.offset(); return this.pinnedOffset = b.top - a }, c.prototype.checkPositionWithEventLoop = function() { setTimeout(a.proxy(this.checkPosition, this), 1) }, c.prototype.checkPosition = function() { if (this.$element.is(":hidden")) return }; var d = a.fn.affix; a.fn.affix = b, a.fn.affix.Constructor = c, a.fn.affix.noConflict = function() { return a.fn.affix = d, this } }(jQuery) ``` -------------------------------- ### Install CellChat v1/v2 R Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Use this command to install the CellChat R package (v1/v2) from GitHub. Ensure devtools is installed. ```r devtools::install_github("jinworks/CellChat") ``` -------------------------------- ### Install Spatial CellChat R Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Use this command to install the Spatial CellChat R package from GitHub. Ensure devtools is installed. ```r devtools::install_github("jinworks/SpatialCellChat") ``` -------------------------------- ### Load and Prepare Data for Comparison Source: https://github.com/jinworks/cellchat/blob/main/tutorial/Comparison_analysis_of_multiple_datasets.html Loads and prepares data from multiple sources for comparative analysis. Ensure data is in a compatible format before proceeding. ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Load datasets df1 = pd.read_csv('dataset1.csv') df2 = pd.read_csv('dataset2.csv') df3 = pd.read_csv('dataset3.csv') # Basic preprocessing (example: handling missing values) df1.fillna(method='ffill', inplace=True) df2.fillna(method='ffill', inplace=True) df3.fillna(method='ffill', inplace=True) # Align columns if necessary (example: selecting common columns) common_cols = list(set(df1.columns) & set(df2.columns) & set(df3.columns)) df1 = df1[common_cols] df2 = df2[common_cols] df3 = df3[common_cols] print("Data loaded and preprocessed successfully.") ``` -------------------------------- ### Set Up CellChat with a Reference Database Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_transcriptomics_data.html Initialize CellChat with a cell-cell communication database. This step is crucial for identifying signaling ligands and receptors. The tutorial uses the human database by default. ```R # Set the cellchat database (e.g., human or mouse) # Use 'CellChatDB.human' or 'CellChatDB.mouse' # Download the database if not already present # CellChatDB <- CellChatDB.download.from.web(path = "/path/to/save/db") # cellchat <- addMeta(cellchat, meta = list(type = "spatial")) # Load the cellchat database CellChatDB <- CellChatDB.human # Use a subset of the database for faster computation if needed # Show available cell chat databases # showDatabaseCategory(CellChatDB) # Set the database for CellChat object cellchat <- setDB(cellchat, DB = CellChatDB) ``` -------------------------------- ### Install CellChat Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat-vignette.html Install the CellChat package from Bioconductor. Ensure you have R version 4.0 or higher. ```R if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") # Install CellChat from Bioconductor BiocManager::install("CellChat") ``` -------------------------------- ### Install ComplexHeatmap R Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Install the ComplexHeatmap R package from GitHub if needed for CellChat. ```r devtools::install_github("jokergoo/ComplexHeatmap") ``` -------------------------------- ### Initialize and Show Bootstrap Modal Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_transcriptomics_data.html This snippet demonstrates how to initialize and show a Bootstrap modal dialog. It handles event listeners for closing and focus management. ```javascript var d,e,f,g,h,i,j; +function(a){function b(b){return this.each(function(){var d=a(this),e=d.data("bs.modal"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b); e||d.data("bs.modal",e=new c(this,f)),"string"==typeof b?e[b]():f.show&&e.show()})} var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=!1,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded")},this)),a(document).on("keydown.bs.modal",a.proxy(function(a){27==a.which&&this.isShown&&this.hide()},this)),"undefined"==typeof this.options.allowFocusInput&& (this.options.allowFocusInput=!0)} c.VERSION="3.3.5",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={"backdrop":!0,"keyboard":!0,"show":!0,"remote":!1}, c.prototype.toggle=function(a){return this.isShown?this.hide():b.call(a,a)},c.prototype.show=function(){var c=this,d=a.Event("show.bs.modal",{relatedTarget:this});this.$element.trigger(d);if(d.isDefaultPrevented())return;this.$body.addClass("modal-open"),this.options.override= !0,this.checkScrollbar(),this.setScrollbar(),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(a.proxy(function(){c.$element.trigger("shown.bs.modal"),c.enforceFocus()},this))},c.prototype.hide=function(b){b&&b.preventDefault();var c=this;this.isShown=!!a(this.$element).trigger(b=a.Event("hide.bs.modal")).isDefaultPrevented();if(!this.isShown)return;a(document,'.modal-open').off('focusin.bs.modal'),this.$element.off('keydown.dismiss.bs.modal').off('click.dismiss.bs.modal').removeClass('in').one('transitionend',function(){c.$element.hide().trigger('hidden.bs.modal')}).emulateTransitionEnd(c.TRANSITION_DURATION)},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(a.proxy(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")},this))},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+e).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};f?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
","trigger":"hover focus","title":"","delay":0,"html":!1,"container":!1,"viewport":{"selector":"body","padding":0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={"click":!1,"hover":!1,"focus":!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this+" tooltip")} ``` -------------------------------- ### Install RcppML R Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Install the RcppML R package from GitHub if needed for Spatial CellChat. ```r devtools::install_github("zdebruine/RcppML") ``` -------------------------------- ### Initialize Tabsets Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat-vignette.html Builds tabsets for navigation. This is a common utility for organizing content within web pages. ```javascript $(document).ready(function () { window.buildTabsets("TOC"); }); ``` -------------------------------- ### Affix Plugin Initialization Source: https://github.com/jinworks/cellchat/blob/main/tutorial/Update-CellChatDB.html Initializes the affix plugin, which pins elements to the viewport when they reach a certain scroll position. Handles 'affix.bs.affix' and 'unaffix.bs.affix' events. ```javascript a(window).on("load.bs.affix.data-api", function(b) { a('[data-spy="affix"]').each(function() { var c = a(this) var d = c.data('offset') ? c.data('offset') : {} if (d.target) { d['target'] = '> ' + d.target } c.affix(d) }) }) ``` -------------------------------- ### Install ALRA R Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Install the ALRA R package from GitHub if needed for Spatial CellChat. ```r devtools::install_github("KlugerLab/ALRA") ``` -------------------------------- ### Install MERINGUE R Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Install the MERINGUE R package from GitHub if needed for Spatial CellChat. ```r devtools::install_github("JEFworks-Lab/MERINGUE") ``` -------------------------------- ### AJAX Request Setup and Execution with jQuery Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_multiomics_data.html Configures and initiates AJAX requests. Handles URL construction, data processing, cross-domain requests, and response handling. Includes mechanisms for global AJAX event handling. ```javascript var bt=C.location,wt={guid:Date.now()},Tt=/\?/;S.parseXML=function(e){ var t,n; if(!e||"string"!=typeof e)return null; try{ t=(new C.DOMParser).parseFromString(e,"text/xml") }catch(e){} return n=t&&t.getElementsByTagName("parsererror")[0],t&&!n||S.error("Invalid XML: "+(n?S.map(n.childNodes,function(e){return e.textContent}).join("\n"): e)),t }; var Ct=/\\\[\\\]/,Et=/\r?\n/g,St=/^(?:submit|button|image|reset|file)$/i,kt=/^(?:input|select|textarea|keygen)/i; function At(n,e,r,i){ var t; if(Array.isArray(e))S.each(e,function(e,t){ r||Ct.test(n)?i(n,t):At(n+"["+("object"==typeof t&&null!=t?e:"")+"]",t,r,i) }); else if(r||"object"!==w(e))i(n,e); else for(t in e)At(n+"["+t+"]",e[t],r,i) } S.param=function(e,t){ var n,r=[],i=function(e,t){ var n=m(t)?t():t; r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n) }; if(null==e)return""; if(Array.isArray(e)||e.jquery&&!S.isPlainObject(e))S.each(e,function(){ i(this.name,this.value) }); else for(n in e)At(n,e[n],t,i); return r.join("&") }, S.fn.extend({ serialize:function(){ return S.param(this.serializeArray()) }, serializeArray:function(){ return this.map(function(){ var e=S.prop(this,"elements"); return e?S.makeArray(e):this }).filter(function(){ var e=this.type; return this.name&&!S(this).is(":disabled")&&kt.test(this.nodeName)&&!St.test(e)&&(this.checked||!pe.test(e)) }).map(function(e,t){ var n=S(this).val(); return null==n?null:Array.isArray(n)?S.map(n,function(e){ return{name:t.name,value:e.replace(Et,"\r\n")} }):{name:t.name,value:n.replace(Et,"\r\n")} }).get() }}); var Nt=/%20/g,jt=/#[^.]*$/,Dt=/(\[?&])_=[^&]*$/,qt=/^(.*?:)[ \t]*([^\r\n]*)$/gm,Lt=/^(?:GET|HEAD)$/,Ht=/^\/\//,Ot={},Pt={},Rt="*/".concat("*", "*"),Mt=E.createElement("a"); function Wt(t,i,o,a){ var s={},u=t===Pt; function l(e){ var r; return s[e]=!0,S.each(t[e]||[],function(e,t){ var n=t(i,o,a); return"string"!=typeof n||u||s[n]?u?! (r=n):void 0:(i.dataTypes.unshift(n),l(n),!1) }),r } return l(i.dataTypes[0])||!s["*"]&&l("*") } function Ft(e,t){ var n,r,i=S.ajaxSettings.flatOptions||{}; for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]); return r&&S.extend(!0,e,r),e } Mt.href=bt.href,S.extend({ active:0, lastModified:{}, etag:{}, ajaxSettings:{ url:bt.href, type:"GET", isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(bt.protocol), global:!0, processData:!0, async:!0, contentType:"application/x-www-form-urlencoded; charset=UTF-8", accepts:{ "*":Rt, text:"text/plain", html:"text/html", xml:"application/xml, text/xml", json:"application/json, text/javascript" }, contents:{ xml:/\bxml\b/, html:/\bhtml/, json:/\bjson\b/ }, responseFields:{ xml:"responseXML", text:"responseText", json:"responseJSON" }, converters:{ "* text":String, "text html":!0, "text json":JSON.parse, "text xml":S.parseXML }, flatOptions:{ url:!0, context:!0 } }, ajaxSetup:function(e,t){ return t?Ft(Ft(e,S.ajaxSettings),t):Ft(S.ajaxSettings,e) }, ajaxPrefilter:It(Ot), ajaxTransport:It(Pt), ajax:function(e,t){ "object"==typeof e&&(t=e,e=void 0), t=t||{}; var c,f,p,n,d,r,h,g,i,o,v=S.ajaxSetup({},t), y=v.context||v, m=v.context&&(y.nodeType||y.jquery)?S(y):S.event, x=S.Deferred(), b=S.Callbacks("once memory"), w=v.statusCode||{}, a={},s={},u="canceled",T={readyState:0,getResponseHeader:function(e){ var t; if(h){ if(!n){ n={}; while(t=qt.exec(p)) n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2]) } t=n[e.toLowerCase()+" "] } return null==t?null:t.join(", ") }, getAllResponseHeaders:function(){ return h?p:null }, setRequestHeader:function(e,t){ return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this }, overrideMimeType:function(e){ return null==h&&(v.mimeType=e),this }, statusCode:function(e){ var t; if(e)if(h)T.always(e[T.status]); else for(t in e)w[t]=[w[t],e[t]] return this }, abort:function(e){ var t=e||u; return c&&c.abort(t),l(0,t),this }}; if(x.promise(T),v.url=((e||v.url||bt.href)+"").replace(Ht,bt.protocol+"//"),v.type=t.method||t.type||v.method||v.type, v.data&&v.processData&&"string"!=typeof v.data&&(v.data=S.param(v.data,v.traditional)),Wt(Ot,v,t,T),h)return T; for(i in(g=S.event&&v.global)&&0==S.active++&&S.event.trigger("ajaxStart"),v.type=v.type.toUpperCase(),v.hasContent=!Lt.test(v.type),f=v.url.replace(jt,""),v.hasContent?v.data&&v.processData&&0===(v.conte ``` -------------------------------- ### Initialize and Run CellChat Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_multiomics_data.html This snippet demonstrates the basic initialization and running of CellChat for analyzing cell-cell communication. Ensure you have the necessary libraries installed. ```python import cellchat import scanpy as sc # Load the data cellchat = cellchat.CellChat(object, group.by = "celltype") # Set the database cellchat.data.ann.var['highly_variable'] = True cellchat.useData(data.use = 'raw', symbolic.name = "raw") cellchat.selectCommunicatingCells(source.cells = "celltype", target.cells = "celltype") # Compute the communication probability and infer the communication network cellchat.computeCommunProb(population.size = 30, raw.use = TRUE, population.threshold = 0.001) cellchat.filterCommunication(min.cells = 10, do.filter.by.assumption = TRUE) # Infer the cell-cell communication network cellchat.inference.RNA(object.list = cellchat, max.size = 10, nIter = 400, iter.max = 300, num.threads = 4) cellchat.computeNet(object.list = cellchat, net.weight = TRUE, optional.args = list(comparison = c("Ctrl", "Expt"), …)) ``` -------------------------------- ### CellChat Data Input Example Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_multiomics_data.html Example of input data format for CellChat, typically a count matrix and cell metadata. ```R data.input <- read.csv(file = "count.csv", row.names = 1) ``` ```R meta <- read.csv(file = "meta.csv", row.names = 1) ``` -------------------------------- ### Install CellChat Package Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_transcriptomics_data.html Installs the CellChat R package and its dependencies. Ensure you have a compatible R version and necessary system libraries. ```R if (!requireNamespace("devtools", quietly = TRUE)) install.packages("devtools") devtools::install_github("sqjin/CellChat", ref = "main", build_vignettes = TRUE) ``` -------------------------------- ### CellChat Database Setup Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_transcriptomics_data.html Sets the reference database for CellChat analysis. This step is essential for identifying ligand-receptor interactions. ```r # Set the reference database cellchat <- setReference(cellchat, "path/to/c2c_database.v2.csv") ``` -------------------------------- ### AJAX Request Setup Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_transcriptomics_data.html Configures the default settings for all AJAX requests. This function can be used to set global AJAX options. ```javascript S.ajaxSetup=function(e,t){ return t?Ft(Ft(e,S.ajaxSettings),t):Ft(S.ajaxSettings,e) } ``` -------------------------------- ### Install circlize R Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Install the circlize R package from GitHub if needed for CellChat. Version 0.4.12 or higher is recommended. ```r devtools::install_github("jokergoo/circlize") ``` -------------------------------- ### Install UMAP Python Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Install the UMAP Python package for dimension reduction using pip. Refer to the GitHub repository for troubleshooting. ```python pip install umap-learn ``` -------------------------------- ### Load and Preprocess Data for Comparison Source: https://github.com/jinworks/cellchat/blob/main/tutorial/Comparison_analysis_of_multiple_datasets.html Loads and preprocesses data from multiple sources. Ensure data is in a compatible format before proceeding. ```python import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler, normalize from sklearn.decomposition import PCA from sklearn.cluster import KMeans import matplotlib.pyplot as plt import seaborn as sns # Load data df1 = pd.read_csv('dataset1.csv') df2 = pd.read_csv('dataset2.csv') df3 = pd.read_csv('dataset3.csv') # Combine dataframes df = pd.concat([df1, df2, df3], ignore_index=True) # Preprocessing scaler = StandardScaler() df_scaled = scaler.fit_transform(df.select_dtypes(include=np.number)) # Normalize data df_normalized = normalize(df_scaled) # Handle missing values (example: fill with mean) df.fillna(df.mean(), inplace=True) ``` -------------------------------- ### Set Up CellChat for Analysis Source: https://github.com/jinworks/cellchat/blob/main/tutorial/CellChat_analysis_of_spatial_multiomics_data.html Set up the CellChat object with necessary information, including cell type labels and the pathway database. This step is crucial before proceeding with inference. ```R cellchat <- addMeta(cellchat, meta = seu.object@meta.data$cell_type, meta.name = "cell_type") cellchat <- setVariableIdentity(cellchat, identity.name = "cell_type") # Set the ligand-receptor interaction database for CellChat analysis # Use 'pathway.mouse' or 'pathway.human' depending on your data # For example, using the human database: cellchat@DB <- CellChatDB.human ``` -------------------------------- ### Initialize Highlight.js for Code Highlighting (JavaScript) Source: https://github.com/jinworks/cellchat/blob/main/tutorial/Comparison_analysis_of_multiple_datasets.html This script configures and initializes the Highlight.js library for syntax highlighting on the page. It ensures that code blocks are correctly identified and styled, with a fallback for when the page is fully loaded. ```javascript if (window.hljs) { hljs.configure({languages: []}); hljs.initHighlightingOnLoad(); if (document.readyState && document.readyState === "complete") { window.setTimeout(function() { hljs.initHighlighting(); }, 0); } } ``` -------------------------------- ### Install NMF R Package Source: https://github.com/jinworks/cellchat/blob/main/README.md Install the NMF R package using install.packages. Version 0.23.0 or higher is recommended. Check provided links for troubleshooting. ```r install.packages('NMF') ``` -------------------------------- ### Load and preprocess a second single-cell dataset Source: https://github.com/jinworks/cellchat/blob/main/tutorial/Comparison_analysis_of_multiple_datasets_with_different_cellular_compositions.html Loads and preprocesses a second single-cell dataset, similar to the first. Ensure the file path is correct. ```python adata2 = sc.read_h5ad("data/Human_kidney_single_cell_data.h5ad") adata2.var_names_make_unique() sc.pp.filter_cells(adata2, min_genes=200) sc.pp.filter_genes(adata2, min_cells=3) sc.pp.normalize_total(adata2, target_sum=1e4) sc.pp.log1p(adata2) sc.pp.highly_variable_genes(adata2, n_top_genes=2000, subset=True) sc.tl.pca(adata2, svd_solver='arpack') ``` -------------------------------- ### Getting Element Offset Source: https://github.com/jinworks/cellchat/blob/main/tutorial/Comparison_analysis_of_multiple_datasets.html Extends jQuery to get the offset (position) of the first element in the set of matched elements relative to the document. If an offset is provided, it sets the position. ```javascript S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0}}) ```