diff --git "a/data/dataset_Substrate.csv" "b/data/dataset_Substrate.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Substrate.csv" @@ -0,0 +1,30875 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Substrate","evocellnet/ksea","R/ksea.R",".R","5151","141","# Required to calculate the p-values in the GSEA. +# The p-values are calculated by suffling the signatures +computeSimpleEMPES <- function(ranking,exp_value_profile,signature,trials){ + ngenes <- length(ranking) + siglen <- length(intersect(signature,ranking)) + ES <- rep(NA,trials) + for (i in 1:trials){ + shuffled_signature <- ranking[sample(1:ngenes,siglen)] + tmp <- ksea(ranking,exp_value_profile,shuffled_signature,display=FALSE,significance=FALSE) + ES[i] <- tmp + } + return(ES) +} + + +##' Enrichment of differentially regulated sites in a signature of kinase known targets +##' +##' The Kinase Set Enrichment Analysis is a established analysis statistical method to look +##' for an enrichment on differentially regulated genes/proteins belonging to a given category +##' in a ranked list usually based on gene expression. +##' +##' @title Kinase Set Enrichment Analysis +##' @param ranking Vector of strings containing the ranking of all ids ordered based on +##' their quantifications. +##' @param norm_express Numeric vector with quantifications. +##' @param signature Vector of strings containing all ids in the signature. +##' @param p Numeric value indicating the power at which the weights are scaled. +##' @param display Logical. When TRUE prints the plot of the enrichment.Set to FALSE +##' when running in batch. +##' @param returnRS Logical. If TRUE a list with all the result attributes is returned. +##' If FALSE only a subset is printed based on the value of \code{significance}. +##' @param significance Logical. When \code{returnRS} is FALSE, if TRUE prints a list with the +##' ES and p-value. If FALSE only the Enrichment Score is printed. +##' @param trial Integer with number of iterations to calculate significance. +##' @return Enrichment result. The output varies depends on the values of \code{returnRS} +##' and \code{significance}. +##' @author David Ochoa (code adapted from Francesco Ioirio's version of the same function). +##' @import graphics +##' @export +ksea <- function(ranking, norm_express, signature, p=1, display=TRUE, + returnRS=FALSE, significance=FALSE, trial=1000){ + + + #intersection between signature and ranked list + signature <- unique(intersect(signature,ranking)) + ## Checks if there's some overlap between the ranking and the signature + if(length(signature) == 0){ + return(NA) + } + + #Numeric 1/0 of the hits on the ranked list + HITS <- as.numeric(is.element(ranking,signature)) + #Multiplication of hits and norm_express + R <- norm_express * HITS + #Accumulation of absolute norm_express-hit numbers at the power of p + hitCases <- cumsum(abs(R) ^ p) + #Maximum value, would be the same as sum(abs(R)^p) + NR <- max(hitCases) + #This might happen if the HITS are in 0 + if(NR == 0) return(NA) + #Vector with the accumulation of missed cases + missCases <- cumsum(1 - HITS) + #Total elements iin the ranking + N <- length(ranking) + #Total in the ranking that are not in the signature + N_Nh <- length(ranking) - length(signature) + #Accumulation of absolute norm_exprss-hit divided by their maximum value + Phit <- hitCases / NR + #Accumulation of the missed cases divided by their maximum possible value + Pmiss <- missCases / N_Nh + + #Maximum difference between hit and miss + m <- max(abs(Phit - Pmiss)) + #index where the maximum is produced + t <- which(abs(Phit - Pmiss) == m) + #In case there is more than one position with maximum values it takes the first one + if (length(t) > 1){ + t <- t[1] + } + ES <- Phit[t] - Pmiss[t] #ES-score + RS <- Phit - Pmiss #vector of RS-scores + if (display){ + if (ES >= 0){ + c <- ""red"" + }else{ + c <- ""green"" + } + + lyt = matrix(c(1,2), + ncol=1, nrow=2,byrow=TRUE) + nf <- layout(mat=lyt, widths=c(1),heights=c(1,5)) + + par(mar=c(0,4,1,1)) #margins + plot(NA, ylim=c(0,1), xlim=c(0,length(HITS)),axes=FALSE,ylab="""",xlab="""",xaxs=""i"") + abline(v=which(HITS == 1), col=""darkgrey"") + # image(matrix(HITS, ncol=1), axes=FALSE, col=c(""#FFFFFFFF"", ""#B2182B"")) + box(lty = ""solid"", col = 'black') + + par(mar=c(4,4,0,1), #margins + las=1) + + plot(0:N, + c(0,Phit - Pmiss), + col=c, + type=""l"", + xlim=c(0,N), + ylim=c(-(abs(ES) + 0.5 * (abs(ES))),abs(ES) + 0.5 * (abs(ES))), + xaxs=""i"", + ## bty=""l"", + axes=TRUE, + xlab=""Site Rank Position"", + ylab=""Running Sum"") + abline(h=0, lty=1, col=""darkgrey"") + axis(side=2) + } + + P <- NA + + if(significance){ + EMPES <- computeSimpleEMPES(ranking,norm_express,signature,trial) #Calculate ES trial number of times by sampling + P <- (ES >= 0) * (length(which(EMPES >= ES)) / trial) + (ES < 0) * (length(which(EMPES <= ES)) / trial) + } + + if (returnRS){ + POSITIONS <- which(HITS == 1) + names(POSITIONS) <- ranking[which(HITS == 1)] + POSITIONS <- POSITIONS[order(names(POSITIONS))] + names(POSITIONS) <- names(POSITIONS)[order(names(POSITIONS))] + result <- list(ES=ES,RS=RS,POSITIONS=POSITIONS,PEAK=t) + return(result) + }else{ + if (significance){ + result <- list(ES=ES,p.value=P) + return(result) + } + else{ + return(ES) + } + } +} +","R" +"Substrate","evocellnet/ksea","R/ksea_batchKinases.R",".R","1226","30","##' Runs KSEA in batch for all Kinase-Substrates +##' +##' This functions allows to run the KSEA in a given dataset for all provided kinases. +##' The function makes use of all available cores in the computer (using \code{parallel}) +##' package. +##' @title Batch KSEA for all kinase regulons +##' @param ranking vector with all quantified positions +##' @param logvalues vector with all quantifications +##' @param regulons list containing vectors with substrates of each kinase. Substrates +##' should be encoded with the same id as the \code{ranking} vector. +##' @param trial Number of permutations used for the empirical p-value generation. +##' @return A vector of p-values containing all KSEA p-values for all +##' @author David Ochoa +##' @import parallel +##' @export +ksea_batchKinases <- function(ranking, logvalues, regulons, trial=1000){ + tests <- mclapply(regulons, function(x) + ksea(ranking, logvalues, x, + display=FALSE, + returnRS=FALSE, + significance=TRUE, + trial=trial), mc.preschedule = FALSE) + if(is.matrix(tests)){ + pvals <- unlist(tests[""p.value"", ]) + }else{ + pvals <- sapply(tests, function(x) if(is.list(x)){return(x$p.value)}else{return(x)}) + } + return(pvals) +} +","R" +"Substrate","sfc-aqua/gosc-graph-state-generation","usage_example.py",".py","2059","66","from timeit import default_timer as timer + +import networkx as nx + +from src.graph_state_generation.optimizers import ( + approximate_static_stabilizer_reduction, + fast_maximal_independent_set_stabilizer_reduction, + greedy_stabilizer_measurement_scheduler, + random_mapper, +) +from src.graph_state_generation.substrate_scheduler import TwoRowSubstrateScheduler + + +def gen_erdos_renyi_graph_single_component(n, m): + G = nx.gnm_random_graph(n, m) + if nx.number_connected_components(G) == 1: + return G + else: + return gen_erdos_renyi_graph_single_component(n, m) + + +# g = gen_erdos_renyi_graph_single_component(500, 2500) +# g = gen_erdos_renyi_graph_single_component(10, 9) +g = nx.cycle_graph(10) +nothing_compiler = TwoRowSubstrateScheduler(g) + +st = timer() +nx.algorithms.approximation.maximum_independent_set(g) +ed = timer() +print(f""time taken - {ed - st}s"") + +nothing_compiler.run() +nothing_compiler.get_summary() +nothing_compiler.visualization() +print(""========================================"") + +scheduler_only_compiler = TwoRowSubstrateScheduler( + g, stabilizer_scheduler=greedy_stabilizer_measurement_scheduler +) +scheduler_only_compiler.run() +scheduler_only_compiler.get_summary() +scheduler_only_compiler.visualization() +print(""========================================"") + +for _ in range(2): + better_compiler = TwoRowSubstrateScheduler( + g, + pre_mapping_optimizer=approximate_static_stabilizer_reduction, + node_to_patch_mapper=random_mapper, + stabilizer_scheduler=greedy_stabilizer_measurement_scheduler, + ) + better_compiler.run() + better_compiler.get_summary() + +print(""========================================"") +for _ in range(2): + faster_compiler = TwoRowSubstrateScheduler( + g, + pre_mapping_optimizer=fast_maximal_independent_set_stabilizer_reduction, + node_to_patch_mapper=random_mapper, + stabilizer_scheduler=greedy_stabilizer_measurement_scheduler, + ) + faster_compiler.run() + faster_compiler.get_summary() + faster_compiler.visualization() +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/__init__.py",".py","0","0","","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/substrate_scheduler/substrate_scheduler_two_row.py",".py","5825","149","#! /bin/usr/env python3 +from timeit import default_timer as timer +from typing import List, Set, Tuple + +import networkx as nx + +from ..utility import Basis +from ..visualization_tools import ascii_instruction_visualization + + +def default_pre_mapping_optimizer(g: nx.Graph) -> Tuple[Set[int], nx.Graph]: + return (set(), g) + + +def default_node_to_patch_mapper(g: nx.Graph, _: Set[int]) -> List[int]: + return [x for x in range(g.number_of_nodes())] + + +def default_stabilizer_scheduler( + stabilizer_to_measure: List[Tuple[int, Tuple[int, int]]] +) -> List[List[Tuple[int, Tuple[int, int]]]]: + + return list(map(lambda x: [(x[0], x[1])], stabilizer_to_measure)) + + +class TwoRowSubstrateScheduler: + """"""The very basic substrate scheduler where all qubits are represented by 2-tile patches + align in a single row and another row is for ancilla to perform multi-Pauli product + measurement for stabilizer generator projection. + + It works in three phases by accepting 3 functions + 1. pre-mapping optimization + 2. node-to-patch mapping + 3. stabilizer measurement scheduling + + If the optimizer functions are not provided, no optimization is done and only one stabilizer + measurement is performed at each time step resulting in O(V) time step + """""" + + def __init__( + self, + input_graph: nx.Graph, + # nx.Graph -> Tuple(Set(stabilizer_to_skip), nx.Graph) + pre_mapping_optimizer=default_pre_mapping_optimizer, + # nx.Graph -> List(int) of length V + node_to_patch_mapper=default_node_to_patch_mapper, + # [(S_i, (min_i, max_i))] -> [[(S_i, (min_i, max_i))], [(S_j, (min_j, max_j))]] with length + # equals to number of timestep where S_i, min_i, and max_i are int + stabilizer_scheduler=default_stabilizer_scheduler, + verbose=False, + ): + """"""pre_mapping_optimizer -"""""" + + + if input_graph == nx.Graph(): + raise ValueError(""Graph is empty. Cannot schedule empty graph."") + + self.input_graph: nx.Graph = input_graph + self.label: List[int] = [] + self.adj_list: List[List[int]] = [] + self.stabilizer: List[ + Tuple[int, List[int]] + ] = [] # Tuple[Pauli_X, List[Pauli_Z]] where it corresponds to the patch label + + self.stabilizer_to_measure: List[ + Tuple[int, Tuple[int, int]] + ] = [] # (G_i, (ancilla_left, ancilla_right)) where G_i denote stabilizer of patch i + self.pre_mapping_optimizer = pre_mapping_optimizer + self.node_to_patch_mapper = node_to_patch_mapper + self.stabilizer_scheduler = stabilizer_scheduler + self.verbose = verbose + + # parse the input graph and set class attributes + self.adj_list = [vs for _, vs in nx.to_dict_of_lists(input_graph).items()] + self.stabilizer_to_measure = [] + + # for reporting instructions and time-space volume analysis + self.patch_state_init: List[Basis] = [Basis.Z] * input_graph.number_of_nodes() + self.measurement_steps: List[List[Tuple[int, Tuple[int, int]]]] = [] + + def visualization(self, fmt=""ascii"", save=False): + if fmt == ""ascii"": + visualizer = ascii_instruction_visualization + else: + raise ValueError(""unknown format"") + + visualizer(self.label, self.patch_state_init, self.measurement_steps) + + def stabilizer_table(self): + """"""print stabilizer of the input graph state in ascii format + (I is replaced with _ for better readability). + Only support up to 100 vertices."""""" + n = self.input_graph.number_of_nodes() + stabilizers_str: List[str] = [""""] * n + + def _adj_to_stabilizer(i: int, vs: List[int]) -> str: + barr = bytearray(b""_"") * n + barr[i] = 65 + 23 # 'X' + for v in vs: + barr[v] = 65 + 25 # 'Z' + return barr.decode() + + for i in range(n): + stabilizers_str[i] = _adj_to_stabilizer(i, self.adj_list[i]) + + print(""\n"".join(stabilizers_str)) + + def run(self): + """"""Execute the three phases on creating the input graph state into + Litinski's GoSC ruleset instructions. + This function will also output the running time of each phase."""""" + + # graph optimization + pre_opt_start_time = timer() + stabilizer_to_skip, transformmed_graph = self.pre_mapping_optimizer(self.input_graph) + pre_opt_end_time = timer() + if self.verbose: + print(f""pre-mapping optimization took - {pre_opt_end_time - pre_opt_start_time}s"") + + # node to patch mapping / labelling + labelling_start_time = timer() + self.label = self.node_to_patch_mapper(transformmed_graph, set()) + labelling_end_time = timer() + if self.verbose: + print(f""node to patch mapping took - {labelling_end_time - labelling_start_time}s"") + + scheduling_start_time = timer() + # from here on we work on patch labelling and not labelling of the input graph + for i, vs in enumerate(self.adj_list): + mi = self.label[i] + mvs = [self.label[v] for v in vs] + + if i in stabilizer_to_skip: + self.patch_state_init[mi] = Basis.X + continue + + self.stabilizer_to_measure.append((mi, (min(mi, min(mvs)), (max(mi, max(mvs)))))) + self.measurement_steps = self.stabilizer_scheduler(self.stabilizer_to_measure) + scheduling_end_time = timer() + if self.verbose: + print(f""measurement scheduler took - {scheduling_end_time - scheduling_start_time}s"") + + def get_summary(self): + print(f""reduce from {self.input_graph.number_of_nodes()} to {len(self.measurement_steps)}"") + + def get_instructions(self): + # TODO: add labeling phase + return self.measurement_steps +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/substrate_scheduler/__init__.py",".py","66","2","from .substrate_scheduler_two_row import TwoRowSubstrateScheduler +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/utility/__init__.py",".py","28","2","from .constant import Basis +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/utility/constant.py",".py","63","7","from enum import Enum + + +class Basis(Enum): + X = 1 + Z = 2 +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/visualization_tools/ascii_visualizer.py",".py","1327","42","from typing import List, Tuple + +from ..utility.constant import Basis + + +def ascii_instruction_visualization( + node_to_patch_mapping: List[int], + patch_initialized_state: List[Basis], + measurement_steps: List[List[Tuple[int, Tuple[int, int]]]], +): + n = len(node_to_patch_mapping) + if n > 1000: + raise NotImplementedError( + f""Your graph has {n} nodees. However, we cannot visulize more "" + ""than 1000 nodes at the moment."" + ) + inverse_map = [0] * n + for i in node_to_patch_mapping: + inverse_map[node_to_patch_mapping[i]] = i + + inverse_map_str = [f""{i:03}"" for i in inverse_map] + + # printing + label_line = ""| "" + "" | "".join(inverse_map_str) + "" |"" + patch_state_line = ""| "" + "" | "".join([f"" {i.name} "" for i in patch_initialized_state]) + "" |"" + label_border = ""|_"" + ""_|_"".join([""___"" for _ in inverse_map_str]) + ""_|"" + + print(label_line) + print(patch_state_line) + print(label_border) + for step in measurement_steps: + curend = 0 + line = """" + for (_, (left, right)) in step: + if left > curend: + line = line + ("" "") * (left - curend) + line += "" |----"" + line += ""------"" * (right - left - 1) + line += ""-----|"" + curend = right + 1 + print(line) +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/visualization_tools/__init__.py",".py","62","2","from .ascii_visualizer import ascii_instruction_visualization +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/optimizers/pre_mapping_optimizer.py",".py","984","30","from typing import Set, Tuple + +import networkx as nx +import numpy as np + + +def approximate_static_stabilizer_reduction(g: nx.Graph) -> Tuple[Set[int], nx.Graph]: + """"""Uses maximum independent set algorithm to find state initialization such that + most stabilizer generators are already stabilized so the stabilizer measurements + needed are reduced."""""" + max_i_set = nx.algorithms.approximation.maximum_independent_set(g) + return (max_i_set, g) + + +def fast_maximal_independent_set_stabilizer_reduction( + g: nx.Graph, +) -> Tuple[Set[int], nx.Graph]: + """"""Repeatly run maximal independent set on a random vertex to find + largest maximal independent set."""""" + i_set = nx.maximal_independent_set(g) + max_retry = np.log2(g.number_of_nodes()) + retry = max_retry + while retry > 0: + ni_set = nx.maximal_independent_set(g) + retry -= 1 + if len(ni_set) > len(i_set): + retry = max_retry + i_set = ni_set + return (i_set, g) +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/optimizers/__init__.py",".py","273","7","from .node_to_patch_mapper import random_mapper +from .pre_mapping_optimizer import ( + approximate_static_stabilizer_reduction, + fast_maximal_independent_set_stabilizer_reduction, +) +from .stabilizer_measurement_scheduler import greedy_stabilizer_measurement_scheduler +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/optimizers/node_to_patch_mapper.py",".py","413","14","from typing import List, Set + +import networkx as nx +import numpy as np + + +def random_mapper(g: nx.Graph, _: Set[int]) -> List[int]: + """"""This mapper randomly permutes the label and ignore the skipped_stabilizer set."""""" + return list(np.random.permutation(g.number_of_nodes())) + + +# def min_cut_mapper(g: nx.Graph, skipped_stabilizer: Set[int]) -> List[int]: +# return [x for x in range(g.number_of_nodes())] +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/optimizers/stabilizer_measurement_scheduler.py",".py","841","23","from collections import deque +from typing import List, Tuple + + +def greedy_stabilizer_measurement_scheduler( + stabilizer_to_measure: List[Tuple[int, Tuple[int, int]]] +) -> List[List[Tuple[int, Tuple[int, int]]]]: + """"""Optimal stabilizer measurement scheduler given that labelling is fixed. Proof to be written."""""" + + # stabilizer_to_measure is [(S_i, (min_i, max_i))] + stabilizer_to_measure = stabilizer_to_measure + stabilizer_to_measure.sort(key=lambda x: x[1][1]) + time_step = deque() # stores list of (S_i, (min_i, max_i)) + time_step.append([stabilizer_to_measure[0]]) + for st in stabilizer_to_measure[1:]: + if st[1][0] > time_step[0][-1][1][1]: + time_step[0].append(st) + time_step.append(time_step.popleft()) + else: + time_step.append([st]) + + return list(time_step) +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","src/graph_state_generation/old_code/visualize_result.py",".py","2953","77","import math +import numbers +import random + +import matplotlib.pyplot as plt +from matplotlib.patches import Rectangle +from tests.graph_state_generation.create_random_graph import ( + gen_erdos_renyi_graph_single_component, +) + +from old_version import two_tile_patch_ver as twotile + +n_nodes_ran = random.randint(3, 5) + +row=3 +col=2*n_nodes_ran +# generate sparse graph +n_edges_ran = random.randint(n_nodes_ran, math.floor((n_nodes_ran * (n_nodes_ran - 1))/ 2 / 2)) + +adj_list_gen = gen_erdos_renyi_graph_single_component(n_nodes_ran, n_edges_ran) #generate random graph for testing + +if adj_list_gen != None: + # run compilation + num_step_scheduled, num_stablizers, adj_list_gen, stablizer_on_qubits, board_step = twotile.main(adj_list_gen, n_nodes_ran) + print(num_step_scheduled) + print(num_stablizers) + +def saveImage(p,step): + filename = '../code_visualization/' + str(step) + '.png' + p.savefig(filename) + +for step in range(0,num_step_scheduled): + plt.figure(figsize=(10, 5)) + + ax = plt.gca() + ax.set_xlim([0, col]) + ax.set_ylim([0, row]) + + step_of_board = board_step[step] + operation_step = stablizer_on_qubits[step] + for i in range(0, row): + row_board=step_of_board[i] + for j in range(0, col): + if isinstance(row_board[j],numbers.Number): + # for qubits + qubit_id=row_board[j] + if qubit_id in operation_step.keys(): + operation=operation_step[qubit_id] + if operation==['Z']: + rec = Rectangle((j, row - i - 1), width=1, height=1, facecolor='r', edgecolor=""gray"") + if operation==['X']: + rec = Rectangle((j, row - i - 1), width=1, height=1, facecolor='y', edgecolor=""gray"") + plt.text(j + 0.5, row - i - 1 + 0.5, (row_board[j],operation),fontweight='bold', fontsize=7.5, verticalalignment=""center"", + horizontalalignment=""center"") + else: + rec = Rectangle((j, row - i - 1), width=1, height=1, facecolor='b', edgecolor=""gray"") + plt.text(j + 0.5, row - i-1 + 0.5, row_board[j], fontsize=7.5, verticalalignment=""center"", horizontalalignment=""center"") + ax.add_patch(rec) + + if row_board[j] == None: + # for unassigned tiles + rec = Rectangle((j, row - i-1), width=1, height=1, facecolor='w', edgecolor=""gray"") + #print(rec) + ax.add_patch(rec) + if row_board[j] == 'anc': + # for ancilla patch + rec = Rectangle((j, row -i-1), width=1, height=1, facecolor='gray', edgecolor=""gray"") + #print(rec) + ax.add_patch(rec) + + plt.title(""step %s / %s"" % (step, num_step_scheduled), fontsize='15', fontweight='bold', y=-0.03) + + plt.axis('equal') + plt.axis('off') + plt.tight_layout() + saveImage(plt,step) +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","data/__init__.py",".py","63","2","from .gen_graphs import gen_erdos_renyi_graph_single_component +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","data/gen_graphs.py",".py","2270","66","import json +import random +import os + +import math + +import networkx as nx + + +def gen_erdos_renyi_graph_single_component(n, m): + if_connected = 0 + for i in range(1000): + G = nx.gnm_random_graph(n, m, seed=51) + if_connected = nx.number_connected_components(G) + if if_connected == 1: + break + if if_connected == 1: + return nx.to_dict_of_lists(G) + else: + return None + + +for i in range(5): + for n_nodes_ran in range(10, 1000, 50): + # minimum number of edges for undirected connected graph is (n-1) edges + # maximal number of edges for undirected connected graph is n(n-1)/2 edges + edge_numbers = n_nodes_ran * (n_nodes_ran - 1) / 2 - n_nodes_ran + + random.seed(10) + + n_edges_very_sparse = random.randint( + n_nodes_ran, math.floor(n_nodes_ran + edge_numbers / 4) + ) + + n_edges_sparse = random.randint( + math.floor(n_nodes_ran + edge_numbers / 4), + math.floor(n_nodes_ran + edge_numbers / 2), + ) + n_edges_dense = random.randint( + math.floor(n_nodes_ran + edge_numbers / 2), + math.floor(n_nodes_ran + edge_numbers * 3 / 4), + ) + n_edges_very_dense = random.randint( + math.floor(n_nodes_ran + edge_numbers * 3 / 4), + math.floor(n_nodes_ran + edge_numbers), + ) + + very_sparse = gen_erdos_renyi_graph_single_component( + n_nodes_ran, n_edges_very_sparse + ) + sparse = gen_erdos_renyi_graph_single_component(n_nodes_ran, n_edges_sparse) + dense = gen_erdos_renyi_graph_single_component(n_nodes_ran, n_edges_dense) + very_dense = gen_erdos_renyi_graph_single_component( + n_nodes_ran, n_edges_very_dense + ) + if not os.path.exists(""graph""): + os.makedirs(""graph"") + with open(f""graph/very_sparse_{i}.json"", ""w"") as json_file: + json.dump(very_sparse, json_file) + with open(f""graph/dense_{i}.json"", ""w"") as json_file: + json.dump(sparse, json_file) + with open(f""graph/dense_{i}.json"", ""w"") as json_file: + json.dump(dense, json_file) + with open(f""graph/very_dense_{i}.json"", ""w"") as json_file: + json.dump(very_dense, json_file) +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","tests/test_pre_mapping_optimizer.py",".py","721","29","import networkx as nx + +from graph_state_generation.optimizers.pre_mapping_optimizer import ( + fast_maximal_independent_set_stabilizer_reduction, +) + + +def test_max_independet_set_reduction_0(): + graph_0 = {0: [2, 5], 1: [3], 2: [0, 3], 3: [1, 2, 4], 4: [3], 5: [0]} + G_0 = nx.Graph(graph_0) + assert sorted(fast_maximal_independent_set_stabilizer_reduction(G_0)[0]) == [ + 1, + 2, + 4, + 5, + ] + + +def test_max_independet_set_reduction_1(): + graph_1 = {0: [1, 2, 3, 4, 5], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0]} + G_1 = nx.Graph(graph_1) + assert sorted(fast_maximal_independent_set_stabilizer_reduction(G_1)[0]) == [ + 1, + 2, + 3, + 4, + 5, + ] +","Python" +"Substrate","sfc-aqua/gosc-graph-state-generation","tests/test_stabilizer_measurement_scheduler.py",".py","484","14","from graph_state_generation.optimizers.stabilizer_measurement_scheduler import ( + greedy_stabilizer_measurement_scheduler, +) + + +def test_greedy_scheduler_0(): + stabilizers_set_0 = [(0, (0, 5)), (1, (1, 2)), (2, (1, 10))] + assert len(greedy_stabilizer_measurement_scheduler(stabilizers_set_0)) == 3 + + +def test_greedy_scheduler_1(): + stabilizers_set_1 = [(0, (0, 5)), (1, (1, 2)), (2, (6, 10))] + assert len(greedy_stabilizer_measurement_scheduler(stabilizers_set_1)) == 2 +","Python" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/RandomP.m",".m","733","16","P1_FilmRef = zeros( Nx, Ny, Nz ); P2_FilmRef = P1_FilmRef; P3_FilmRef = P1_FilmRef; + +init_perturb = rand(Nx, Ny, Nz) > 0.5; % where to perturb +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; % how much to perturb +P1_FilmRef(init_perturb) = perturb_amt(init_perturb); +P1_FilmRef(~init_perturb) = -perturb_amt(~init_perturb); + +init_perturb = rand(Nx, Ny, Nz) > 0.5; +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; +P2_FilmRef(init_perturb) = perturb_amt(init_perturb); +P2_FilmRef(~init_perturb) = -perturb_amt(~init_perturb); + +init_perturb = rand(Nx, Ny, Nz) > 0.5; +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; +P3_FilmRef(init_perturb) = perturb_amt(init_perturb); +P3_FilmRef(~init_perturb) = -perturb_amt(~init_perturb);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/ThermalNoise.m",".m","493","10","% Thermal Noise +Thermal_Noise_Sigma = sqrt(2 * ThermConst); + +Thermal_Noise_1 = normrnd(0,Thermal_Noise_Sigma,Nx,Ny,Nz); +Thermal_Noise_2 = normrnd(0,Thermal_Noise_Sigma,Nx,Ny,Nz); +Thermal_Noise_3 = normrnd(0,Thermal_Noise_Sigma,Nx,Ny,Nz); + +Thermal_Noise_1_2Dk = fft_2d_slices(Thermal_Noise_1) .* in_film .* Nucleation_Sites; +Thermal_Noise_2_2Dk = fft_2d_slices(Thermal_Noise_2) .* in_film .* Nucleation_Sites; +Thermal_Noise_3_2Dk = fft_2d_slices(Thermal_Noise_3) .* in_film .* Nucleation_Sites;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/AxesSetup.m",".m","1308","37","%% Set up real space axis +x_axis = linspace(0, Lx, Nx)'; y_axis = linspace(0, Ly, Ny)'; z_axis = linspace(0, Lz, Nz)'; + +%% VERY IMPORTANT STEP!! Let us redefine zero, otherwise the exp() term will make our matrix solving go to shit... +z_axis = z_axis - z_axis((round(Nz/2))); + +dx = x_axis(2) - x_axis(1); dy = y_axis(2) - y_axis(1); dz = z_axis(2) - z_axis(1); +[y_grid, x_grid, z_grid] = meshgrid(x_axis, y_axis, z_axis); +% kx_grid(y,x,z) + +%% Fourier space vectors -> Gradient energy terms and things that use air + film + sub +kx = 2*pi/Lx*[0:Nx/2 -Nx/2+1:-1]'; +ky = 2*pi/Ly*[0:Ny/2 -Ny/2+1:-1]'; +kz = 2*pi/Lz*[0:Nz/2 -Nz/2+1:-1]'; +[ky_grid_3D,kx_grid_3D,kz_grid_3D] = meshgrid(kx,ky,kz); +[ky_grid_2D, kx_grid_2D] = meshgrid(kx, ky); + +k_mag_3D = sqrt(kx_grid_3D.^2 + ky_grid_3D.^2 + kz_grid_3D.^2); +ex_3D = kx_grid_3D ./ k_mag_3D; +ey_3D = ky_grid_3D ./ k_mag_3D; +ez_3D = kz_grid_3D ./ k_mag_3D; + +%% +if( sub_index > 0 ) + in_film = (z_grid > z_axis(sub_index)) & (z_grid <= z_axis(film_index)); + not_in_film = ~in_film; + not_in_film = +not_in_film; + in_film = +in_film; +else + in_film = 1; + not_in_film = 0; +end + +%% z axis +h_film = z_axis(film_index); % end of film +h_sub = z_axis(1); % where substrate ends...limit of elastic deformation allowed in substrate +h_int = z_axis(interface_index);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/colorGradient.m",".m","2484","87","function [grad,im]=colorGradient(c1,c2,depth) +% COLORGRADIENT allows you to generate a gradient between 2 given colors, +% that can be used as colormap in your figures. +% +% USAGE: +% +% [grad,im]=getGradient(c1,c2,depth) +% +% INPUT: +% - c1: color vector given as Intensity or RGB color. Initial value. +% - c2: same as c1. This is the final value of the gradient. +% - depth: number of colors or elements of the gradient. +% +% OUTPUT: +% - grad: a matrix of depth*3 elements containing colormap (or gradient). +% - im: a depth*20*3 RGB image that can be used to display the result. +% +% EXAMPLES: +% grad=colorGradient([1 0 0],[0.5 0.8 1],128); +% surf(peaks) +% colormap(grad); +% +% -------------------- +% [grad,im]=colorGradient([1 0 0],[0.5 0.8 1],128); +% image(im); %display an image with the color gradient. + +% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal +% v:1.0 22 May 2011. Initial release. + +%Check input arguments. +%input arguments must be 2 or 3. +error(nargchk(2, 3, nargin)); + +%If c1 or c2 is not a valid RGB vector return an error. +if numel(c1)~=3 + error('color c1 is not a valir RGB vector'); +end +if numel(c2)~=3 + error('color c2 is not a valir RGB vector'); +end + +if max(c1)>1&&max(c1)<=255 + %warn if RGB values are given instead of Intensity values. Convert and + %keep procesing. + warning('color c1 is not given as intensity values. Trying to convert'); + c1=c1./255; +elseif max(c1)>255||min(c1)<0 + error('C1 RGB values are not valid.') +end + +if max(c2)>1&&max(c2)<=255 + %warn if RGB values are given instead of Intensity values. Convert and + %keep procesing. + warning('color c2 is not given as intensity values. Trying to convert'); + c2=c2./255; +elseif max(c2)>255||min(c2)<0 + error('C2 RGB values are not valid.') +end +%default depth is 64 colors. Just in case we did not define that argument. +if nargin < 3 + depth=64; +end + +%determine increment step for each color channel. +dr=(c2(1)-c1(1))/(depth-1); +dg=(c2(2)-c1(2))/(depth-1); +db=(c2(3)-c1(3))/(depth-1); + +%initialize gradient matrix. +grad=zeros(depth,3); +%initialize matrix for each color. Needed for the image. Size 20*depth. +r=zeros(20,depth); +g=zeros(20,depth); +b=zeros(20,depth); +%for each color step, increase/reduce the value of Intensity data. +for j=1:depth + grad(j,1)=c1(1)+dr*(j-1); + grad(j,2)=c1(2)+dg*(j-1); + grad(j,3)=c1(3)+db*(j-1); + r(:,j)=grad(j,1); + g(:,j)=grad(j,2); + b(:,j)=grad(j,3); +end + +%merge R G B matrix and obtain our image. +im=cat(3,r,g,b); +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/CalcElasticEnergy.m",".m","3166","22","if( ELASTIC ) + CalculateStrain; + + f1_elastic = (- 2.*C11.*Q11 - 4.*C12.*Q12).*TotalStrain_FilmRef_11.*P1_FilmRef + (- 2.*C11.*Q12 - 2.*C12.*Q11 - 2.*C12.*Q12).*TotalStrain_FilmRef_22.*P1_FilmRef + (- 2.*C11.*Q12 - 2.*C12.*Q11 - 2.*C12.*Q12).*TotalStrain_FilmRef_33.*P1_FilmRef + (-4.*C44.*Q44).*TotalStrain_FilmRef_12.*P2_FilmRef + (-4.*C44.*Q44).*TotalStrain_FilmRef_13.*P3_FilmRef + (2.*C11.*Q11.^2 + 4.*C11.*Q12.^2 + 4.*C12.*Q12.^2 + 8.*C12.*Q11.*Q12).*P1_FilmRef.^3 + (2.*C11.*Q12.^2 + 2.*C12.*Q11.^2 + 6.*C12.*Q12.^2 + 4.*C44.*Q44.^2 + 4.*C11.*Q11.*Q12 + 4.*C12.*Q11.*Q12).*P1_FilmRef.*P2_FilmRef.^2 + (2.*C11.*Q12.^2 + 2.*C12.*Q11.^2 + 6.*C12.*Q12.^2 + 4.*C44.*Q44.^2 + 4.*C11.*Q11.*Q12 + 4.*C12.*Q11.*Q12).*P1_FilmRef.*P3_FilmRef.^2; + f2_elastic = (- 2.*C11.*Q12 - 2.*C12.*Q11 - 2.*C12.*Q12).*TotalStrain_FilmRef_11.*P2_FilmRef + (- C11.*Q11 - C11.*Q12 - C12.*Q11 - 3.*C12.*Q12 - 2.*C44.*Q44).*TotalStrain_FilmRef_22.*P2_FilmRef + (2.*C44.*Q44 - C11.*Q12 - C12.*Q11 - 3.*C12.*Q12 - C11.*Q11).*TotalStrain_FilmRef_33.*P2_FilmRef + (-4.*C44.*Q44).*TotalStrain_FilmRef_12.*P1_FilmRef + (2.*C11.*Q12 - 2.*C11.*Q11 + 2.*C12.*Q11 - 2.*C12.*Q12).*TotalStrain_FilmRef_23.*P3_FilmRef + (2.*C11.*Q12.^2 + 2.*C12.*Q11.^2 + 6.*C12.*Q12.^2 + 4.*C44.*Q44.^2 + 4.*C11.*Q11.*Q12 + 4.*C12.*Q11.*Q12).*P1_FilmRef.^2.*P2_FilmRef + (C11.*Q11.^2 + 3.*C11.*Q12.^2 + C12.*Q11.^2 + 5.*C12.*Q12.^2 + 2.*C44.*Q44.^2 + 2.*C11.*Q11.*Q12 + 6.*C12.*Q11.*Q12).*P2_FilmRef.^3 + (3.*C11.*Q11.^2 + 5.*C11.*Q12.^2 - C12.*Q11.^2 + 3.*C12.*Q12.^2 - 2.*C44.*Q44.^2 - 2.*C11.*Q11.*Q12 + 10.*C12.*Q11.*Q12).*P2_FilmRef.*P3_FilmRef.^2; + f3_elastic = (- 2.*C11.*Q12 - 2.*C12.*Q11 - 2.*C12.*Q12).*TotalStrain_FilmRef_11.*P3_FilmRef + (2.*C44.*Q44 - C11.*Q12 - C12.*Q11 - 3.*C12.*Q12 - C11.*Q11).*TotalStrain_FilmRef_22.*P3_FilmRef + (- C11.*Q11 - C11.*Q12 - C12.*Q11 - 3.*C12.*Q12 - 2.*C44.*Q44).*TotalStrain_FilmRef_33.*P3_FilmRef + (-4.*C44.*Q44).*TotalStrain_FilmRef_13.*P1_FilmRef + (2.*C11.*Q12 - 2.*C11.*Q11 + 2.*C12.*Q11 - 2.*C12.*Q12).*TotalStrain_FilmRef_23.*P2_FilmRef + (2.*C11.*Q12.^2 + 2.*C12.*Q11.^2 + 6.*C12.*Q12.^2 + 4.*C44.*Q44.^2 + 4.*C11.*Q11.*Q12 + 4.*C12.*Q11.*Q12).*P1_FilmRef.^2.*P3_FilmRef + (3.*C11.*Q11.^2 + 5.*C11.*Q12.^2 - C12.*Q11.^2 + 3.*C12.*Q12.^2 - 2.*C44.*Q44.^2 - 2.*C11.*Q11.*Q12 + 10.*C12.*Q11.*Q12).*P2_FilmRef.^2.*P3_FilmRef + (C11.*Q11.^2 + 3.*C11.*Q12.^2 + C12.*Q11.^2 + 5.*C12.*Q12.^2 + 2.*C44.*Q44.^2 + 2.*C11.*Q11.*Q12 + 6.*C12.*Q11.*Q12).*P3_FilmRef.^3; + + f1_elastic = f1_elastic .* in_film .* Nucleation_Sites; + f2_elastic = f2_elastic .* in_film .* Nucleation_Sites; + f3_elastic = f3_elastic .* in_film .* Nucleation_Sites; + + f1_elastic_2Dk = fft_2d_slices(f1_elastic); + f2_elastic_2Dk = fft_2d_slices(f2_elastic); + f3_elastic_2Dk = fft_2d_slices(f3_elastic); +else + f1_elastic_2Dk = 0; f2_elastic_2Dk = 0; f3_elastic_2Dk = 0; + f1_elastic = 0; f2_elastic = 0; f3_elastic = 0; + TotalStrain_FilmRef_11 = 0; TotalStrain_FilmRef_22 = 0; + TotalStrain_FilmRef_33 = 0; TotalStrain_FilmRef_12 = 0; + TotalStrain_FilmRef_13 = 0; TotalStrain_FilmRef_23 = 0; + u_FilmRef_1 = 0; u_FilmRef_2 = 0; u_FilmRef_3 = 0; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/GreenTensorSetup.m",".m","1233","39","%% Green's Tensor +Green_FilmRef_k = zeros(Nx,Ny,Nz,3,3); + +% For each k vector find Green's Tensor +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny +for k3_ind = 1 : Nz + + K_vec = [kx_grid_3D(k1_ind,k2_ind,k3_ind) ky_grid_3D(k1_ind,k2_ind,k3_ind) kz_grid_3D(k1_ind,k2_ind,k3_ind)]; % Fourier space vector + g_inv = zeros(3,3); + for i_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + for k_ind = 1 : 3 + g_inv(i_ind,j_ind) = g_inv(i_ind,j_ind) + C_FilmRef(i_ind,k_ind,j_ind,l_ind) * K_vec(k_ind) * K_vec(l_ind); + end + end + end + end + + Green_FilmRef_k(k1_ind,k2_ind,k3_ind,:,:) = inv(g_inv); + +end +end +end + +Green_FilmRef_k((kx==0),(ky==0),(kz==0),:,:) = 0; + +Green_FilmRef_k_11 = squeeze(Green_FilmRef_k(:,:,:,1,1)); +Green_FilmRef_k_12 = squeeze(Green_FilmRef_k(:,:,:,1,2)); +Green_FilmRef_k_13 = squeeze(Green_FilmRef_k(:,:,:,1,3)); + +Green_FilmRef_k_21 = squeeze(Green_FilmRef_k(:,:,:,2,1)); +Green_FilmRef_k_22 = squeeze(Green_FilmRef_k(:,:,:,2,2)); +Green_FilmRef_k_23 = squeeze(Green_FilmRef_k(:,:,:,2,3)); + +Green_FilmRef_k_31 = squeeze(Green_FilmRef_k(:,:,:,3,1)); +Green_FilmRef_k_32 = squeeze(Green_FilmRef_k(:,:,:,3,2)); +Green_FilmRef_k_33 = squeeze(Green_FilmRef_k(:,:,:,3,3));","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/CrystalRef_Transform_FilmRef.m",".m","171","3","P1_FilmRef = P2_CrystalRef; +P2_FilmRef = (2.^(1/2).*P3_CrystalRef)/2 - (2.^(1/2).*P1_CrystalRef)/2; +P3_FilmRef = (2.^(1/2).*P1_CrystalRef)/2 + (2.^(1/2).*P3_CrystalRef)/2;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/EigenstrainInFilm.m",".m","5925","32","%% Eigenstrains +% Transformed eigenstrains, in film reference frame +CalcEigenstrains + +%% Calculate the displacement field via Khachutaryan method +% For each k vector calculate displacement field +u_1_A_k = (- Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/2 - Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_13.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/2 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i)/2 - Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_12.*kz_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i)/2).*C11 + (- Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i - Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i - Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/2 + Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_13.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/2 - Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i)/2 + Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_12.*kz_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i)/2).*C12 + (- Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_12.*kx_grid_3D.*2i - Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_13.*kx_grid_3D.*2i - Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_11.*ky_grid_3D.*2i - Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i + Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i - Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_11.*kz_grid_3D.*2i + Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i - Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i).*C44; +u_2_A_k = (- Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/2 - Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_23.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/2 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i)/2 - Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_22.*kz_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i)/2).*C11 + (- Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i - Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i - Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/2 + Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_23.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/2 - Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i)/2 + Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_22.*kz_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i)/2).*C12 + (- Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_22.*kx_grid_3D.*2i - Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_23.*kx_grid_3D.*2i - Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_21.*ky_grid_3D.*2i - Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i + Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i - Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_21.*kz_grid_3D.*2i + Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i - Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i).*C44; +u_3_A_k = (- Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/2 - Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_33.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/2 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i)/2 - Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_32.*kz_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i)/2).*C11 + (- Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i - Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i - Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/2 + Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_33.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/2 - Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i)/2 + Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_32.*kz_grid_3D.*1i - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i)/2).*C12 + (- Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_32.*kx_grid_3D.*2i - Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_33.*kx_grid_3D.*2i - Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_31.*ky_grid_3D.*2i - Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i + Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i - Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_31.*kz_grid_3D.*2i + Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i - Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i).*C44; + +% DC component = zero by def. +u_1_A_k((kx==0),(ky==0),(kz==0)) = 0; +u_2_A_k((kx==0),(ky==0),(kz==0)) = 0; +u_3_A_k((kx==0),(ky==0),(kz==0)) = 0; + +u_1_A = real( ifftn( u_1_A_k ) ); +u_2_A = real( ifftn( u_2_A_k ) ); +u_3_A = real( ifftn( u_3_A_k ) ); + +e_11_A_k = 1i .* kx_grid_3D .* u_1_A_k; +e_22_A_k = 1i .* ky_grid_3D .* u_2_A_k; +e_33_A_k = 1i .* kz_grid_3D .* u_3_A_k; +e_12_A_k = 0.5 * ( 1i .* kx_grid_3D .* u_2_A_k + 1i .* ky_grid_3D .* u_1_A_k ); +e_13_A_k = 0.5 * ( 1i .* kx_grid_3D .* u_3_A_k + 1i .* kz_grid_3D .* u_1_A_k ); +e_23_A_k = 0.5 * ( 1i .* kz_grid_3D .* u_2_A_k + 1i .* ky_grid_3D .* u_3_A_k ); + +e_11_A = real(ifftn(e_11_A_k)); +e_22_A = real(ifftn(e_22_A_k)); +e_33_A = real(ifftn(e_33_A_k)); +e_12_A = real(ifftn(e_12_A_k)); +e_13_A = real(ifftn(e_13_A_k)); +e_23_A = real(ifftn(e_23_A_k));","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/unfreezeColors.m",".m","3611","107","function unfreezeColors(h) +% unfreezeColors Restore colors of a plot to original indexed color. (v2.3) +% +% Useful if you want to apply a new colormap to plots whose +% colors were previously frozen with freezeColors. +% +% Usage: +% unfreezeColors unfreezes all objects in current axis, +% unfreezeColors(axh) same, but works on axis axh. axh can be vector. +% unfreezeColors(figh) same, but for all objects in figure figh. +% +% Has no effect on objects on which freezeColors was not already called. +% (Note: if colorbars were frozen using cbfreeze, use cbfreeze('off') to +% unfreeze them. See freezeColors for information on cbfreeze.) +% +% +% See also freezeColors, freezeColors_pub.html, cbfreeze. +% +% +% John Iversen (iversen@nsi.edu) 3/23/05 +% + +% Changes: +% JRI 9/1/06 now restores any object with frozen CData; +% can unfreeze an entire figure at once. +% JRI 4/7/10 Change documentation for colorbars + +% Free for all uses, but please retain the following: +% +% Original Author: +% John Iversen, 2005-10 +% john_iversen@post.harvard.edu + +error(nargchk(0,1,nargin,'struct')) + +appdatacode = 'JRI__freezeColorsData'; + +%default: operate on gca +if nargin < 1, + h = gca; +end + +if ~ishandle(h), + error('JRI:unfreezeColors:invalidHandle',... + 'The argument must be a valid graphics handle to a figure or axis') +end + +%if h is a figure, loop on its axes +if strcmp(get(h,'type'),'figure'), + h = get(h,'children'); +end + +for h1 = h', %loop on axes + + %process all children, acting only on those with saved CData + % ( in appdata JRI__freezeColorsData) + ch = findobj(h1); + + for hh = ch', + + %some object handles may be invalidated when their parent changes + % (e.g. restoring colors of a scattergroup unfortunately changes + % the handles of all its children). So, first check to make sure + % it's a valid handle + if ishandle(hh) + if isappdata(hh,appdatacode), + ad = getappdata(hh,appdatacode); + %get oroginal cdata + %patches have to be handled separately (see note in freezeColors) + if ~strcmp(get(hh,'type'),'patch'), + cdata = get(hh,'CData'); + else + cdata = get(hh,'faceVertexCData'); + cdata = permute(cdata,[1 3 2]); + end + indexed = ad{1}; + scalemode = ad{2}; + + %size consistency check + if all(size(indexed) == size(cdata(:,:,1))), + %ok, restore indexed cdata + if ~strcmp(get(hh,'type'),'patch'), + set(hh,'CData',indexed); + else + set(hh,'faceVertexCData',indexed); + end + %restore cdatamapping, if needed + g = get(hh); + if isfield(g,'CDataMapping'), + set(hh,'CDataMapping',scalemode); + end + %clear appdata + rmappdata(hh,appdatacode) + else + warning('JRI:unfreezeColors:internalCdataInconsistency',... + ['Could not restore indexed data: it is the wrong size. ' ... + 'Were the axis contents changed since the call to freezeColors?']) + end + + end %test if has our appdata + end %test ishandle + + end %loop on children + +end %loop on axes + +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/convert.m",".m","1116","42","function color = convert( P1, P2, P3, P1_min,P1_max,P2_min,P2_max,P3_min,P3_max ) +% convert P into a color + +% num = 1024; +% Area = hsv(num); +% Area_axis = linspace(-pi,pi,num); +% Phi = parula(num); +% Phi_axis = linspace(-pi/2,pi/2,num); +% +% +% % find where in the Area P is +% polar_angle = atan2(P2, P1); +% polar_angle = repmat(polar_angle,1,num); +% Area_axis = repmat(Area_axis,numel(P1),1); +% [~, ind] = min(abs(polar_angle - Area_axis),[],2); +% Area_val = Area(ind,:); +% +% % find where in the height P is +% Phi_axis = repmat(Phi_axis,numel(P1),1); +% phi_angle = acos( P3 ./ sqrt( P1.^2 + P2.^2 ) ); phi_angle = repmat(phi_angle,1,num); +% [~, ind] = min(abs(phi_angle - Phi_axis),[],2); +% Height_val = Phi(ind,:); +% +% color = cat(3,Area_val,Height_val); + + % normalize P + R = sqrt(P1.^2 + P2.^2 + P3.^2); + + P1 = P1 ./ R; + P2 = P2 ./ R; + P3 = P3 ./ R; + + R = (P3+1)/2; + G = (P1+1)/2; + B = (P2+1)/2; + + Area_val = [R,G,B]; + Height_val = [R,G,B]; + + color = cat(3,Area_val,Height_val); + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/SurfaceDepolEnergy.m",".m","142","6","%% Surface depolarization field +if( ELECTRIC == 1 && SURFACE_DEPOL == 1 ) + f3_surface_depol_2Dk = 0; +else + f3_surface_depol_2Dk = 0; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/CalcP_CrystalRef.m",".m","336","10","% Calculate P within the film +P1_film = P1_CrystalRef(:,:,interface_index:film_index); +P2_film = P2_CrystalRef(:,:,interface_index:film_index); +P3_film = P3_CrystalRef(:,:,interface_index:film_index); + +P1_val = vol_avg(abs(P1_film)) +P2_val = vol_avg(abs(P2_film)) +P3_val = vol_avg(abs(P3_film)) + +P_val = sqrt(P1_val^2+P2_val^2+P3_val^2)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/EnergyDensities.m",".m","5493","76","% Landau Energy +f_landau = a1 .* ( P1_CrystalRef.^2 + P2_CrystalRef.^2 + P3_CrystalRef.^2 ) + a11 .* ( P1_CrystalRef.^4 + P2_CrystalRef.^4 + P3_CrystalRef.^4 ) + ... + a12 .* ( P1_CrystalRef.^2 .* P2_CrystalRef.^2 + P1_CrystalRef.^2 .* P3_CrystalRef.^2 + P2_CrystalRef.^2 .* P3_CrystalRef.^2 ) + ... + a111 .* ( P1_CrystalRef.^6 + P2_CrystalRef.^6 + P3_CrystalRef.^6 ) + a112 .* ( P1_CrystalRef.^4 .* (P2_CrystalRef.^2 + P3_CrystalRef.^2) + P2_CrystalRef.^4 .* (P3_CrystalRef.^2 + P1_CrystalRef.^2) + P3_CrystalRef.^4 .* (P1_CrystalRef.^2 + P2_CrystalRef.^2) ) + ... + a123 .* ( P1_CrystalRef.^2 .* P2_CrystalRef.^2 .* P3_CrystalRef.^2 ) + ... + a1111 .* ( P1_CrystalRef.^8 + P2_CrystalRef.^8 + P3_CrystalRef.^8 ) + ... + a1112 .* ( P1_CrystalRef.^4 .* P2_CrystalRef.^4 + P2_CrystalRef.^4 .* P3_CrystalRef.^4 + P1_CrystalRef.^4 .* P3_CrystalRef.^4 ) + ... + a1123 .* ( P1_CrystalRef.^4 .* P2_CrystalRef.^2 .* P3_CrystalRef.^2 + P2_CrystalRef.^4 .* P3_CrystalRef.^2 .* P1_CrystalRef.^2 + P3_CrystalRef.^4 .* P1_CrystalRef.^2 .* P2_CrystalRef.^2 ); + +Eigenstrain_11 = Q11 * P1_CrystalRef.^2 + Q12 .* (P2_CrystalRef.^2 + P3_CrystalRef.^2); +Eigenstrain_22 = Q11 * P2_CrystalRef.^2 + Q12 .* (P1_CrystalRef.^2 + P3_CrystalRef.^2); +Eigenstrain_33 = Q11 * P3_CrystalRef.^2 + Q12 .* (P1_CrystalRef.^2 + P2_CrystalRef.^2); +Eigenstrain_23 = Q44 * P2_CrystalRef .* P3_CrystalRef; +Eigenstrain_13 = Q44 * P1_CrystalRef .* P3_CrystalRef; +Eigenstrain_12 = Q44 * P1_CrystalRef .* P2_CrystalRef; + +ElasticStrain_11 = e_11 + e_11_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_11; +ElasticStrain_22 = e_22 + e_22_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_22; +ElasticStrain_33 = e_33 + e_33_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_33; +ElasticStrain_12 = e_12 + e_12_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_12; +ElasticStrain_23 = e_23 + e_23_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_23; +ElasticStrain_13 = e_13 + e_13_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_13; + +f_elastic = (C11/2) .* ( ElasticStrain_11.^2 + ElasticStrain_22.^2 + ElasticStrain_33.^2 ) + ... + (C12) .* ( ElasticStrain_11 .* ElasticStrain_22 + ElasticStrain_22 .* ElasticStrain_33 + ElasticStrain_11 .* ElasticStrain_33 ) + ... + (2*C44) .* ( ElasticStrain_12.^2 + ElasticStrain_23.^2 + ElasticStrain_13.^2 ); + +% e11_tot = e_11 + e_11_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e22_tot = e_22 + e_22_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e33_tot = e_33 + e_33_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e12_tot = e_12 + e_12_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e23_tot = e_23 + e_23_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e13_tot = e_13 + e_13_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% +% f_elastic_2 = b11 .* ( P1_CrystalRef.^4 + P2_CrystalRef.^4 + P3_CrystalRef.^4 ) + b12 .* ( P1_CrystalRef.^2 .* P2_CrystalRef.^2 + P1_CrystalRef.^2 .* P3_CrystalRef.^2 + P2_CrystalRef.^2 .* P3_CrystalRef.^2 ) + ... +% (C11/2) .* ( e11_tot.^2 + e22_tot.^2 + e33_tot.^2 ) + ... +% (C12) .* ( e11_tot .* e22_tot + e22_tot .* e33_tot + e11_tot .* e33_tot ) + ... +% (2*C44) .* ( e12_tot.^2 + e23_tot.^2 + e13_tot.^2 ) + ... +% -( q11 .* e11_tot + q12 .* e22_tot + q12 .* e33_tot ) .* P1_CrystalRef.^2 + ... +% -( q11 .* e22_tot + q12 .* e11_tot + q12 .* e33_tot ) .* P2_CrystalRef.^2 + ... +% -( q11 .* e33_tot + q12 .* e11_tot + q12 .* e22_tot ) .* P3_CrystalRef.^2 + ... +% -(2*q44) .* ( e12_tot .* P1_CrystalRef .* P2_CrystalRef + e23_tot .* P2_CrystalRef .* P3_CrystalRef + e13_tot .* P1_CrystalRef .* P3_CrystalRef ); + +P1_CrystalRef_2Dk = fft_2d_slices(P1_CrystalRef); P2_CrystalRef_2Dk = fft_2d_slices(P2_CrystalRef); P3_CrystalRef_2Dk = fft_2d_slices(P3_CrystalRef); + +P1_CrystalRef_1 = ifft_2d_slices(P1_CrystalRef_2Dk .* kx_grid_3D); +P1_CrystalRef_2 = ifft_2d_slices(P1_CrystalRef_2Dk .* ky_grid_3D); +P1_CrystalRef_3 = finite_diff_x3_first_der(P1_CrystalRef,dz); + +P2_CrystalRef_1 = ifft_2d_slices(P2_CrystalRef_2Dk .* kx_grid_3D); +P2_CrystalRef_2 = ifft_2d_slices(P2_CrystalRef_2Dk .* ky_grid_3D); +P2_CrystalRef_3 = finite_diff_x3_first_der(P2_CrystalRef,dz); + +P3_CrystalRef_1 = ifft_2d_slices(P3_CrystalRef_2Dk .* kx_grid_3D); +P3_CrystalRef_2 = ifft_2d_slices(P3_CrystalRef_2Dk .* ky_grid_3D); +P3_CrystalRef_3 = finite_diff_x3_first_der(P3_CrystalRef,dz); + +G12 = 0; H44 = 0.6 * G110; H14 = 0; +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; + +f_grad = (G11/2) * ( P1_CrystalRef_1.^2 + P2_CrystalRef_2.^2 + P3_CrystalRef_3.^2 ) + ... + G12 .* ( P1_CrystalRef_1 .* P2_CrystalRef_2 + P2_CrystalRef_2 .* P3_CrystalRef_3 + P3_CrystalRef_3 .* P1_CrystalRef_1 ) + ... + (H44/2) .* ( P1_CrystalRef_2.^2 + P2_CrystalRef_1.^2 + P2_CrystalRef_3.^2 + P3_CrystalRef_2.^2 + P1_CrystalRef_3.^2 + P3_CrystalRef_1.^2 ) + ... + (H14 - G12) .* ( P1_CrystalRef_2 .* P2_CrystalRef_1 + P1_CrystalRef_3 .* P3_CrystalRef_1 + P2_CrystalRef_3 .* P3_CrystalRef_2 ); + +f_elec = (-1/2) .* ( E_1_depol .* P1_CrystalRef + E_2_depol .* P2_CrystalRef + E_3_depol .* P3_CrystalRef ); + +f_elec_ext = -( E_1_applied .* P1_CrystalRef + E_2_applied .* P2_CrystalRef + E_3_applied .* P3_CrystalRef ); + +F_landau = sum(sum(sum(f_landau))); +F_elastic = sum(sum(sum(f_elastic))); +F_grad = sum(sum(sum(f_grad))); +F_elec = sum(sum(sum(f_elec))); +F_elec_ext = sum(sum(sum(f_elec_ext))); + +[F_landau, F_elastic,F_grad,F_elec]","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Render3D_CrystalRef.m",".m","124","1","Visualize_3D(P1_CrystalRef,P2_CrystalRef,P3_CrystalRef,x_grid*1e9,y_grid*1e9,z_grid*1e9,interface_index,film_index,Nx,Ny,Nz)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Visualize_3D.m",".m","5720","136","function out = Visualize_3D(P1,P2,P3,x_grid,y_grid,z_grid,interface_index,film_index,Nx,Ny,Nz_film) + P1_film = P1(:,:,interface_index:film_index); + P2_film = P2(:,:,interface_index:film_index); + P3_film = P3(:,:,interface_index:film_index); + + x_grid_film = x_grid(:,:,interface_index:film_index); + y_grid_film = y_grid(:,:,interface_index:film_index); + z_grid_film = z_grid(:,:,interface_index:film_index); + + P1_max = max(max(max(P1_film))); + P1_min = min(min(min(P1_film))); + + P2_max = max(max(max(P2_film))); + P2_min = min(min(min(P2_film))); + + P3_max = max(max(max(P3_film))); + P3_min = min(min(min(P3_film))); + + Nz_film = film_index - interface_index + 1; + + %% Get the sides of the cube... + yz_1_x = x_grid_film(1,:,:); yz_1_x = reshape(yz_1_x,Ny,Nz_film); + yz_1_y = y_grid_film(1,:,:); yz_1_y = reshape(yz_1_y,Ny,Nz_film); + yz_1_z = z_grid_film(1,:,:); yz_1_z = reshape(yz_1_z,Ny,Nz_film); + + yz_1_P1 = P1_film(1,:,:); yz_1_P1 = reshape(yz_1_P1,Ny*Nz_film,1); + yz_1_P2 = P2_film(1,:,:); yz_1_P2 = reshape(yz_1_P2,Ny*Nz_film,1); + yz_1_P3 = P3_film(1,:,:); yz_1_P3 = reshape(yz_1_P3,Ny*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(yz_1_P1,yz_1_P2,yz_1_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Ny,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Ny,Nz_film,3); + yz_1_color = (Area+Height)/2; + + surf(yz_1_x,yz_1_y,yz_1_z,yz_1_color); + hold on; + + %% Get the sides of the cube... + yz_2_x = x_grid_film(end,:,:); yz_2_x = reshape(yz_2_x,Ny,Nz_film); + yz_2_y = y_grid_film(end,:,:); yz_2_y = reshape(yz_2_y,Ny,Nz_film); + yz_2_z = z_grid_film(end,:,:); yz_2_z = reshape(yz_2_z,Ny,Nz_film); + + yz_2_P1 = P1_film(end,:,:); yz_2_P1 = reshape(yz_2_P1,Ny*Nz_film,1); + yz_2_P2 = P2_film(end,:,:); yz_2_P2 = reshape(yz_2_P2,Ny*Nz_film,1); + yz_2_P3 = P3_film(end,:,:); yz_2_P3 = reshape(yz_2_P3,Ny*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(yz_2_P1,yz_2_P2,yz_2_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Ny,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Ny,Nz_film,3); + yz_2_color = (Area+Height)/2; + + surf(yz_2_x,yz_2_y,yz_2_z,yz_2_color); + + + %% Get the sides of the cube... + xz_1_x = x_grid_film(:,1,:); xz_1_x = reshape(xz_1_x,Nx,Nz_film); + xz_1_y = y_grid_film(:,1,:); xz_1_y = reshape(xz_1_y,Nx,Nz_film); + xz_1_z = z_grid_film(:,1,:); xz_1_z = reshape(xz_1_z,Nx,Nz_film); + + xz_1_P1 = P1_film(:,1,:); xz_1_P1 = reshape(xz_1_P1,Nx*Nz_film,1); + xz_1_P2 = P2_film(:,1,:); xz_1_P2 = reshape(xz_1_P2,Nx*Nz_film,1); + xz_1_P3 = P3_film(:,1,:); xz_1_P3 = reshape(xz_1_P3,Nx*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xz_1_P1,xz_1_P2,xz_1_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Nz_film,3); + xz_1_color = (Area+Height)/2; + + surf(xz_1_x,xz_1_y,xz_1_z,xz_1_color); + + %% Get the sides of the cube... + xz_2_x = x_grid_film(:,end,:); xz_2_x = reshape(xz_2_x,Nx,Nz_film); + xz_2_y = y_grid_film(:,end,:); xz_2_y = reshape(xz_2_y,Nx,Nz_film); + xz_2_z = z_grid_film(:,end,:); xz_2_z = reshape(xz_2_z,Nx,Nz_film); + + xz_2_P1 = P1_film(:,end,:); xz_2_P1 = reshape(xz_2_P1,Nx*Nz_film,1); + xz_2_P2 = P2_film(:,end,:); xz_2_P2 = reshape(xz_2_P2,Nx*Nz_film,1); + xz_2_P3 = P3_film(:,end,:); xz_2_P3 = reshape(xz_2_P3,Nx*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xz_2_P1,xz_2_P2,xz_2_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Nz_film,3); + xz_2_color = (Area+Height)/2; + + surf(xz_2_x,xz_2_y,xz_2_z,xz_2_color); + + %% Get the sides of the cube... + xy_1_x = x_grid_film(:,:,1); xy_1_x = reshape(xy_1_x,Nx,Ny); + xy_1_y = y_grid_film(:,:,1); xy_1_y = reshape(xy_1_y,Nx,Ny); + xy_1_z = z_grid_film(:,:,1); xy_1_z = reshape(xy_1_z,Nx,Ny); + + xy_1_P1 = P1_film(:,:,1); xy_1_P1 = reshape(xy_1_P1,Nx*Ny,1); + xy_1_P2 = P2_film(:,:,1); xy_1_P2 = reshape(xy_1_P2,Nx*Ny,1); + xy_1_P3 = P3_film(:,:,1); xy_1_P3 = reshape(xy_1_P3,Nx*Ny,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xy_1_P1,xy_1_P2,xy_1_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Ny,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Ny,3); + xy_1_color = (Area+Height)/2; + + surf(xy_1_x,xy_1_y,xy_1_z,xy_1_color); + + %% Get the sides of the cube... + xy_2_x = x_grid_film(:,:,end); xy_2_x = reshape(xy_2_x,Nx,Ny); + xy_2_y = y_grid_film(:,:,end); xy_2_y = reshape(xy_2_y,Nx,Ny); + xy_2_z = z_grid_film(:,:,end); xy_2_z = reshape(xy_2_z,Nx,Ny); + + xy_2_P1 = P1_film(:,:,end); xy_2_P1 = reshape(xy_2_P1,Nx*Ny,1); + xy_2_P2 = P2_film(:,:,end); xy_2_P2 = reshape(xy_2_P2,Nx*Ny,1); + xy_2_P3 = P3_film(:,:,end); xy_2_P3 = reshape(xy_2_P3,Nx*Ny,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xy_2_P1,xy_2_P2,xy_2_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Ny,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Ny,3); + xy_2_color = (Area+Height)/2; + + surf(xy_2_x,xy_2_y,xy_2_z,xy_2_color); + + %% + axis([min(min(min(x_grid_film))) max(max(max(x_grid_film))) ... + min(min(min(y_grid_film))) max(max(max(y_grid_film))) ... + min(min(min(z_grid_film))) max(max(max(z_grid_film)))] ) + shading flat +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/CalcElecEnergy.m",".m","3453","93","if( ELECTRIC ) + + %% Solve particular solution within the entire sample... + P1_FilmRef_3Dk = fftn(P1_FilmRef); + P2_FilmRef_3Dk = fftn(P2_FilmRef); + P3_FilmRef_3Dk = fftn(P3_FilmRef); + + %%%%%%%% + %%%%%%%% + %% + %% Isotropic relative background permittivity constant --> Nothing changes!! + %% + %%%%%%%% + %%%%%%%% + potential_A_k = -1i .* (kx_grid_3D .* P1_FilmRef_3Dk + ky_grid_3D .* P2_FilmRef_3Dk + kz_grid_3D .* P3_FilmRef_3Dk) ./ ... + ( permittivity_0 .* (k_electric_11 .* kx_grid_3D.^2 + k_electric_22 .* ky_grid_3D.^2 + k_electric_33 .* kz_grid_3D.^2) ); + potential_A_k(k_mag_3D == 0) = 0; + potential_A = real(ifftn(potential_A_k)); + + E_A_1_k = -1i .* kx_grid_3D .* potential_A_k; + E_A_2_k = -1i .* ky_grid_3D .* potential_A_k; + E_A_3_k = -1i .* kz_grid_3D .* potential_A_k; + + E_A_1 = real(ifftn(E_A_1_k)); + E_A_2 = real(ifftn(E_A_2_k)); + E_A_3 = real(ifftn(E_A_3_k)); + + %% Homogenous solution boundary condition application, 2D FT solution + C_mat = zeros(Nx,Ny,2); + potential_bc_interface = squeeze(potential_A(:,:,interface_index)); + potential_bc_film = squeeze(potential_A(:,:,film_index)); + potential_bc_interface_2Dk = -fft2(potential_bc_interface); + potential_bc_film_2Dk = -fft2(potential_bc_film); + potential_bc_given_mat = cat(3,potential_bc_interface_2Dk,potential_bc_film_2Dk); + + potential_B_2Dk = zeros(Nx,Ny,Nz); + potential_B_2Dk_d3 = zeros(Nx,Ny,Nz); + + for k1_ind = 1 : Nx + for k2_ind = 1 : Ny + + C_mat(k1_ind,k2_ind,:) = squeeze(electric_bc_mats_inv(k1_ind,k2_ind,:,:)) * squeeze(potential_bc_given_mat(k1_ind,k2_ind,:)); + + end + end + + C1 = squeeze(C_mat(:,:,1)); C2 = squeeze(C_mat(:,:,2)); + p = sqrt((k_electric_11*kx_grid_2D.^2 + k_electric_22*ky_grid_2D.^2)/k_electric_33); + for z_loop = 1 : numel(z_axis) + potential_B_2Dk(:,:,z_loop) = C1 .* exp(z_axis(z_loop) .* p) + C2 .* exp(-z_axis(z_loop) .* p); + potential_B_2Dk_d3(:,:,z_loop) = p .* C1 .* exp(z_axis(z_loop) .* p) - p .* C2 .* exp(-z_axis(z_loop) .* p); + end + + % Fourier space origin + C_origin = electric_bc_mats_inv_korigin * squeeze(potential_bc_given_mat(1,1,:)); + C1 = C_origin(1); C2 = C_origin(2); + potential_B_2Dk(1,1,:) = C1 * z_axis + C2; + potential_B_2Dk_d3(1,1,:) = C1; + + %% Total Potential + potential_B = ifft_2d_slices(potential_B_2Dk); + potential_FilmRef = potential_A + potential_B; + + % E field + E_B_2Dk_1 = -1i .* kx_grid_3D .* potential_B_2Dk; + E_B_2Dk_2 = -1i .* ky_grid_3D .* potential_B_2Dk; + E_B_2Dk_3 = -potential_B_2Dk_d3; + + E_B_1 = ifft_2d_slices(E_B_2Dk_1); + E_B_2 = ifft_2d_slices(E_B_2Dk_2); + E_B_3 = ifft_2d_slices(E_B_2Dk_3); + + % Depolarization field, not including surface charge effect + E_FilmRef_1_depol = E_A_1 + E_B_1; + E_FilmRef_2_depol = E_A_2 + E_B_2; + E_FilmRef_3_depol = E_A_3 + E_B_3; + + %% Electrical energy define + f1_elec = -0.5 * E_FilmRef_1_depol .* in_film .* Nucleation_Sites; + f2_elec = -0.5 * E_FilmRef_2_depol .* in_film .* Nucleation_Sites; + f3_elec = -0.5 * E_FilmRef_3_depol .* in_film .* Nucleation_Sites; + + f1_elec_2Dk = fft_2d_slices(f1_elec); + f2_elec_2Dk = fft_2d_slices(f2_elec); + f3_elec_2Dk = fft_2d_slices(f3_elec); + +else + + f1_elec_2Dk = 0; f2_elec_2Dk = 0; f3_elec_2Dk = 0; + E_FilmRef_1_depol = 0; E_FilmRef_2_depol = 0; E_FilmRef_3_depol = 0; + potential_FilmRef = 0; + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/ElectrostaticSetup.m",".m","614","19","electric_bc_mats_inv = zeros(Nx,Ny,2,2); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if(k1_ind ~= 1 || k2_ind ~= 1) + eta_1 = kx_grid_2D(k1_ind,k2_ind); + eta_2 = ky_grid_2D(k1_ind,k2_ind); + p = sqrt((k_electric_11*eta_1^2 + k_electric_22*eta_2^2)/k_electric_33); + + potential_sol_mat = [ exp(h_int*p), exp(-h_int*p); ... + exp(h_film*p), exp(-h_film*p)]; + + electric_bc_mats_inv(k1_ind,k2_ind,:,:) = inv(potential_sol_mat); + end +end +end + +electric_bc_mats_inv_korigin = inv( [h_int, 1;... + h_film, 1] );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Setup_BST.m",".m","4981","165","% Run inputs +LOAD = 0; % 1 = Load initial conditions from file called init.mat, 0 = random P initial conditions +E_1_applied_FilmRef = 0; E_2_applied_FilmRef = 0; E_3_applied_FilmRef = 0; % in V/m, 1e5 V/m = 1 kV/cm +T = 17; % in C +Us_11 = 0.5068e-2; % unitless misfit strain +Us_22 = Us_11; % anisotropic misfit strain +% BST composition +BTO_pct = 0.8; STO_pct = 1 - BTO_pct; + + + + + +%% ---- Nothing needed to modify below ---- %% + +%% Convergence +epsilon = 1e-2; % convergence criterion +saves = [0 : 1000 : 20000]; % save after this many iterations + +%% Grid Size +Nx = 64; Ny = Nx; Nz = 36; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 32; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 1 && ELASTIC; % automatically 0 if no elastic energy +% no heterogenous elastic relaxation if no elastic energy + +ELECTRIC = 1; +SURFACE_DEPOL = 0; % depolarization energy due to uncompensated surface charges + +NUCLEATE = 0; % nucleation sites, places that don't change during temporal evolution, 1 -> during hysteresis calcs + +ThermConst = 0; % No thermal energy + +%% BTO = http://www.ems.psu.edu/~chen/publications/YL2005APL.pdf +C11_BTO = 1.78 * 1e11; +C12_BTO = 0.964 * 1e11; +C44_BTO = 1.22 * 1e11; + +Q11_BTO = 0.10; +Q12_BTO = -0.034; +Q44_BTO = 0.029; + +a1_BTO = @(T) 4.124 * ( T - 115 ) * 1e5; +a11_BTO = -2.097 * 1e8; +a12_BTO = 7.974 * 1e8; +a111_BTO = 1.294 * 1e9; +a112_BTO = -1.950 * 1e9; +a123_BTO = -2.5 * 1e9; +a1111_BTO = 3.863 * 1e10; +a1112_BTO = 2.529 * 1e10; +a1122_BTO = 1.637 * 1e10; +a1123_BTO = 1.367 * 1e10; + +%% STO, Table VII, Table I last column +% http://www.wolframalpha.com/input/?i=1+dyn%2Fcm%5E2 +% 1 dyn/cm^2 = 0.1 Pa +C11_STO = 3.36 * 1e11; +C12_STO = 1.07 * 1e11; +C44_STO = 1.27 * 1e11; + +% STO Yu Luan Li PRB 184112, Table II +% 1 cm^4 / esu^2 = 8.988 * 1e10 m^4 / C^2 +% http://www.wolframalpha.com/input/?i=(1+cm)%5E4%2F(3.3356e-10+coulomb)%5E2 +Q11_STO = 4.57 * 1e-2; +Q12_STO = -1.348 * 1e-2; +Q44_STO = 0.957 * 1e-2; + +% STO Yu Luan Li PRB 184112, Table III a1 (1st, from ref 6, 16, 22), Table +% VII a11, a12, a1 +% Shirokov, Yuzyu, PRB 144118, Table I STO in parantheses + +% 1 cm^2 * dyn / esu^2 = 8.9876 * 1e9 J * m^2 / C +a1_STO = @(T) 4.05 * 1e7 * ( coth( 54 / (T+273) ) - coth(54/30) ); + +% 1 cm^6 * dyn / esu^4 = 8.0776 * 1e20 J * m^5 / C^4 +a11_STO = 17 * 1e8; +a12_STO = 13.7 * 1e8; + +a111_STO = 0; +a112_STO = 0; +a123_STO = 0; +a1111_STO = 0; +a1112_STO = 0; +a1122_STO = 0; +a1123_STO = 0; + +%% Elastic Tensor +C11 = C11_BTO * BTO_pct + C11_STO * STO_pct; +C12 = C12_BTO * BTO_pct + C12_STO * STO_pct; +C44 = C44_BTO * BTO_pct + C44_STO * STO_pct; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + +%% Electrostriction +q11_BTO = C11_BTO * Q11_BTO + 2 * C12_BTO * Q12_BTO; +q12_BTO = C11_BTO * Q12_BTO + C12_BTO * (Q11_BTO + Q12_BTO); +q44_BTO = 2 * C44_BTO * Q44_BTO; + +q11_STO = C11_STO * Q11_STO + 2 * C12_STO * Q12_STO; +q12_STO = C11_STO * Q12_STO + C12_STO * (Q11_STO + Q12_STO); +q44_STO = 2 * C44_STO * Q44_STO; + +q11 = q11_BTO * BTO_pct + q11_STO * STO_pct; +q12 = q12_BTO * BTO_pct + q12_STO * STO_pct; +q44 = q44_BTO * BTO_pct + q44_STO * STO_pct; + +q11_h = q11 + 2 * q12; +q22_h = q11 - q12; +C11_h = C11 + 2 * C12; +C22_h = C11 - C12; + +Q11 = (1/3) * ( (q11_h/C11_h) + (2 * q22_h/C22_h) ); +Q12 = (1/3) * ( (q11_h/C11_h) - (q22_h/C22_h) ); +Q44 = q44 / (2 * C44); + +%% LGD Constants, stress free BTO +a1_T = @(T) a1_BTO(T) * BTO_pct + a1_STO(T) * STO_pct; +a1 = a1_T(T); +a11 = a11_BTO * BTO_pct + a11_STO * STO_pct; +a12 = a12_BTO * BTO_pct + a12_STO * STO_pct; +a111 = a111_BTO * BTO_pct + a111_STO * STO_pct; +a112 = a112_BTO * BTO_pct + a112_STO * STO_pct; +a123 = a123_BTO * BTO_pct + a123_STO * STO_pct; +a1111 = a1111_BTO * BTO_pct + a1111_STO * STO_pct; +a1112 = a1112_BTO * BTO_pct + a1112_STO * STO_pct; +a1122 = a1122_BTO * BTO_pct + a1122_STO * STO_pct; +a1123 = a1123_BTO * BTO_pct + a1123_STO * STO_pct; + +%% Simulation Size +l_0 = 1e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = 0.5*l_0*(Nz-1); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = l_0^2 * a0; +G11 = 0.6 * G110; +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = 0.6 * G110; % H44 = G44 + G44' + +%% Run time setup +t_0 = 1/a0; +dt = 0.0125/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% Electrical +permittivity_0 = 8.85418782*1e-12; +k11 = 1000; k22 = k11; k33 = k11;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/HomoStrainSetup.m",".m","756","9","TotalStrain_FilmRef_homo_11 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) Us_11; +TotalStrain_FilmRef_homo_22 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) Us_22; +TotalStrain_FilmRef_homo_12 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) Us_12; +TotalStrain_FilmRef_homo_33 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) -(2*C12*TotalStrain_FilmRef_homo_11(P1_FilmRef,P2_FilmRef,P3_FilmRef) + ... + C11*TotalStrain_FilmRef_homo_22(P1_FilmRef,P2_FilmRef,P3_FilmRef) + ... + C12*TotalStrain_FilmRef_homo_22(P1_FilmRef,P2_FilmRef,P3_FilmRef) - 2*C44*TotalStrain_FilmRef_homo_22(P1_FilmRef,P2_FilmRef,P3_FilmRef))... + /(C11 + C12 + 2*C44); +TotalStrain_FilmRef_homo_23 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) 0; +TotalStrain_FilmRef_homo_13 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) 0;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Main.m",".m","831","44","clc; +rng(1) + +%% Setup stuff +FundamentalConstants; +Setup; +AxesSetup; +Nucleate; +TransformElasticTensor; +GreenTensorSetup; +HomoStrainSetup; + +%% Setup energy stuff +if(VPA_ELASTIC_ON) + InfinitePlateSetup_vpa; +else + InfinitePlateSetup; +end + +if(VPA_ELECTRIC_ON) + ElectrostaticSetup_vpa; +else + ElectrostaticSetup; +end + +%% Initial conditions +InitP; + +%% Energies +CalcElasticEnergy +CalcElecEnergy +ThermalNoise +LandauEnergy +SurfaceDepolEnergy +ExternalEFieldEnergy + +f1_2Dk = f1_landau_2Dk + f1_elec_2Dk + f1_elastic_2Dk + f1_ext_E_2Dk + Thermal_Noise_1_2Dk; +f2_2Dk = f2_landau_2Dk + f2_elec_2Dk + f2_elastic_2Dk + f2_ext_E_2Dk + Thermal_Noise_2_2Dk; +f3_2Dk = f3_landau_2Dk + f3_elec_2Dk + f3_elastic_2Dk + f3_ext_E_2Dk + Thermal_Noise_3_2Dk + f3_surface_depol_2Dk; +c = 0; % Flag for do while loop +error = inf; + +%% Main loop +MainLoop","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/ElectrostaticSetup_vpa.m",".m","694","22","% Use vpa to get more accurate inverted matrices + +electric_bc_mats_inv = zeros(Nx,Ny,2,2); + +for k1 = 1 : Nx +for k2 = 1 : Ny + if(k1 ~= 1 || k2 ~= 1) + eta_1 = kx_grid_2D(k1,k2); + eta_2 = ky_grid_2D(k1,k2); + p = sqrt((k_electric_11*eta_1^2 + k_electric_22*eta_2^2)/k_electric_33); + + potential_sol_mat = [ exp(h_int*p), exp(-h_int*p); ... + exp(h_film*p), exp(-h_film*p)]; + + vpa_mat = vpa(potential_sol_mat); + electric_bc_mats_inv(k1,k2,:,:) = double(inv(vpa_mat)); + end +end +end + +electric_bc_mats_inv_korigin = double ( inv( vpa([h_int, 1;... + h_film, 1]) ) );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/FilmRef_Transform_CrystalRef.m",".m","211","4","% Transform back from film ref to crystal ref +P1_CrystalRef = (2.^(1/2).*P3_FilmRef)/2 - (2.^(1/2).*P2_FilmRef)/2; +P2_CrystalRef = P1_FilmRef; +P3_CrystalRef = (2.^(1/2).*P2_FilmRef)/2 + (2.^(1/2).*P3_FilmRef)/2;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/R_Phases.m",".m","1102","19","r1_plus = ( P1_CrystalRef > 0.3 ) & ( P2_CrystalRef > 0.3 ) & ( P3_CrystalRef > 0.3 ); +r2_plus = ( P1_CrystalRef < -0.3 ) & ( P2_CrystalRef > 0.3 ) & ( P3_CrystalRef > 0.3 ); +r3_plus = ( P1_CrystalRef < -0.3 ) & ( P2_CrystalRef < -0.3 ) & ( P3_CrystalRef > 0.3 ); +r4_plus = ( P1_CrystalRef > 0.3 ) & ( P2_CrystalRef < -0.3 ) & ( P3_CrystalRef > 0.3 ); + +r1_minus = ( P1_CrystalRef < -0.3 ) & ( P2_CrystalRef < -0.3 ) & ( P3_CrystalRef < -0.3 ); +r2_minus = ( P1_CrystalRef > 0.3 ) & ( P2_CrystalRef < -0.3 ) & ( P3_CrystalRef < -0.3 ); +r3_minus = ( P1_CrystalRef > 0.3 ) & ( P2_CrystalRef > 0.3 ) & ( P3_CrystalRef < -0.3 ); +r4_minus = ( P1_CrystalRef < -0.3 ) & ( P2_CrystalRef > 0.3 ) & ( P3_CrystalRef < -0.3 ); + +sum(sum(sum(r1_plus))) / sum(sum(sum(in_film))) +sum(sum(sum(r2_plus))) / sum(sum(sum(in_film))) +sum(sum(sum(r3_plus))) / sum(sum(sum(in_film))) +sum(sum(sum(r4_plus))) / sum(sum(sum(in_film))) + +sum(sum(sum(r1_minus))) / sum(sum(sum(in_film))) +sum(sum(sum(r2_minus))) / sum(sum(sum(in_film))) +sum(sum(sum(r3_minus))) / sum(sum(sum(in_film))) +sum(sum(sum(r4_minus))) / sum(sum(sum(in_film)))","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/vol_avg.m",".m","64","5","function out = vol_avg( f ) + + out = mean(mean(mean(f))); + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/GradEnergy.m",".m","631","13","%% Gradient Free Energy +% Treat the z term not in FFT... +P1_FilmRef_d3_d3 = finite_diff_x3_second_der(P1_FilmRef_prev_2Dk,dz); +P2_FilmRef_d3_d3 = finite_diff_x3_second_der(P2_FilmRef_prev_2Dk,dz); +P3_FilmRef_d3_d3 = finite_diff_x3_second_der(P3_FilmRef_prev_2Dk,dz); + +G1_no_d3 = G11 * kx_grid_3D.^2 + H44 * ky_grid_3D.^2; +G2_no_d3 = G11 * ky_grid_3D.^2 + H44 * kx_grid_3D.^2; +G3_no_d3 = H44 * (kx_grid_3D.^2 + ky_grid_3D.^2); + +G1_d3_part = H44 * P1_FilmRef_d3_d3 .* in_film .* Nucleation_Sites; +G2_d3_part = H44 * P2_FilmRef_d3_d3 .* in_film .* Nucleation_Sites; +G3_d3_part = G11 * P3_FilmRef_d3_d3 .* in_film .* Nucleation_Sites; ","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/SaveData.m",".m","1595","35","save(sprintf('%sfinal__%g Us11__%g Us22__%gC__%gkV-cm__%s.mat',PATH,Us_11*1e2,Us_22*1e2,Temperature,E_1_applied_FilmRef/1e5,STRING),... + 'P1_FilmRef','P2_FilmRef','P3_FilmRef',... + 'P1_FilmRef_prev','P2_FilmRef_prev','P3_FilmRef_prev',... + ... + 'a1','a1_T','a11','a111','a1111','a1112','a112','a1122','a1123','a12','a123',... + ... + 'C11','C12','C44','C_CrystalRef',... + 'TotalStrain_FilmRef_11','TotalStrain_FilmRef_22','TotalStrain_FilmRef_33','TotalStrain_FilmRef_12','TotalStrain_FilmRef_13','TotalStrain_FilmRef_23',... + 'u_FilmRef_1','u_FilmRef_2','u_FilmRef_3',... + 'TotalStrain_FilmRef_homo_11','TotalStrain_FilmRef_homo_22','TotalStrain_FilmRef_homo_33','TotalStrain_FilmRef_homo_12','TotalStrain_FilmRef_homo_13','TotalStrain_FilmRef_homo_23',... + ... + 'q11','q12','q44',... + 'Q11','Q12','Q44',... + ... + 'E_1_applied_FilmRef','E_2_applied_FilmRef','E_3_applied_FilmRef',... + 'E_FilmRef_1_depol','E_FilmRef_2_depol','E_FilmRef_3_depol',... + 'k_electric_11','k_electric_22','k_electric_33',... + 'potential_FilmRef',... + ... + 'G11','G12','H14','H44','G110',... + 'dt',... + 'l_0',... + 'h_film','h_int','h_sub',... + 'interface_index','film_index',... + 'x_axis','y_axis','z_axis',... + 'x_grid','y_grid','z_grid',... + 'Nx','Ny','Nz',... + ... + 'VPA_ELECTRIC_ON','VPA_ELASTIC_ON','ELASTIC','HET_ELASTIC_RELAX',... + 'ELECTRIC','SURFACE_DEPOL','NUCLEATE','ThermConst','LOAD',... + ... + 'Temperature','Us_11','Us_22','Us_12',... + ... + 'Transform_Matrix','in_film','Nucleation_Sites','errors'... + );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/MainLoop.m",".m","2073","63","if( 7 ~= exist(PATH,'dir')) + mkdir(PATH); +end + +errors = zeros(saves(end),1); + +while (c == 0 || error > epsilon) && c < saves(end) + + % saving + if( sum(c == saves) == 1 ) + save(sprintf('%s%g t__%g Us11__%g Us22__%gC__%gkV-cm__%s.mat',PATH,c,Us_11*1e2,Us_22*1e2,Temperature,E_1_applied_FilmRef/1e5,STRING),'P1_FilmRef','P2_FilmRef','P3_FilmRef'); + end + + % Previous iteration + P1_FilmRef_prev_2Dk = P1_FilmRef_2Dk; + f1_prev_2Dk = f1_2Dk; + + P2_FilmRef_prev_2Dk = P2_FilmRef_2Dk; + f2_prev_2Dk = f2_2Dk; + + P3_FilmRef_prev_2Dk = P3_FilmRef_2Dk; + f3_prev_2Dk = f3_2Dk; + + P1_FilmRef_prev = P1_FilmRef; + P2_FilmRef_prev = P2_FilmRef; + P3_FilmRef_prev = P3_FilmRef; + + % Next iteration + GradEnergy % d3_part uses previous P's + P1_FilmRef_2Dk = (( P1_FilmRef_prev_2Dk + dt .* -f1_prev_2Dk + dt .* G1_d3_part ) ./ ( 1 + dt .* G1_no_d3 )); + P2_FilmRef_2Dk = (( P2_FilmRef_prev_2Dk + dt .* -f2_prev_2Dk + dt .* G2_d3_part ) ./ ( 1 + dt .* G2_no_d3 )); + P3_FilmRef_2Dk = (( P3_FilmRef_prev_2Dk + dt .* -f3_prev_2Dk + dt .* G3_d3_part ) ./ ( 1 + dt .* G3_no_d3 )); + + P1_FilmRef = ifft_2d_slices(P1_FilmRef_2Dk); + P2_FilmRef = ifft_2d_slices(P2_FilmRef_2Dk); + P3_FilmRef = ifft_2d_slices(P3_FilmRef_2Dk); + + CalcElasticEnergy + CalcElecEnergy + ThermalNoise; + LandauEnergy + SurfaceDepolEnergy + ExternalEFieldEnergy + + f1_2Dk = f1_landau_2Dk + f1_elec_2Dk + f1_elastic_2Dk + f1_ext_E_2Dk + Thermal_Noise_1_2Dk; + f2_2Dk = f2_landau_2Dk + f2_elec_2Dk + f2_elastic_2Dk + f2_ext_E_2Dk + Thermal_Noise_2_2Dk; + f3_2Dk = f3_landau_2Dk + f3_elec_2Dk + f3_elastic_2Dk + f3_ext_E_2Dk + Thermal_Noise_3_2Dk + f3_surface_depol_2Dk; + + c = c + 1; + + % Progress + error = max( [sum(sum(sum(abs(P1_FilmRef-P1_FilmRef_prev)))); sum(sum(sum(abs(P2_FilmRef-P2_FilmRef_prev)))); sum(sum(sum(abs(P3_FilmRef-P3_FilmRef_prev))))] ); + errors(c) = error; + % print error + if( mod(c, 50) == 0 ) + Visualize + drawnow + error + end + +end + +SaveData","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Pretty.m",".m","334","8","Render3D_CrystalRef +dx = x_axis(2) - x_axis(1); +dy = y_axis(2) - y_axis(1); +dz = z_axis(2) - z_axis(1); + +axis([min(x_axis)*1e9, max(x_axis)*1e9, min(y_axis)*1e9, max(y_axis)*1e9,... + min(z_axis)*1e9, (min(z_axis)+(max(x_axis)-min(x_axis)))*1e9]); +set(gca,'xtick',[]);set(gca,'ytick',[]);set(gca,'ztick',[]);set(gca,'Visible','off')","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/freezeColors.m",".m","9815","276","function freezeColors(varargin) +% freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3) +% +% Problem: There is only one colormap per figure. This function provides +% an easy solution when plots using different colomaps are desired +% in the same figure. +% +% freezeColors freezes the colors of graphics objects in the current axis so +% that subsequent changes to the colormap (or caxis) will not change the +% colors of these objects. freezeColors works on any graphics object +% with CData in indexed-color mode: surfaces, images, scattergroups, +% bargroups, patches, etc. It works by converting CData to true-color rgb +% based on the colormap active at the time freezeColors is called. +% +% The original indexed color data is saved, and can be restored using +% unfreezeColors, making the plot once again subject to the colormap and +% caxis. +% +% +% Usage: +% freezeColors applies to all objects in current axis (gca), +% freezeColors(axh) same, but works on axis axh. +% +% Example: +% subplot(2,1,1); imagesc(X); colormap hot; freezeColors +% subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc... +% +% Note: colorbars must also be frozen. Due to Matlab 'improvements' this can +% no longer be done with freezeColors. Instead, please +% use the function CBFREEZE by Carlos Adrian Vargas Aguilera +% that can be downloaded from the MATLAB File Exchange +% (http://www.mathworks.com/matlabcentral/fileexchange/24371) +% +% h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar) +% +% For additional examples, see test/test_main.m +% +% Side effect on render mode: freezeColors does not work with the painters +% renderer, because Matlab doesn't support rgb color data in +% painters mode. If the current renderer is painters, freezeColors +% changes it to zbuffer. This may have unexpected effects on other aspects +% of your plots. +% +% See also unfreezeColors, freezeColors_pub.html, cbfreeze. +% +% +% John Iversen (iversen@nsi.edu) 3/23/05 +% + +% Changes: +% JRI (iversen@nsi.edu) 4/19/06 Correctly handles scaled integer cdata +% JRI 9/1/06 should now handle all objects with cdata: images, surfaces, +% scatterplots. (v 2.1) +% JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded) +% JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3) +% JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it. +% JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf) +% JRI 4/7/10 Change documentation for colorbars + +% Hidden option for NaN colors: +% Missing data are often represented by NaN in the indexed color +% data, which renders transparently. This transparency will be preserved +% when freezing colors. If instead you wish such gaps to be filled with +% a real color, add 'nancolor',[r g b] to the end of the arguments. E.g. +% freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]), +% where [r g b] is a color vector. This works on images & pcolor, but not on +% surfaces. +% Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes +% attributed in the code. + +% Free for all uses, but please retain the following: +% Original Author: +% John Iversen, 2005-10 +% john_iversen@post.harvard.edu + +appdatacode = 'JRI__freezeColorsData'; + +[h, nancolor] = checkArgs(varargin); + +%gather all children with scaled or indexed CData +cdatah = getCDataHandles(h); + +%current colormap +cmap = colormap; +nColors = size(cmap,1); +cax = caxis; + +% convert object color indexes into colormap to true-color data using +% current colormap +for hh = cdatah', + g = get(hh); + + %preserve parent axis clim + parentAx = getParentAxes(hh); + originalClim = get(parentAx, 'clim'); + + % Note: Special handling of patches: For some reason, setting + % cdata on patches created by bar() yields an error, + % so instead we'll set facevertexcdata instead for patches. + if ~strcmp(g.Type,'patch'), + cdata = g.CData; + else + cdata = g.FaceVertexCData; + end + + %get cdata mapping (most objects (except scattergroup) have it) + if isfield(g,'CDataMapping'), + scalemode = g.CDataMapping; + else + scalemode = 'scaled'; + end + + %save original indexed data for use with unfreezeColors + siz = size(cdata); + setappdata(hh, appdatacode, {cdata scalemode}); + + %convert cdata to indexes into colormap + if strcmp(scalemode,'scaled'), + %4/19/06 JRI, Accommodate scaled display of integer cdata: + % in MATLAB, uint * double = uint, so must coerce cdata to double + % Thanks to O Yamashita for pointing this need out + idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors); + else %direct mapping + idx = cdata; + %10/8/09 in case direct data is non-int (e.g. image;freezeColors) + % (Floor mimics how matlab converts data into colormap index.) + % Thanks to D Armyr for the catch + idx = floor(idx); + end + + %clamp to [1, nColors] + idx(idx<1) = 1; + idx(idx>nColors) = nColors; + + %handle nans in idx + nanmask = isnan(idx); + idx(nanmask)=1; %temporarily replace w/ a valid colormap index + + %make true-color data--using current colormap + realcolor = zeros(siz); + for i = 1:3, + c = cmap(idx,i); + c = reshape(c,siz); + c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified) + realcolor(:,:,i) = c; + end + + %apply new true-color color data + + %true-color is not supported in painters renderer, so switch out of that + if strcmp(get(gcf,'renderer'), 'painters'), + set(gcf,'renderer','zbuffer'); + end + + %replace original CData with true-color data + if ~strcmp(g.Type,'patch'), + set(hh,'CData',realcolor); + else + set(hh,'faceVertexCData',permute(realcolor,[1 3 2])) + end + + %restore clim (so colorbar will show correct limits) + if ~isempty(parentAx), + set(parentAx,'clim',originalClim) + end + +end %loop on indexed-color objects + + +% ============================================================================ % +% Local functions + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% getCDataHandles -- get handles of all descendents with indexed CData +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function hout = getCDataHandles(h) +% getCDataHandles Find all objects with indexed CData + +%recursively descend object tree, finding objects with indexed CData +% An exception: don't include children of objects that themselves have CData: +% for example, scattergroups are non-standard hggroups, with CData. Changing +% such a group's CData automatically changes the CData of its children, +% (as well as the children's handles), so there's no need to act on them. + +error(nargchk(1,1,nargin,'struct')) + +hout = []; +if isempty(h),return;end + +ch = get(h,'children'); +for hh = ch' + g = get(hh); + if isfield(g,'CData'), %does object have CData? + %is it indexed/scaled? + if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1, + hout = [hout; hh]; %#ok %yes, add to list + end + else %no CData, see if object has any interesting children + hout = [hout; getCDataHandles(hh)]; %#ok + end +end + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% getParentAxes -- return handle of axes object to which a given object belongs +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +function hAx = getParentAxes(h) +% getParentAxes Return enclosing axes of a given object (could be self) + +error(nargchk(1,1,nargin,'struct')) +%object itself may be an axis +if strcmp(get(h,'type'),'axes'), + hAx = h; + return +end + +parent = get(h,'parent'); +if (strcmp(get(parent,'type'), 'axes')), + hAx = parent; +else + hAx = getParentAxes(parent); +end + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% checkArgs -- Validate input arguments +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function [h, nancolor] = checkArgs(args) +% checkArgs Validate input arguments to freezeColors + +nargs = length(args); +error(nargchk(0,3,nargs,'struct')) + +%grab handle from first argument if we have an odd number of arguments +if mod(nargs,2), + h = args{1}; + if ~ishandle(h), + error('JRI:freezeColors:checkArgs:invalidHandle',... + 'The first argument must be a valid graphics handle (to an axis)') + end + % 4/2010 check if object to be frozen is a colorbar + if strcmp(get(h,'Tag'),'Colorbar'), + if ~exist('cbfreeze.m'), + warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',... + ['You seem to be attempting to freeze a colorbar. This no longer'... + 'works. Please read the help for freezeColors for the solution.']) + else + cbfreeze(h); + return + end + end + args{1} = []; + nargs = nargs-1; +else + h = gca; +end + +%set nancolor if that option was specified +nancolor = [nan nan nan]; +if nargs == 2, + if strcmpi(args{end-1},'nancolor'), + nancolor = args{end}; + if ~all(size(nancolor)==[1 3]), + error('JRI:freezeColors:checkArgs:badColorArgument',... + 'nancolor must be [r g b] vector'); + end + nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0; + else + error('JRI:freezeColors:checkArgs:unrecognizedOption',... + 'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1}) + end +end + + +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/CalcEigenstrains.m",".m","1273","19","Eigenstrain_FilmRef_11 = P1_FilmRef.^2.*Q11 + (P2_FilmRef.^2 + P3_FilmRef.^2).*Q12; +Eigenstrain_FilmRef_12 = (P1_FilmRef.*P2_FilmRef).*Q44; +Eigenstrain_FilmRef_13 = (P1_FilmRef.*P3_FilmRef).*Q44; +Eigenstrain_FilmRef_21 = Eigenstrain_FilmRef_12; +Eigenstrain_FilmRef_22 = (P2_FilmRef.^2/2 + P3_FilmRef.^2/2).*Q11 + (P1_FilmRef.^2 + P2_FilmRef.^2/2 + P3_FilmRef.^2/2).*Q12 + (P2_FilmRef.^2/2 - P3_FilmRef.^2/2).*Q44; +Eigenstrain_FilmRef_23 = (P2_FilmRef.*P3_FilmRef).*Q11 + (-P2_FilmRef.*P3_FilmRef).*Q12; +Eigenstrain_FilmRef_31 = Eigenstrain_FilmRef_13; +Eigenstrain_FilmRef_32 = Eigenstrain_FilmRef_23; +Eigenstrain_FilmRef_33 = (P2_FilmRef.^2/2 + P3_FilmRef.^2/2).*Q11 + (P1_FilmRef.^2 + P2_FilmRef.^2/2 + P3_FilmRef.^2/2).*Q12 + (P3_FilmRef.^2/2 - P2_FilmRef.^2/2).*Q44; + +Eigenstrain_FilmRef_11_k = fftn(Eigenstrain_FilmRef_11); +Eigenstrain_FilmRef_22_k = fftn(Eigenstrain_FilmRef_22); +Eigenstrain_FilmRef_33_k = fftn(Eigenstrain_FilmRef_33); +Eigenstrain_FilmRef_23_k = fftn(Eigenstrain_FilmRef_23); +Eigenstrain_FilmRef_13_k = fftn(Eigenstrain_FilmRef_13); +Eigenstrain_FilmRef_12_k = fftn(Eigenstrain_FilmRef_12); +Eigenstrain_FilmRef_21_k = Eigenstrain_FilmRef_12_k; +Eigenstrain_FilmRef_31_k = Eigenstrain_FilmRef_13_k; +Eigenstrain_FilmRef_32_k = Eigenstrain_FilmRef_23_k;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/LandauEnergy.m",".m","4241","12","%% Landau Free Energy +f1_landau = a1122.*(2.*P1_FilmRef.^3.*P2_FilmRef.^4 + 12.*P1_FilmRef.^3.*P2_FilmRef.^2.*P3_FilmRef.^2 + 2.*P1_FilmRef.^3.*P3_FilmRef.^4) + 2.*P1_FilmRef.*a1 + a112.*(4.*P1_FilmRef.^3.*P2_FilmRef.^2 + 4.*P1_FilmRef.^3.*P3_FilmRef.^2 + P1_FilmRef.*P2_FilmRef.^4 + 6.*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^2 + P1_FilmRef.*P3_FilmRef.^4) + 4.*P1_FilmRef.^3.*a11 + 6.*P1_FilmRef.^5.*a111 + 8.*P1_FilmRef.^7.*a1111 + a1112.*(6.*P1_FilmRef.^5.*P2_FilmRef.^2 + 6.*P1_FilmRef.^5.*P3_FilmRef.^2 + (P1_FilmRef.*P2_FilmRef.^6)/2 + (15.*P1_FilmRef.*P2_FilmRef.^4.*P3_FilmRef.^2)/2 + (15.*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^4)/2 + (P1_FilmRef.*P3_FilmRef.^6)/2) + a12.*(2.*P1_FilmRef.*P2_FilmRef.^2 + 2.*P1_FilmRef.*P3_FilmRef.^2) + a1123.*(P1_FilmRef.^3.*P2_FilmRef.^4 - 2.*P1_FilmRef.^3.*P2_FilmRef.^2.*P3_FilmRef.^2 + P1_FilmRef.^3.*P3_FilmRef.^4 + (P1_FilmRef.*P2_FilmRef.^6)/2 - (P1_FilmRef.*P2_FilmRef.^4.*P3_FilmRef.^2)/2 - (P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^4)/2 + (P1_FilmRef.*P3_FilmRef.^6)/2) + a123.*((P1_FilmRef.*P2_FilmRef.^4)/2 - P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^2 + (P1_FilmRef.*P3_FilmRef.^4)/2); +f2_landau = 2.*P2_FilmRef.*a1 - a1123.*(- P1_FilmRef.^4.*P2_FilmRef.^3 + P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2 - (3.*P1_FilmRef.^2.*P2_FilmRef.^5)/2 + P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2 + (P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/2) + a1112.*(2.*P1_FilmRef.^6.*P2_FilmRef + (3.*P1_FilmRef.^2.*P2_FilmRef.^5)/2 + 15.*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2 + (15.*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/2 + P2_FilmRef.^7 + 3.*P2_FilmRef.^5.*P3_FilmRef.^2 - 5.*P2_FilmRef.^3.*P3_FilmRef.^4 + P2_FilmRef.*P3_FilmRef.^6) + a111.*((3.*P2_FilmRef.^5)/2 + 15.*P2_FilmRef.^3.*P3_FilmRef.^2 + (15.*P2_FilmRef.*P3_FilmRef.^4)/2) + a112.*(2.*P1_FilmRef.^4.*P2_FilmRef + 2.*P1_FilmRef.^2.*P2_FilmRef.^3 + 6.*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2 + (3.*P2_FilmRef.^5)/2 - P2_FilmRef.^3.*P3_FilmRef.^2 - (P2_FilmRef.*P3_FilmRef.^4)/2) + a12.*(2.*P1_FilmRef.^2.*P2_FilmRef + P2_FilmRef.^3 - P2_FilmRef.*P3_FilmRef.^2) + a11.*(2.*P2_FilmRef.^3 + 6.*P2_FilmRef.*P3_FilmRef.^2) + a1111.*(P2_FilmRef.^7 + 21.*P2_FilmRef.^5.*P3_FilmRef.^2 + 35.*P2_FilmRef.^3.*P3_FilmRef.^4 + 7.*P2_FilmRef.*P3_FilmRef.^6) + a1122.*(2.*P1_FilmRef.^4.*P2_FilmRef.^3 + 6.*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2 + P2_FilmRef.^7/2 - (3.*P2_FilmRef.^5.*P3_FilmRef.^2)/2 + (3.*P2_FilmRef.^3.*P3_FilmRef.^4)/2 - (P2_FilmRef.*P3_FilmRef.^6)/2) + a123.*(P1_FilmRef.^2.*P2_FilmRef.^3 - P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2); +f3_landau = 2.*P3_FilmRef.*a1 - a1123.*(P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef - P1_FilmRef.^4.*P3_FilmRef.^3 + (P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/2 + P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3 - (3.*P1_FilmRef.^2.*P3_FilmRef.^5)/2) + a1112.*(2.*P1_FilmRef.^6.*P3_FilmRef + (15.*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/2 + 15.*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3 + (3.*P1_FilmRef.^2.*P3_FilmRef.^5)/2 + P2_FilmRef.^6.*P3_FilmRef - 5.*P2_FilmRef.^4.*P3_FilmRef.^3 + 3.*P2_FilmRef.^2.*P3_FilmRef.^5 + P3_FilmRef.^7) + a111.*((15.*P2_FilmRef.^4.*P3_FilmRef)/2 + 15.*P2_FilmRef.^2.*P3_FilmRef.^3 + (3.*P3_FilmRef.^5)/2) + a112.*(2.*P1_FilmRef.^4.*P3_FilmRef + 6.*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef + 2.*P1_FilmRef.^2.*P3_FilmRef.^3 - (P2_FilmRef.^4.*P3_FilmRef)/2 - P2_FilmRef.^2.*P3_FilmRef.^3 + (3.*P3_FilmRef.^5)/2) + a12.*(2.*P1_FilmRef.^2.*P3_FilmRef - P2_FilmRef.^2.*P3_FilmRef + P3_FilmRef.^3) + a11.*(6.*P2_FilmRef.^2.*P3_FilmRef + 2.*P3_FilmRef.^3) + a1111.*(7.*P2_FilmRef.^6.*P3_FilmRef + 35.*P2_FilmRef.^4.*P3_FilmRef.^3 + 21.*P2_FilmRef.^2.*P3_FilmRef.^5 + P3_FilmRef.^7) + a1122.*(6.*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef + 2.*P1_FilmRef.^4.*P3_FilmRef.^3 - (P2_FilmRef.^6.*P3_FilmRef)/2 + (3.*P2_FilmRef.^4.*P3_FilmRef.^3)/2 - (3.*P2_FilmRef.^2.*P3_FilmRef.^5)/2 + P3_FilmRef.^7/2) + a123.*(- P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef + P1_FilmRef.^2.*P3_FilmRef.^3); + +f1_landau = f1_landau .* in_film .* Nucleation_Sites; +f2_landau = f2_landau .* in_film .* Nucleation_Sites; +f3_landau = f3_landau .* in_film .* Nucleation_Sites; + +f1_landau_2Dk = fft_2d_slices(f1_landau); +f2_landau_2Dk = fft_2d_slices(f2_landau); +f3_landau_2Dk = fft_2d_slices(f3_landau);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/CalculateStrain.m",".m","1783","58","if(HET_ELASTIC_RELAX) + EigenstrainInFilm; + InfinitePlate; +else % Don't do heterogenous strain relaxation + u_1_A = 0; + u_2_A = 0; + u_3_A = 0; + + u_1_B = 0; + u_2_B = 0; + u_3_B = 0; + + e_11_A = 0; + e_22_A = 0; + e_33_A = 0; + e_12_A = 0; + e_13_A = 0; + e_23_A = 0; + + e_11_B = 0; + e_22_B = 0; + e_33_B = 0; + e_12_B = 0; + e_13_B = 0; + e_23_B = 0; +end + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% +%% +% A + B = het strains +% A + B + homo = total strain +%% +%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% e_FilmRef_het_11 = e_11_A + e_11_B; +% e_FilmRef_het_22 = e_22_A + e_22_B; +% e_FilmRef_het_33 = e_33_A + e_33_B; +% e_FilmRef_het_12 = e_12_A + e_12_B; +% e_FilmRef_het_13 = e_13_A + e_13_B; +% e_FilmRef_het_23 = e_23_A + e_23_B; +% e_FilmRef_het_21 = e_12_FilmRef_het; +% e_FilmRef_het_31 = e_13_FilmRef_het; +% e_FilmRef_het_32 = e_23_FilmRef_het; + +u_FilmRef_1 = u_1_A + u_1_B; +u_FilmRef_2 = u_2_A + u_2_B; +u_FilmRef_3 = u_3_A + u_3_B; + +TotalStrain_FilmRef_11 = e_11_A + e_11_B + TotalStrain_FilmRef_homo_11(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_12 = e_12_A + e_12_B + TotalStrain_FilmRef_homo_12(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_13 = e_13_A + e_13_B + TotalStrain_FilmRef_homo_13(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_22 = e_22_A + e_22_B + TotalStrain_FilmRef_homo_22(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_23 = e_23_A + e_23_B + TotalStrain_FilmRef_homo_23(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_33 = e_33_A + e_33_B + TotalStrain_FilmRef_homo_33(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_32 = TotalStrain_FilmRef_23; +TotalStrain_FilmRef_21 = TotalStrain_FilmRef_12; +TotalStrain_FilmRef_31 = TotalStrain_FilmRef_13;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Hysteresis.m",".m","2771","115","%% Nucleation sites, have 0 free energy change... +Setup +% Nucleation_Sites = +(rand(Nx,Ny,Nz) < (1-0.01)) .* in_film; +L = 5; +Nucleation_Sites = ones(Nx,Ny,Nz); +xy_edges = 8; +z_edges = 2; +for i = 1 : 7 + Nucleation_Sites(randi([xy_edges,Nx-L+1-xy_edges])+(0:L-1),randi([xy_edges,Ny-L+1-xy_edges])+(0:L-1),randi([z_edges,Nz-L+1-z_edges])+(0:L-1)) = 0; +end + +% Percent of nucleation sites +Nucleation_pct = abs(sum(sum(sum(Nucleation_Sites-1)))/(Nx*Ny*(film_index-interface_index+1))); + +%% Hysteresis Loops + +% Run 0 kV/cm + +% +Load = 1; +E_fields_tot = [0, 1e2, 1e3, 1e4, 1e5, 5e5, 1e6, 2e6, 3e6, 4e6, 5e6, 6e6, 7e6, 8e6, 9e6, 1e7]; +E_vectors = []; +P_vectors = []; + +%% +E_fields = E_fields_tot(2:end); + +for E_1_applied_FilmRef = E_fields + + folder = sprintf('%gkV-cm',E_1_applied_FilmRef/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied_FilmRef]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied_FilmRef/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +%% +E_fields = E_fields_tot(1:end-1); +E_fields = fliplr(E_fields); + +for E_1_applied_FilmRef = E_fields + + folder = sprintf('%g_2kV-cm',E_1_applied_FilmRef/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied_FilmRef]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied_FilmRef/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +%% +E_fields = -E_fields_tot(2:end); + +for E_1_applied_FilmRef = E_fields + + folder = sprintf('%gkV-cm',E_1_applied_FilmRef/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied_FilmRef]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied_FilmRef/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +%% +E_fields = -E_fields_tot(1:end-1); +E_fields = fliplr(E_fields); + +for E_1_applied_FilmRef = E_fields + + folder = sprintf('%g_2kV-cm',E_1_applied_FilmRef/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied_FilmRef]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied_FilmRef/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +save('PE','P_vectors','E_vectors');","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Nucleate.m",".m","566","16","%% Nucleation sites, have 0 free energy change... +% Nucleation_Sites = +(rand(Nx,Ny,Nz) < (1-0.01)) .* in_film; +if( NUCLEATE ) + L = 5; + Nucleation_Sites = ones(Nx,Ny,Nz); + xy_edges = 8; + z_edges = 2; + for i_ind = 1 : 7 + Nucleation_Sites(randi([xy_edges,Nx-L+1-xy_edges])+(0:L-1),randi([xy_edges,Ny-L+1-xy_edges])+(0:L-1),randi([z_edges,Nz-L+1-z_edges])+(0:L-1)) = 0; + end + + % Percent of nucleation sites + Nucleation_pct = abs(sum(sum(sum(Nucleation_Sites-1)))/(Nx*Ny*(film_index-interface_index+1))); +else + Nucleation_Sites = 1; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/InfinitePlateSetup_vpa.m",".m","3887","93","U = zeros(3,3); +m = [0, 0, 1]; +for i_ind = 1 : 3 +for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + U(i_ind,k_ind) = U(i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * m(j_ind) * m(l_ind); + end + end +end +end + +R = zeros(Nx,Ny,3,3); W = zeros(numel(kx),numel(ky),3,3); +eigenvec_mat = zeros(Nx,Ny,6,6); % the eigenvalues and eigenvectors found at each k vector pt +eigenval_mat = zeros(Nx,Ny,6); % the eigenvalues and eigenvectors found at each k vector pt +mat_mat = zeros(numel(kx),numel(ky),6,6); + +for k1_ind = 1 : numel(kx) +for k2_ind = 1 : numel(ky) + + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Origin, different solution, be mindful of dividing by k vector as well! + + n = [ kx_grid_2D(k1_ind,k2_ind), ky_grid_2D(k1_ind,k2_ind), 0 ] ./ sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ) ; + + for i_ind = 1 : 3 + for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + R(k1_ind,k2_ind,i_ind,k_ind) = R(k1_ind,k2_ind,i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * m(l_ind); + W(k1_ind,k2_ind,i_ind,k_ind) = W(k1_ind,k2_ind,i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * n(l_ind); + end + end + end + end + + R_mat = squeeze(R(k1_ind,k2_ind,:,:)); + W_mat = squeeze(W(k1_ind,k2_ind,:,:)); + + + N1 = -inv(U)*R_mat'; N2 = inv(U); N3 = R_mat*inv(U)*R_mat'-W_mat; + mat = [N1, N2; N3, N1']; + vpa_mat = vpa(mat); + + [eigenvec, eigenval] = eig(vpa_mat); + eigenvec = double(eigenvec); + eigenval = diag(double(eigenval)); + + mat_mat(k1_ind,k2_ind,:,:) = mat; + eigenvec_mat(k1_ind,k2_ind,:,:) = eigenvec; + eigenval_mat(k1_ind,k2_ind,:) = eigenval; + + end +end +end + +%% BC matrix solutions +bc_mats = zeros(Nx,Ny,6,6); +strain_bc_mats_inv = zeros(Nx,Ny,6,6); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Because we divide by K^2 to make matrices better + K = sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ); + bc_mat = zeros(6,6); + % [ d1 * eigenvec(1,1) + d2 * eigenvec(1,2) + + % d1 * eigenvec(2,1) + d2 * eigenvec(2,2) + + % d1 * eigenvec(3,1) + d2 * eigenvec(3,2) + + % d1 * eigenvec(4,1) + d2 * eigenvec(4,2) + + for m = 1 : 6 % the eigenvalue -> column of eigenvec_mat ~ eigenvector + for k_ind = 1 : 3 % eigenvector a, scale by K + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_sub*1i*K); + end + % rescale by K^-1 to avoid conditioning errors... need to rescale + % the given value as well! + for k_ind = 4 : 6 % eigenvector b + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_film*1i*K) * 1i * K / K^2; + end + end + bc_mats(k1_ind,k2_ind,:,:) = bc_mat; + + vpa_mat = vpa(bc_mat); + strain_bc_mats_inv(k1_ind,k2_ind,:,:) = double(inv(vpa_mat)); + end +end +end + +strain_bc_mat_inv_korigin = inv( vpa([ h_sub 1 0 0 0 0 ; ... + 0 0 h_sub 1 0 0 ; ... + 0 0 0 0 h_sub 1 ; ... + C_FilmRef(1,3,1,3) 0 C_FilmRef(1,3,2,3) 0 C_FilmRef(1,3,3,3) 0 ; ... + C_FilmRef(2,3,1,3) 0 C_FilmRef(2,3,2,3) 0 C_FilmRef(2,3,3,3) 0 ; ... + C_FilmRef(3,3,1,3) 0 C_FilmRef(3,3,2,3) 0 C_FilmRef(3,3,3,3) 0 ]) ); +strain_bc_mat_inv_korigin = double(strain_bc_mat_inv_korigin);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/FundamentalConstants.m",".m","34","1","permittivity_0 = 8.85418782*1e-12;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/InfinitePlateSetup.m",".m","3695","88","U = zeros(3,3); +m = [0, 0, 1]; +for i_ind = 1 : 3 +for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + U(i_ind,k_ind) = U(i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * m(j_ind) * m(l_ind); + end + end +end +end + +R = zeros(Nx,Ny,3,3); W = zeros(numel(kx),numel(ky),3,3); +eigenvec_mat = zeros(Nx,Ny,6,6); % the eigenvalues and eigenvectors found at each k vector pt +eigenval_mat = zeros(Nx,Ny,6); % the eigenvalues and eigenvectors found at each k vector pt +mat_mat = zeros(numel(kx),numel(ky),6,6); + +for k1_ind = 1 : numel(kx) +for k2_ind = 1 : numel(ky) + + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Origin, different solution, be mindful of dividing by k vector as well! + + n = [ kx_grid_2D(k1_ind,k2_ind), ky_grid_2D(k1_ind,k2_ind), 0 ] ./ sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ) ; + + for i_ind = 1 : 3 + for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + R(k1_ind,k2_ind,i_ind,k_ind) = R(k1_ind,k2_ind,i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * m(l_ind); + W(k1_ind,k2_ind,i_ind,k_ind) = W(k1_ind,k2_ind,i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * n(l_ind); + end + end + end + end + + R_mat = squeeze(R(k1_ind,k2_ind,:,:)); + W_mat = squeeze(W(k1_ind,k2_ind,:,:)); + + + N1 = -inv(U)*R_mat'; N2 = inv(U); N3 = R_mat*inv(U)*R_mat'-W_mat; + mat = [N1, N2; N3, N1']; + + [eigenvec, eigenval] = eig(mat,'vector'); + + mat_mat(k1_ind,k2_ind,:,:) = mat; + eigenvec_mat(k1_ind,k2_ind,:,:) = eigenvec; + eigenval_mat(k1_ind,k2_ind,:) = eigenval; + + end +end +end + +%% BC matrix solutions +bc_mats = zeros(Nx,Ny,6,6); +strain_bc_mats_inv = zeros(Nx,Ny,6,6); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Because we divide by K^2 to make matrices better + K = sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ); + bc_mat = zeros(6,6); + % [ d1 * eigenvec(1,1) + d2 * eigenvec(1,2) + + % d1 * eigenvec(2,1) + d2 * eigenvec(2,2) + + % d1 * eigenvec(3,1) + d2 * eigenvec(3,2) + + % d1 * eigenvec(4,1) + d2 * eigenvec(4,2) + + for m = 1 : 6 % the eigenvalue -> column of eigenvec_mat ~ eigenvector + for k_ind = 1 : 3 % eigenvector a, scale by K + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_sub*1i*K); + end + % rescale by K^-1 to avoid conditioning errors... need to rescale + % the given value as well! + for k_ind = 4 : 6 % eigenvector b + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_film*1i*K) * 1i * K / K^2; + end + end + bc_mats(k1_ind,k2_ind,:,:) = bc_mat; + strain_bc_mats_inv(k1_ind,k2_ind,:,:) = inv(bc_mat); + end +end +end + +strain_bc_mat_inv_korigin = inv([ h_sub 1 0 0 0 0 ; ... + 0 0 h_sub 1 0 0 ; ... + 0 0 0 0 h_sub 1 ; ... + C_FilmRef(1,3,1,3) 0 C_FilmRef(1,3,2,3) 0 C_FilmRef(1,3,3,3) 0 ; ... + C_FilmRef(2,3,1,3) 0 C_FilmRef(2,3,2,3) 0 C_FilmRef(2,3,3,3) 0 ; ... + C_FilmRef(3,3,1,3) 0 C_FilmRef(3,3,2,3) 0 C_FilmRef(3,3,3,3) 0 ]); +strain_bc_mat_inv_korigin = double(strain_bc_mat_inv_korigin);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/finite_diff_x3_second_der.m",".m","528","16","function out = finite_diff_x3_second_der( mat, dz ) + + [~,~,Nz] = size(mat); + out = mat; + + for i = 2 : Nz - 1 + out(:,:,i) = (1/dz^2) * (mat(:,:,i+1) - 2*mat(:,:,i) + mat(:,:,i-1)); + end + + out(:,:,1) = (mat(:,:,2) - mat(:,:,1)) / dz; % approx d/dx3 ~ forward difference + out(:,:,1) = (out(:,:,2) - out(:,:,1)) / dz; % approx d^2/dx3^2 ~ using another forward difference + + out(:,:,end) = (mat(:,:,end) - mat(:,:,end-1)) / dz; + out(:,:,end) = (out(:,:,end) - out(:,:,end-1)) / dz; + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/TransformElasticTensor.m",".m","509","24","% Transform +C_FilmRef = zeros(3,3,3,3); + +for i_ind = 1 : 3 +for j_ind = 1 : 3 +for k_ind = 1 : 3 +for l_ind = 1 : 3 + + for m_ind = 1 : 3 + for n_ind = 1 : 3 + for o_ind = 1 : 3 + for p_ind = 1 : 3 + + C_FilmRef(i_ind,j_ind,k_ind,l_ind) = Transform_Matrix(i_ind,m_ind) * Transform_Matrix(j_ind,n_ind) * Transform_Matrix(k_ind,o_ind) * Transform_Matrix(l_ind,p_ind) * C_CrystalRef(m_ind,n_ind,o_ind,p_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind); + + end + end + end + end + +end +end +end +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Visualize.m",".m","1105","25","% subplot(2,3,1); +% surf(z_axis,y_axis,squeeze(P3(:,16,:))); shading interp; view(0,90); axis([min(z_axis) max(z_axis) min(y_axis) max(y_axis)]); colormap parula; +% xlabel('Y (m)'); ylabel('Z (m)'); colorbar +% freezeColors + +subplot(2,2,1); +surf(x_axis*1e9,y_axis*1e9,P3_FilmRef(:,:,film_index)); shading interp; view(0,90); +axis([min(x_axis)*1e9 max(x_axis)*1e9 min(y_axis)*1e9 max(y_axis)*1e9]); colormap parula; +% xlabel('X (m)'); ylabel('Y (m)'); +freezeColors + +subplot(2,2,2); +angle = atan2(P2_FilmRef,P1_FilmRef); surf(x_axis*1e9,y_axis*1e9,angle(:,:,film_index)); view(0,90); colormap hsv; shading interp; +axis([min(x_axis)*1e9 max(x_axis)*1e9 min(y_axis)*1e9 max(y_axis)*1e9]); +caxis([-pi pi]); +% xlabel('X (m)'); ylabel('Y (m)'); +freezeColors + +subplot(2,2,3); +semilogy(errors(1:c)); + +subplot(2,2,4); +% Visualize_3D(P1_FilmRef,P2_FilmRef,P3_FilmRef,x_grid*1e9,y_grid*1e9,z_grid*1e9,interface_index,film_index,Nx,Ny,Nz) +surf(z_axis*1e9,y_axis*1e9,squeeze(P1_FilmRef(:,1,:))); colormap parula; shading interp; view(0,90); +axis([min(z_axis)*1e9 max(z_axis)*1e9 min(y_axis)*1e9 max(y_axis)*1e9]); ","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Setup_BFO_2.m",".m","3106","103","% Run inputs +LOAD = 1; % 1 = Load initial conditions from file called init.mat, 0 = random P initial conditions +E_1_applied_FilmRef = 0; E_2_applied_FilmRef = 0; E_3_applied_FilmRef = 0; % in V/m, 1e5 V/m = 1 kV/cm +T = 27; % in C +Us_11 = 0; % unitless misfit strain +Us_22 = Us_11; % anisotropic misfit strain +STRING = 'BFO small Q44'; % Material Name +VPA_ELECTRIC_ON = 1; % numerical errors when doing electric energy, so we need to use vpa +VPA_ELASTIC_ON = 0; + +%% ---- Nothing needed to modify below ---- %% +% BFO Constants http://www.mmm.psu.edu/JXZhang2008_JAP_Computersimulation.pdf + +%% Convergence +epsilon = 1e-10; % convergence criterion +saves = [0 : 500 : 100000]; % save after this many iterations + +%% Grid Size +Nx = 32; Ny = Nx; Nz = 32; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 28; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 1 && ELASTIC; % automatically 0 if no elastic energy +% no heterogenous elastic relaxation if no elastic energy + +ELECTRIC = 1; +SURFACE_DEPOL = 0; % depolarization energy due to uncompensated surface charges + +NUCLEATE = 0; % nucleation sites, places that don't change during temporal evolution, 1 -> during hysteresis calcs + +ThermConst = 0; % No thermal energy + +%% Elastic Tensor +Poisson_Ratio = 0.35; +Shear_Mod = 0.69 * 1e11; + +C11 = 2 * Shear_Mod * ( 1 - Poisson_Ratio ) / ( 1 - 2 * Poisson_Ratio ); +C12 = 2 * Shear_Mod * Poisson_Ratio / ( 1 - 2 * Poisson_Ratio ); +C44 = Shear_Mod; + +C12 = 1.62 * 1e11; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + + +%% Electrostriction +Q11 = 0.032; % Q1111 = Q11 +Q12 = -0.016; % Q1122 = Q12 +Q44 = 0.01 * 2; % 2 * Q1212 = Q44 + +q11 = C11 * Q11 + 2 * C12 * Q12; +q12 = C11 * Q12 + C12 * ( Q11 + Q12 ); +q44 = 2 * C44 * Q44; + +%% LGD Constants, stress free BTO +a1_T = @(T) 4.9 * ((T+273)-1103) * 1e5; % T in C +a1 = a1_T(T); +a11 = 5.42 * 1e8; +a12 = 1.54 * 1e8; +a111 = 0; +a112 = 0; +a123 = 0; +a1111 = 0; +a1112 = 0; +a1122 = 0; +a1123 = 0; + +%% Simulation Size +l_0 = 0.5e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = l_0*(Nz-1); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = l_0^2 * a0; +G11 = 0.6 * G110; + +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = G11; % H44 = G44 + G44' + +%% Run time setup +t_0 = 1/a0; +dt = 0.0125/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% Electrical +k_electric_11 = 500; k_electric_22 = k_electric_11; k_electric_33 = k_electric_11;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/InitP.m",".m","492","14","% Initial Conditions +if( LOAD ) + load('init.mat','P1_FilmRef','P2_FilmRef','P3_FilmRef'); +else + RandomP; +end + +% Thin film simulation +P1_FilmRef(:,:,1:sub_index) = 0; P2_FilmRef(:,:,1:sub_index) = 0; P3_FilmRef(:,:,1:sub_index) = 0; +P1_FilmRef(:,:,film_index+1:end) = 0; P2_FilmRef(:,:,film_index+1:end) = 0; P3_FilmRef(:,:,film_index+1:end) = 0; + +P1_FilmRef_2Dk = fft_2d_slices( P1_FilmRef ); +P2_FilmRef_2Dk = fft_2d_slices( P2_FilmRef ); +P3_FilmRef_2Dk = fft_2d_slices( P3_FilmRef );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/fft_2d_slices.m",".m","160","12","function out = fft_2d_slices( mat ) + + out = mat; + [~, ~, z] = size(mat); + + for i = 1 : z + + out(:,:,i) = fft2(squeeze(mat(:,:,i))); + + end + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Setup.m",".m","3662","112","% Run inputs +rng(100) +LOAD = 0; % 1 = Load initial conditions from file called init.mat, 0 = random P initial conditions +E_1_applied_FilmRef = 0; E_2_applied_FilmRef = 0; E_3_applied_FilmRef = 0; % in V/m, 1e5 V/m = 1 kV/cm +Temperature = 27; % in C +Us_11 = -0.5*1e-2; % unitless misfit strain +Us_22 = Us_11; % anisotropic misfit strain +Us_12 = 0; +STRING = 'BFO_6'; % Material Name +PATH = './BFO_6/'; +VPA_ELECTRIC_ON = 1; % numerical errors when doing electric energy, so we need to use vpa +VPA_ELASTIC_ON = 0; +dt_factor = 0.01; + +%% ---- Nothing needed to modify below ---- %% +% BFO Constants http://www.mmm.psu.edu/JXZhang2008_JAP_Computersimulation.pdf + +%% Convergence +epsilon = 1e-5; % convergence criterion +saves = [0 : 1000 : 100000]; % save after this many iterations + +%% Grid Size +Nx = 32; Ny = Nx; Nz = 32; % Grid Points +sub_index = 16; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 31; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 1 && ELASTIC; % automatically 0 if no elastic energy +% no heterogenous elastic relaxation if no elastic energy + +ELECTRIC = 1; +SURFACE_DEPOL = 0; % depolarization energy due to uncompensated surface charges + +NUCLEATE = 0; % nucleation sites, places that don't change during temporal evolution, 1 -> during hysteresis calcs + +ThermConst = 0; % No thermal energy + +%% Elastic Tensor +Poisson_Ratio = 0.35; +Shear_Mod = 0.69 * 1e11; + +C11 = 2 * Shear_Mod * ( 1 - Poisson_Ratio ) / ( 1 - 2 * Poisson_Ratio ); +C12 = 2 * Shear_Mod * Poisson_Ratio / ( 1 - 2 * Poisson_Ratio ); +C44 = Shear_Mod; + +C12 = 1.62 * 1e11; + +C_CrystalRef = zeros(3,3,3,3); +C_CrystalRef(1,1,1,1) = C11; C_CrystalRef(2,2,2,2) = C11; C_CrystalRef(3,3,3,3) = C11; +C_CrystalRef(1,1,2,2) = C12; C_CrystalRef(1,1,3,3) = C12; C_CrystalRef(2,2,1,1) = C12; +C_CrystalRef(2,2,3,3) = C12; C_CrystalRef(3,3,1,1) = C12; C_CrystalRef(3,3,2,2) = C12; +C_CrystalRef(1,2,1,2) = C44; C_CrystalRef(2,1,2,1) = C44; C_CrystalRef(1,3,1,3) = C44; +C_CrystalRef(3,1,3,1) = C44; C_CrystalRef(2,3,2,3) = C44; C_CrystalRef(3,2,3,2) = C44; +C_CrystalRef(1,2,2,1) = C44; C_CrystalRef(2,1,1,2) = C44; C_CrystalRef(1,3,3,1) = C44; +C_CrystalRef(3,1,1,3) = C44; C_CrystalRef(2,3,3,2) = C44; C_CrystalRef(3,2,2,3) = C44; + + +%% Electrostriction +Q11 = 0.032; % Q1111 = Q11 +Q12 = -0.016; % Q1122 = Q12 +Q44 = 0.01 * 2; % 2 * Q1212 = Q44 + +q11 = C11 * Q11 + 2 * C12 * Q12; +q12 = C11 * Q12 + C12 * ( Q11 + Q12 ); +q44 = 2 * C44 * Q44; + +%% LGD Constants, stress free BTO +a1_T = @(T) 4.9 * ((T+273)-1103) * 1e5; % T in C +a1 = a1_T(Temperature); +a11 = 5.42 * 1e8; +a12 = 1.54 * 1e8; +a111 = 0; +a112 = 0; +a123 = 0; +a1111 = 0; +a1112 = 0; +a1122 = 0; +a1123 = 0; + +%% Simulation Size +l_0 = 0.5e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = l_0*(Nz-1); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = l_0^2 * a0; +G11 = 0.6 * G110; + +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = G11; % H44 = G44 + G44' + +%% Run time setup +t_0 = 1/a0; +dt = dt_factor/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% Electrical +k_electric_11 = 100; k_electric_22 = k_electric_11; k_electric_33 = k_electric_11; + +%% Transformation from crystal to global +Transform_Matrix = [ 0 1 0; ... + -1/sqrt(2) 0 1/sqrt(2); ... + 1/sqrt(2) 0 1/sqrt(2) ];","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/Render3D_FilmRef.m",".m","115","1","Visualize_3D(P1_FilmRef,P2_FilmRef,P3_FilmRef,x_grid*1e9,y_grid*1e9,z_grid*1e9,interface_index,film_index,Nx,Ny,Nz)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/ExternalEFieldEnergy.m",".m","330","8","%% External field +f1_ext_E = -E_1_applied_FilmRef .* in_film .* Nucleation_Sites; +f2_ext_E = -E_2_applied_FilmRef .* in_film .* Nucleation_Sites; +f3_ext_E = -E_3_applied_FilmRef .* in_film .* Nucleation_Sites; + +f1_ext_E_2Dk = fft_2d_slices(f1_ext_E); +f2_ext_E_2Dk = fft_2d_slices(f2_ext_E); +f3_ext_E_2Dk = fft_2d_slices(f3_ext_E);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/CalcP_FilmRef.m",".m","327","10","% Calculate P within the film +P1_film = P1_FilmRef(:,:,interface_index:film_index); +P2_film = P2_FilmRef(:,:,interface_index:film_index); +P3_film = P3_FilmRef(:,:,interface_index:film_index); + +P1_val = vol_avg(abs(P1_film)) +P2_val = vol_avg(abs(P2_film)) +P3_val = vol_avg(abs(P3_film)) + +P_val = sqrt(P1_val^2+P2_val^2+P3_val^2)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/ifft_2d_slices.m",".m","168","12","function out = ifft_2d_slices( mat ) + + out = mat; + [~, ~, z] = size(mat); + + for i = 1 : z + + out(:,:,i) = real(ifft2(squeeze(mat(:,:,i)))); + + end + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/InfinitePlate.m",".m","5565","131","%% Application of Boundary Conditions +% bc in real space + +% 3D fft diff.. +bc_film_1_3Dk = C44.*(Eigenstrain_FilmRef_13_k - kx_grid_3D.*u_3_A_k.*1i) + C44.*(Eigenstrain_FilmRef_13_k - kz_grid_3D.*u_1_A_k.*1i); +bc_film_2_3Dk = (C11/2 - C12/2).*(Eigenstrain_FilmRef_23_k - ky_grid_3D.*u_3_A_k.*1i) + (C11/2 - C12/2).*(Eigenstrain_FilmRef_23_k - kz_grid_3D.*u_2_A_k.*1i); +bc_film_3_3Dk = (Eigenstrain_FilmRef_33_k - kz_grid_3D.*u_3_A_k.*1i).*(C11/2 + C12/2 + C44) + C12.*(Eigenstrain_FilmRef_11_k - kx_grid_3D.*u_1_A_k.*1i) + (Eigenstrain_FilmRef_22_k - ky_grid_3D.*u_2_A_k.*1i).*(C11/2 + C12/2 - C44); + +% real space bc +% bc applied on the top surface in real space +bc_film_1 = real(ifftn(squeeze(bc_film_1_3Dk))); +bc_film_2 = real(ifftn(squeeze(bc_film_2_3Dk))); +bc_film_3 = real(ifftn(squeeze(bc_film_3_3Dk))); + +bc_film_1 = squeeze(bc_film_1(:,:,film_index)); +bc_film_2 = squeeze(bc_film_2(:,:,film_index)); +bc_film_3 = squeeze(bc_film_3(:,:,film_index)); + +% Strain free substrate +bc_sub_1 = -squeeze(u_1_A(:,:,1)); +bc_sub_2 = -squeeze(u_2_A(:,:,1)); +bc_sub_3 = -squeeze(u_3_A(:,:,1)); + +%% fft2 the bc +bc_film_1_2Dk = fft2(bc_film_1); +bc_film_2_2Dk = fft2(bc_film_2); +bc_film_3_2Dk = fft2(bc_film_3); + +% Orders of magnitude larger... so let's make the matrix better to work with +rescaling_mat = sqrt( kx_grid_2D.^2 + ky_grid_2D.^2 ).^2; +rescaling_mat(1,1) = 1; +bc_film_1_2Dk = bc_film_1_2Dk ./ rescaling_mat; +bc_film_2_2Dk = bc_film_2_2Dk ./ rescaling_mat; +bc_film_3_2Dk = bc_film_3_2Dk ./ rescaling_mat; + +bc_sub_1_2Dk = fft2(bc_sub_1); +bc_sub_2_2Dk = fft2(bc_sub_2); +bc_sub_3_2Dk = fft2(bc_sub_3); + +bc_given_k_space = cat(4,bc_sub_1_2Dk,bc_sub_2_2Dk,bc_sub_3_2Dk,bc_film_1_2Dk,bc_film_2_2Dk,bc_film_3_2Dk); +d_sols = zeros(numel(kx),numel(ky),6); + +%% Apply the boundary conditions to get the solution to the diff. eq. +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + % Solve the matrix problem + d_sols(k1_ind,k2_ind,:) = squeeze(strain_bc_mats_inv(k1_ind,k2_ind,:,:)) * squeeze(bc_given_k_space(k1_ind,k2_ind,:)); +end +end + +%% Construct the solution in the 2D k-space, kx,ky,z +u_B_2Dk_mat = zeros(Nx,Ny,Nz,3); +u_B_2Dk_d3_mat = zeros(Nx,Ny,Nz,3); + +q_1 = squeeze(d_sols(:,:,1)); +q_2 = squeeze(d_sols(:,:,2)); +q_3 = squeeze(d_sols(:,:,3)); +q_4 = squeeze(d_sols(:,:,4)); +q_5 = squeeze(d_sols(:,:,5)); +q_6 = squeeze(d_sols(:,:,6)); + +p_1 = squeeze(eigenval_mat(:,:,1)); +p_2 = squeeze(eigenval_mat(:,:,2)); +p_3 = squeeze(eigenval_mat(:,:,3)); +p_4 = squeeze(eigenval_mat(:,:,4)); +p_5 = squeeze(eigenval_mat(:,:,5)); +p_6 = squeeze(eigenval_mat(:,:,6)); + +for l_ind = 1 : 3 + for z_loop = 1 : numel(z_axis); + K = sqrt( kx_grid_2D.^2 + ky_grid_2D.^2 ); + + a_vec_1 = squeeze(eigenvec_mat(:,:,l_ind,1)); + a_vec_2 = squeeze(eigenvec_mat(:,:,l_ind,2)); + a_vec_3 = squeeze(eigenvec_mat(:,:,l_ind,3)); + a_vec_4 = squeeze(eigenvec_mat(:,:,l_ind,4)); + a_vec_5 = squeeze(eigenvec_mat(:,:,l_ind,5)); + a_vec_6 = squeeze(eigenvec_mat(:,:,l_ind,6)); + + u_B_2Dk_mat(:,:,z_loop,l_ind) = q_1 .* a_vec_1 .* exp(p_1.*z_axis(z_loop).*1i.*K) + ... + q_2 .* a_vec_2 .* exp(p_2.*z_axis(z_loop).*1i.*K) + ... + q_3 .* a_vec_3 .* exp(p_3.*z_axis(z_loop).*1i.*K) + ... + q_4 .* a_vec_4 .* exp(p_4.*z_axis(z_loop).*1i.*K) + ... + q_5 .* a_vec_5 .* exp(p_5.*z_axis(z_loop).*1i.*K) + ... + q_6 .* a_vec_6 .* exp(p_6.*z_axis(z_loop).*1i.*K); + u_B_2Dk_d3_mat(:,:,z_loop,l_ind) = ( q_1 .* a_vec_1 .* exp(p_1.*z_axis(z_loop).*1i.*K) .* p_1 + ... + q_2 .* a_vec_2 .* exp(p_2.*z_axis(z_loop).*1i.*K) .* p_2 + ... + q_3 .* a_vec_3 .* exp(p_3.*z_axis(z_loop).*1i.*K) .* p_3 + ... + q_4 .* a_vec_4 .* exp(p_4.*z_axis(z_loop).*1i.*K) .* p_4 + ... + q_5 .* a_vec_5 .* exp(p_5.*z_axis(z_loop).*1i.*K) .* p_5 + ... + q_6 .* a_vec_6 .* exp(p_6.*z_axis(z_loop).*1i.*K) .* p_6 ) .* 1i .* K; + end +end + +% 2D origin point... +d_sols(1,1,:) = strain_bc_mat_inv_korigin * squeeze(bc_given_k_space(1,1,:)); + +q = squeeze(d_sols(1,1,:)); +u_B_2Dk_mat(1,1,:,1) = q(1) * z_axis + q(2); +u_B_2Dk_mat(1,1,:,2) = q(3) * z_axis + q(4); +u_B_2Dk_mat(1,1,:,3) = q(5) * z_axis + q(6); +u_B_2Dk_d3_mat(1,1,:,1) = q(1); +u_B_2Dk_d3_mat(1,1,:,2) = q(3); +u_B_2Dk_d3_mat(1,1,:,3) = q(5); + +u_1_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,1)); +u_2_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,2)); +u_3_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,3)); +u_1_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,1)); +u_2_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,2)); +u_3_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,3)); + +%% Calculate the strains, e_ij = 0.5 * (u_i,j + u_j,i) +e_11_B_2Dk = u_1_B_2Dk .* 1i .* kx_grid_3D; +e_22_B_2Dk = u_2_B_2Dk .* 1i .* ky_grid_3D; +e_33_B_2Dk = u_3_B_2Dk_d3; +e_23_B_2Dk = 0.5 * (u_2_B_2Dk_d3 + 1i .* ky_grid_3D .* u_3_B_2Dk); +e_13_B_2Dk = 0.5 * (u_1_B_2Dk_d3 + 1i .* kx_grid_3D .* u_3_B_2Dk); +e_12_B_2Dk = 0.5 * (1i .* ky_grid_3D .* u_1_B_2Dk + 1i .* kx_grid_3D .* u_2_B_2Dk); + +%% Final outputs +u_1_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,1))); +u_2_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,2))); +u_3_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,3))); + +e_11_B = ifft_2d_slices(e_11_B_2Dk); +e_22_B = ifft_2d_slices(e_22_B_2Dk); +e_33_B = ifft_2d_slices(e_33_B_2Dk); +e_23_B = ifft_2d_slices(e_23_B_2Dk); +e_13_B = ifft_2d_slices(e_13_B_2Dk); +e_12_B = ifft_2d_slices(e_12_B_2Dk);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/NonRandomInit.m",".m","1031","27","%% +RandomP; + +% Remember changing first variable is y axis!! +% P(y,x,z); + +P1_FilmRef(1:12,:,:) = P1_FilmRef(1:12,:,:) - 0.003; +P2_FilmRef(1:12,:,:) = P2_FilmRef(1:12,:,:) - 0.003; +P3_FilmRef(1:12,:,:) = P3_FilmRef(1:12,:,:) - 0.003; + +P1_FilmRef(13:24,:,:) = P1_FilmRef(13:24,:,:) + 0.0015; +P2_FilmRef(13:24,:,:) = P2_FilmRef(13:24,:,:) - 0.003; +P3_FilmRef(13:24,:,:) = P3_FilmRef(13:24,:,:) - 0.003; +P1_FilmRef(13:24,:,end-20:end) = P1_FilmRef(13:24,:,end-20:end) + 0.0015; +P1_FilmRef(13:24,:,end-15:end) = P1_FilmRef(13:24,:,end-15:end) + 0.0015; +P1_FilmRef(13:24,:,end-10:end) = P1_FilmRef(13:24,:,end-10:end) + 0.0015; +P1_FilmRef(13:24,:,end-5:end) = P1_FilmRef(13:24,:,end-5:end) + 0.0015; + +P1_FilmRef(25:end,:,:) = P1_FilmRef(25:end,:,:) - 0.003; +P2_FilmRef(25:end,:,:) = P2_FilmRef(25:end,:,:) - 0.003; +P3_FilmRef(25:end,:,:) = P3_FilmRef(25:end,:,:) - 0.003; + +P1_FilmRef = P1_FilmRef .* in_film; +P2_FilmRef = P2_FilmRef .* in_film; +P3_FilmRef = P3_FilmRef .* in_film; + +save('init.mat','P1_FilmRef','P2_FilmRef','P3_FilmRef');","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/DomainPctCalc.m",".m","3650","74","%% For P1_CrystalRef ~ P2 ~ P3 within the domain +% Polar Angle +R = sqrt( P1_CrystalRef.^2 + P2_CrystalRef.^2 + P3_CrystalRef.^2 ); +Theta = acos( P3_CrystalRef ./ R ); % -> [0,pi] +Phi = atan2( P2_CrystalRef, P1_CrystalRef ); % -> [-pi,pi] + +threshold_P1_CrystalRef = 5e-2; % P1_CrystalRef ~ 0 +threshold_P2_CrystalRef = 5e-2; % P2_CrystalRef ~ 0 +threshold_P3_CrystalRef = 5e-2; % P3_CrystalRef ~ 0 + +total_el = sum(sum(sum( P1_CrystalRef ~= 0))); + +%% Tetragonal +a1 = ( abs(P1_CrystalRef) > threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) < threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) < threshold_P3_CrystalRef ); +a2 = ( abs(P1_CrystalRef) < threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) > threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) < threshold_P3_CrystalRef ); +c = ( abs(P1_CrystalRef) < threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) < threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) > threshold_P3_CrystalRef ); + + +%% Orthorhombic +O12 = ( abs(P1_CrystalRef) > threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) > threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) < threshold_P3_CrystalRef ); +O13 = ( abs(P1_CrystalRef) > threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) < threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) > threshold_P3_CrystalRef ); +O23 = ( abs(P1_CrystalRef) < threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) > threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) > threshold_P3_CrystalRef ); + + +%% Rhombohedral +r = ( abs(P1_CrystalRef) > threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) > threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) > threshold_P3_CrystalRef ); + +%% Calc +a1_calc = sum(sum(sum(a1))) /total_el; +a2_calc = sum(sum(sum(a2))) /total_el; +c_calc = sum(sum(sum(c))) / total_el; + +O12_calc = sum(sum(sum(O12))) / total_el; +O13_calc = sum(sum(sum(O13))) / total_el; +O23_calc = sum(sum(sum(O23))) / total_el; + +r_calc = sum(sum(sum(r))) / total_el; + +Names = {'a1','a2','c','O12','O13','O23','r'} +Pcts = [a1_calc,a2_calc,c_calc,O12_calc,O13_calc,O23_calc,r_calc] +Avg_val = [ mean(mean(mean(abs(P1_CrystalRef)))); mean(mean(mean(abs(P2_CrystalRef)))); mean(mean(mean(abs(P3_CrystalRef))))]' + + + +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Trash +% %% Tetragonal +% % a1/a2 domain, Theta ~pi/2 ; Phi ~ 0, pi/2, pi, -pi, -pi/2 +% a1_a2 = ( abs(Theta - (pi/2)) < threshold_angle ) & ... +% ( abs(abs(Phi) - pi) < threshold_angle | abs(abs(Phi) - (pi/2)) < threshold_angle ) ; +% +% % c domain, Theta ~0,pi ; Phi ~0 +% c = ( Theta < threshold_angle | abs(Theta - pi) < threshold_angle ) & ... +% ( abs(P1_CrystalRef) < threshold_mag & abs(P2_CrystalRef) < threshold_mag ); +% +% %% Orthorhombic +% % aa1/aa2 domain, Theta ~pi/2, Phi ~ pi/4, 3*pi/4, -pi/4, -3*pi/4 +% aa1_aa2 = ( abs(Theta - (pi/2)) < threshold_angle ) & ... +% ( abs(abs(Phi) - (pi/4)) < threshold_angle | abs(abs(Phi) - (3*pi/4)) < threshold_angle ) ; +% +% % P1_CrystalRef ~ P3_CrystalRef, P2_CrystalRef ~ 0 +% % Theta ~ pi/4, 3pi/4 ; Phi ~ 0, pi +% a1_c = ( abs(Theta - (pi/4)) < threshold_angle | abs(Theta - (3*pi/4)) < threshold_angle ) & ... +% ( abs(Phi) < threshold_angle | abs(abs(Phi) - pi) < threshold_angle ); +% +% % P1_CrystalRef ~ 0, P2_CrystalRef ~ P3_CrystalRef +% % Theta ~ pi/4, 3pi/4 ; Phi ~ pi/2, 3pi/2 +% a2_c = ( abs(Theta - (pi/4)) < threshold_angle | abs(Theta - (3*pi/4)) < threshold_angle ) & ... +% ( abs(abs(Phi) - (pi/2)) < threshold_angle | abs(abs(Phi) - (3*pi/2)) < threshold_angle ); +% +% +% %% Rhombohedral +% r = ( abs(Theta - (pi/6)) < threshold_angle | abs(Theta - (5*pi/6)) < threshold_angle ) & ... +% ( abs(abs(Phi) - (pi/4)) < threshold_angle | abs(abs(Phi) - (3*pi/4)) + threshold_angle );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(110)/finite_diff_x3_first_der.m",".m","389","14","function out = finite_diff_x3_first_der( mat, dz ) + + [~,~,Nz] = size(mat); + out = mat; + + for i = 2 : Nz - 1 + out(:,:,i) = (1/dz) * ( (-1/2) * mat(:,:,i-1) + (1/2) * mat(:,:,i+1) ); + end + + % approximate endpoints using forward difference + out(:,:,1) = ( mat(:,:,2) - mat(:,:,1) ) / dz; + out(:,:,end) = ( mat(:,:,end) - mat(:,:,end-1) ) / dz; + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","README/analytical_derivations.m",".m","19735","792","%% Calculate displacement field +C = sym(zeros(3,3,3,3)); + +C(1,1,1,1) = sym('C11'); C(2,2,2,2) = sym('C11'); C(3,3,3,3) = sym('C11'); +C(1,1,2,2) = sym('C12'); C(1,1,3,3) = sym('C12'); C(2,2,1,1) = sym('C12'); +C(2,2,3,3) = sym('C12'); C(3,3,1,1) = sym('C12'); C(3,3,2,2) = sym('C12'); +C(1,2,1,2) = sym('C44'); C(2,1,2,1) = sym('C44'); C(1,3,1,3) = sym('C44'); +C(3,1,3,1) = sym('C44'); C(2,3,2,3) = sym('C44'); C(3,2,3,2) = sym('C44'); +C(1,2,2,1) = sym('C44'); C(2,1,1,2) = sym('C44'); C(1,3,3,1) = sym('C44'); +C(3,1,1,3) = sym('C44'); C(2,3,3,2) = sym('C44'); C(3,2,2,3) = sym('C44'); + +e = sym(zeros(3,3)); +e(1,1) = sym( 'e_11' ); +e(2,2) = sym( 'e_22' ); +e(3,3) = sym( 'e_33' ); +e(2,3) = sym( 'e_23' ); +e(1,3) = sym( 'e_13' ); +e(1,2) = sym( 'e_12' ); +e(3,2) = e(2,3); +e(3,1) = e(1,3); +e(2,1) = e(1,2); + + +s = sym(zeros(3,3)); +for i = 1 : 3 +for j = 1 : 3 + for k = 1 : 3 + for l = 1 : 3 + s(i,j) = s(i,j) + C(i,j,k,l) * e(k,l); + end + end +end +end + +%% +%% Calculate displacement field +C = sym(zeros(3,3,3,3)); + +for i = 1 : 3 +for j = 1 : 3 +for k = 1 : 3 +for l = 1 : 3 + C(i,j,k,l) = sprintf('C(%d,%d,%d,%d)', i, j, k, l); +end +end +end +end + +e = sym(zeros(3,3)); +e(1,1) = sym( 'ElasticStrain_11' ); +e(2,2) = sym( 'ElasticStrain_22' ); +e(3,3) = sym( 'ElasticStrain_33' ); +e(2,3) = sym( 'ElasticStrain_23' ); +e(1,3) = sym( 'ElasticStrain_13' ); +e(1,2) = sym( 'ElasticStrain_12' ); +e(3,2) = e(2,3); +e(3,1) = e(1,3); +e(2,1) = e(1,2); + +s = sym(zeros(3,3)); +for i = 1 : 3 +for j = 1 : 3 + for k = 1 : 3 + for l = 1 : 3 + s(i,j) = s(i,j) + C(i,j,k,l) * e(k,l); + end + end +end +end + + +%% Elastic Energy +F_ela = 0; + +for i = 1 : 3 +for j = 1 : 3 +for k = 1 : 3 +for l = 1 : 3 + + F_ela = F_ela + 0.5 * C(i,j,k,l) * e(i,j) * e(k,l); + +end +end +end +end + +collect(F_ela,['C11','C12','C44']) + +%% + + +% Green's Tensor, k-space dependent Tensor (matrix) +Green = sym(zeros(3,3)); +Green(1,1) = sym('Green(k1,k2,k3,1,1)'); Green(1,2) = sym('Green(k1,k2,k3,1,2)'); Green(1,3) = sym('Green(k1,k2,k3,1,3)'); +Green(2,1) = sym('Green(k1,k2,k3,2,1)'); Green(2,2) = sym('Green(k1,k2,k3,2,2)'); Green(2,3) = sym('Green(k1,k2,k3,2,3)'); +Green(3,1) = sym('Green(k1,k2,k3,3,1)'); Green(3,2) = sym('Green(k1,k2,k3,3,2)'); Green(3,3) = sym('Green(k1,k2,k3,3,3)'); + +%% +% Eigenstrain +% Eigenstress_ijkl = C_ijkl * Eigestrain_ijkl +Eigenstrain = sym(zeros(3,3)); +Eigenstrain(1,1) = sym( 'Eigenstrain_11_k(k1,k2,k3)' ); +Eigenstrain(2,2) = sym( 'Eigenstrain_22_k(k1,k2,k3)' ); +Eigenstrain(3,3) = sym( 'Eigenstrain_33_k(k1,k2,k3)' ); +Eigenstrain(2,3) = sym( 'Eigenstrain_23_k(k1,k2,k3)' ); +Eigenstrain(1,3) = sym( 'Eigenstrain_13_k(k1,k2,k3)' ); +Eigenstrain(1,2) = sym( 'Eigenstrain_12_k(k1,k2,k3)' ); +Eigenstrain(3,2) = Eigenstrain(2,3); +Eigenstrain(3,1) = Eigenstrain(1,3); +Eigenstrain(2,1) = Eigenstrain(1,2); + + +% Fourier space vector +k_vec = sym(zeros(3,1)); k_vec(1) = sym('kx_grid(k1,k2,k3)'); k_vec(2) = sym('ky_grid(k1,k2,k3)'); k_vec(3) = sym('kz_grid(k1,k2,k3)'); +u_mat = sym(zeros(3,1)); +for i = 1 : 3 + for m = 1 : 3 + for j = 1 : 3 + for k = 1 : 3 + for l = 1 : 3 + + u_mat(i) = u_mat(i) + sym('-1i') * Green(i,j) * C(j,m,k,l) * Eigenstrain(k,l) * k_vec(m); + + end + end + end + end +end + + +%% Test if a solution +C = sym(zeros(3,3,3,3)); + +C(1,1,1,1) = sym('C11'); C(2,2,2,2) = sym('C11'); C(3,3,3,3) = sym('C11'); +C(1,1,2,2) = sym('C12'); C(1,1,3,3) = sym('C12'); C(2,2,1,1) = sym('C12'); +C(2,2,3,3) = sym('C12'); C(3,3,1,1) = sym('C12'); C(3,3,2,2) = sym('C12'); +C(1,2,1,2) = sym('C44'); C(2,1,2,1) = sym('C44'); C(1,3,1,3) = sym('C44'); +C(3,1,3,1) = sym('C44'); C(2,3,2,3) = sym('C44'); C(3,2,3,2) = sym('C44'); +C(1,2,2,1) = sym('C44'); C(2,1,1,2) = sym('C44'); C(1,3,3,1) = sym('C44'); +C(3,1,1,3) = sym('C44'); C(2,3,3,2) = sym('C44'); C(3,2,2,3) = sym('C44'); + +LHS = sym(zeros(3,1)); +RHS = sym(zeros(3,1)); + +% Eigenstrain +Eigenstrain_k_space = sym(zeros(3,3)); +Eigenstrain_k_space(1,1) = sym( 'Eigenstrain_11_k' ); +Eigenstrain_k_space(2,2) = sym( 'Eigenstrain_22_k' ); +Eigenstrain_k_space(3,3) = sym( 'Eigenstrain_33_k' ); +Eigenstrain_k_space(2,3) = sym( 'Eigenstrain_23_k' ); +Eigenstrain_k_space(1,3) = sym( 'Eigenstrain_13_k' ); +Eigenstrain_k_space(1,2) = sym( 'Eigenstrain_12_k' ); +Eigenstrain_k_space(3,2) = Eigenstrain_k_space(2,3); +Eigenstrain_k_space(3,1) = Eigenstrain_k_space(1,3); +Eigenstrain_k_space(2,1) = Eigenstrain_k_space(1,2); + +e_k_space = sym(zeros(3,3)); +e_k_space(1,1) = sym('e_11_k'); +e_k_space(2,2) = sym('e_22_k'); +e_k_space(3,3) = sym('e_33_k'); +e_k_space(1,2) = sym('e_12_k'); +e_k_space(1,3) = sym('e_13_k'); +e_k_space(2,3) = sym('e_23_k'); +e_k_space(3,2) = e_k_space(2,3); +e_k_space(3,1) = e_k_space(1,3); +e_k_space(2,1) = e_k_space(1,2); + +u_k_space = [ sym('u_1_k'); sym('u_2_k'); sym('u_3_k') ]; + +k_mat = [ sym('kx_grid'); sym('ky_grid'); sym('kz_grid') ]; + +for i = 1 : 3 + for j = 1 : 3 + for k = 1 : 3 + for l = 1 : 3 + + LHS(i) = LHS(i) + C(i,j,k,l) * u_k_space(k) * k_mat(j) * k_mat(l); + RHS(i) = RHS(i) + -1i * C(i,j,k,l) * Eigenstrain_k_space(k,l) * k_mat(j); + + end + end + end +end + +%% Eigenstrain calculate strain using Green's tensor +Eigenstrain_k_space = sym(zeros(3,3)); +Eigenstrain_k_space(1,1) = sym( 'Eigenstrain_11_k(k1,k2,k3)' ); +Eigenstrain_k_space(2,2) = sym( 'Eigenstrain_22_k(k1,k2,k3)' ); +Eigenstrain_k_space(3,3) = sym( 'Eigenstrain_33_k(k1,k2,k3)' ); +Eigenstrain_k_space(2,3) = sym( 'Eigenstrain_23_k(k1,k2,k3)' ); +Eigenstrain_k_space(1,3) = sym( 'Eigenstrain_13_k(k1,k2,k3)' ); +Eigenstrain_k_space(1,2) = sym( 'Eigenstrain_12_k(k1,k2,k3)' ); +Eigenstrain_k_space(3,2) = Eigenstrain_k_space(2,3); +Eigenstrain_k_space(3,1) = Eigenstrain_k_space(1,3); +Eigenstrain_k_space(2,1) = Eigenstrain_k_space(1,2); + +e_ij_k = sym(zeros(3,3)); +k_vec = sym(zeros(3,1)); k_vec(1) = sym('kx_grid_3D(k1,k2,k3)'); k_vec(2) = sym('ky_grid_3D(k1,k2,k3)'); k_vec(3) = sym('kz_grid_3D(k1,k2,k3)'); + +for i = 1 : 3 +for j = 1 : 3 + for n = 1 : 3 + for m = 1 : 3 + for k = 1 : 3 + for l = 1 : 3 + + e_ij_k(i,j) = e_ij_k(i,j) + 0.5 * (k_vec(j) * Green(i,n) + k_vec(i) * Green(j,n)) * k_vec(m) * C(n,m,k,l) * Eigenstrain_k_space(k,l); + + end + end + end + end +end +end + +%% Strain using eigenstress +e_ij_k = sym(zeros(3,3)); +k_vec = sym(zeros(3,1)); k_vec(1) = sym('kx_grid_3D(k1,k2,k3)'); k_vec(2) = sym('ky_grid_3D(k1,k2,k3)'); k_vec(3) = sym('kz_grid_3D(k1,k2,k3)'); + +Eigenstress_k_space = sym(zeros(3,3)); +Eigenstress_k_space(1,1) = sym( 'Eigenstress_11_k(k1,k2,k3)' ); +Eigenstress_k_space(2,2) = sym( 'Eigenstress_22_k(k1,k2,k3)' ); +Eigenstress_k_space(3,3) = sym( 'Eigenstress_33_k(k1,k2,k3)' ); +Eigenstress_k_space(2,3) = sym( 'Eigenstress_23_k(k1,k2,k3)' ); +Eigenstress_k_space(1,3) = sym( 'Eigenstress_13_k(k1,k2,k3)' ); +Eigenstress_k_space(1,2) = sym( 'Eigenstress_12_k(k1,k2,k3)' ); +Eigenstress_k_space(3,2) = Eigenstress_k_space(2,3); +Eigenstress_k_space(3,1) = Eigenstress_k_space(1,3); +Eigenstress_k_space(2,1) = Eigenstress_k_space(1,2); +for i = 1 : 3 +for j = 1 : 3 + for n = 1 : 3 + for m = 1 : 3 + + e_ij_k(i,j) = e_ij_k(i,j) + 0.5 * (k_vec(j) * Green(i,n) + k_vec(i) * Green(j,n)) * k_vec(m) * Eigenstress_k_space(n,m); + + end + end +end +end + + +%% Real space verification + +% C_ijkl*d^2u_k/dr_j*dr_l = C_ijkl*dEigen_kl/dr_j +% u_diff_mat(j,l,k) --> u_k,jl --> d^2u_k/dr_j*dr_l +u_diff_mat = sym(zeros(3,3,3)); +Eigenstrain_diff_mat = sym(zeros(3,3,3)); + +for k = 1 : 3 +for l = 1 : 3 +for j = 1 : 3 + + Eigenstrain_diff_mat(k,l,j) = sym(sprintf('Eigenstrain_%g%g_d%g',k,l,j)); + u_diff_mat(k,l,j) = sym(sprintf('u_%g_d%g_d%g',k,l,j)); + +end +end +end + +LHS = sym(zeros(3,1)); +RHS = sym(zeros(3,1)); + +for i = 1 : 3 + for k = 1 : 3 + for j = 1 : 3 + for l = 1 : 3 + + LHS(i) = LHS(i) + C(i,j,k,l) * u_diff_mat(k,l,j); + RHS(i) = RHS(i) + C(i,j,k,l) * Eigenstrain_diff_mat(k,l,j); + + end + end + end +end + + +ks = ['x', 'y', 'z']; + +for k = 1 : 3 +for l = 1 : 3 +for j = 1 : 3 + + fprintf('u_%g_d%g_d%g = real(ifftn(u_%g .* -1 .* k%c_grid_3D .* k%c_grid_3D));',k,l,j,k,ks(l),ks(j)); + fprintf('\n'); +end +end +end + +for k = 1 : 3 +for l = 1 : 3 +for j = 1 : 3 + + fprintf('Eigenstrain_%g%g_d%g = real(ifftn(Eigenstrain_%g%g .* 1i .* k%c_grid_3D));',k,l,j,k,l,ks(j)); + fprintf('\n'); +end +end +end +%% YuLuan Li 2d confirmation +LHS_term1 = sym(zeros(3,1)); +LHS_term2 = sym(zeros(3,1)); +LHS_term3 = sym(zeros(3,1)); +LHS = sym(zeros(3,1)); + +u_kspace_term1 = [sym('u_1_B_k'), sym('u_2_B_k'), sym('u_3_B_k')]; +u_kspace_term2 = [sym('u_1_B_k_d3'), sym('u_2_B_k_d3'), sym('u_3_B_k_d3')]; +u_kspace_term3 = [sym('u_1_B_k_d3_d3'), sym('u_2_B_k_d3_d3'), sym('u_3_B_k_d3_d3')]; + +k_2D = [sym('kx_grid_3D'),sym('ky_grid_3D')]; + +for i = 1 : 3 + + for k = 1 : 3 + for alpha = 1 : 2 + for beta = 1 : 2 + LHS_term1(i) = LHS_term1(i) + C(i,alpha,k,beta) * 1i * k_2D(alpha) * 1i * k_2D(beta) * u_kspace_term1(k); + end + end + end + + for k = 1 : 3 + for alpha = 1 : 2 + LHS_term2(i) = LHS_term2(i) + ( C(i,alpha,k,3) + C(i,3,k,alpha) ) * 1i * k_2D(alpha) * u_kspace_term2(k); + end + end + + for k = 1 : 3 + LHS_term3(i) = LHS_term3(i) + C(i,3,k,3) * u_kspace_term3(k); + end + +end + +for i = 1 : 3 + LHS(i) = LHS_term1(i) + LHS_term2(i) + LHS_term3(i); +end + + +%% Calculating hetero stress from hetero strain +% sigma_ij = C_ijkl * ( 1i * k_l * u_k - eigenstrain_kl ) +sigma2_ij = sym(zeros(3,3)); +u_k_space = [ sym('u_1_k'); sym('u_2_k'); sym('u_3_k') ]; +k_mat = [ sym('kx_grid'); sym('ky_grid'); sym('kz_grid') ]; + +for i = 1 : 3 +for j = 1 : 3 + + for k = 1 : 3 + for l = 1 : 3 + sigma2_ij(i,j) = sigma2_ij(i,j) + C(i,j,k,l) * ... + ( 0.5 * 1i * k_mat(l) * u_k_space(k) + 0.5 * 1i * k_mat(k) * u_k_space(l) - Eigenstrain_k_space(k,l)); + end + end + +end +end + +%% Calculating hetero stress from hetero strain +C = sym(zeros(3,3,3,3)); + +C(1,1,1,1) = sym('C11'); C(2,2,2,2) = sym('C11'); C(3,3,3,3) = sym('C11'); +C(1,1,2,2) = sym('C12'); C(1,1,3,3) = sym('C12'); C(2,2,1,1) = sym('C12'); +C(2,2,3,3) = sym('C12'); C(3,3,1,1) = sym('C12'); C(3,3,2,2) = sym('C12'); +C(1,2,1,2) = sym('C44'); C(2,1,2,1) = sym('C44'); C(1,3,1,3) = sym('C44'); +C(3,1,3,1) = sym('C44'); C(2,3,2,3) = sym('C44'); C(3,2,3,2) = sym('C44'); +C(1,2,2,1) = sym('C44'); C(2,1,1,2) = sym('C44'); C(1,3,3,1) = sym('C44'); +C(3,1,1,3) = sym('C44'); C(2,3,3,2) = sym('C44'); C(3,2,2,3) = sym('C44'); + +% Eigenstrain +Eigenstrain_k_space = sym(zeros(3,3)); +Eigenstrain_k_space(1,1) = sym( 'Eigenstrain_11_k' ); +Eigenstrain_k_space(2,2) = sym( 'Eigenstrain_22_k' ); +Eigenstrain_k_space(3,3) = sym( 'Eigenstrain_33_k' ); +Eigenstrain_k_space(2,3) = sym( 'Eigenstrain_23_k' ); +Eigenstrain_k_space(1,3) = sym( 'Eigenstrain_13_k' ); +Eigenstrain_k_space(1,2) = sym( 'Eigenstrain_12_k' ); +Eigenstrain_k_space(3,2) = Eigenstrain_k_space(2,3); +Eigenstrain_k_space(3,1) = Eigenstrain_k_space(1,3); +Eigenstrain_k_space(2,1) = Eigenstrain_k_space(1,2); + +% sigma_ij = C_ijkl * ( 1i * k_l * u_k - eigenstrain_kl ) +sigma_ij = sym(zeros(3,3)); +u_k_space = [ sym('u_1_k'); sym('u_2_k'); sym('u_3_k') ]; +k_mat = [ sym('kx_grid_3D'); sym('ky_grid_3D'); sym('kz_grid_3D') ]; + +for i = 1 : 3 +for j = 1 : 3 + + for k = 1 : 3 + for l = 1 : 3 + sigma_ij(i,j) = sigma_ij(i,j) + C(i,j,k,l) * ( 1i * k_mat(l) * u_k_space(k) - Eigenstrain_k_space(k,l)); + end + end + +end +end + +%% BC condition for het. strain +C = sym(zeros(3,3,3,3)); + +C(1,1,1,1) = sym('C11'); C(2,2,2,2) = sym('C11'); C(3,3,3,3) = sym('C11'); +C(1,1,2,2) = sym('C12'); C(1,1,3,3) = sym('C12'); C(2,2,1,1) = sym('C12'); +C(2,2,3,3) = sym('C12'); C(3,3,1,1) = sym('C12'); C(3,3,2,2) = sym('C12'); +C(1,2,1,2) = sym('C44'); C(2,1,2,1) = sym('C44'); C(1,3,1,3) = sym('C44'); +C(3,1,3,1) = sym('C44'); C(2,3,2,3) = sym('C44'); C(3,2,3,2) = sym('C44'); +C(1,2,2,1) = sym('C44'); C(2,1,1,2) = sym('C44'); C(1,3,3,1) = sym('C44'); +C(3,1,1,3) = sym('C44'); C(2,3,3,2) = sym('C44'); C(3,2,2,3) = sym('C44'); + +BC_film = sym(zeros(3,1)); +u_A_k_space = [ sym('u_1_A_k'); sym('u_2_A_k'); sym('u_3_A_k') ]; +k_mat = [ sym('kx_grid'); sym('ky_grid'); sym('kz_grid') ]; +Eigenstrain_k_space; + +for i = 1 : 3 + + for k = 1 : 3 + for l = 1 : 3 + + BC_film(i) = BC_film(i) + -C(i,3,k,l) * ( u_A_k_space(k) * 1i * k_mat(l) - Eigenstrain_k_space(k,l) ); + + end + end + +end + +%% Expand elastic energy +P1 = sym('P1'); P2 = sym('P2'); P3 = sym('P3'); + +C = sym(zeros(3,3,3,3)); + +C(1,1,1,1) = sym('C11'); C(2,2,2,2) = sym('C11'); C(3,3,3,3) = sym('C11'); +C(1,1,2,2) = sym('C12'); C(1,1,3,3) = sym('C12'); C(2,2,1,1) = sym('C12'); +C(2,2,3,3) = sym('C12'); C(3,3,1,1) = sym('C12'); C(3,3,2,2) = sym('C12'); +C(1,2,1,2) = sym('C44'); C(2,1,2,1) = sym('C44'); C(1,3,1,3) = sym('C44'); +C(3,1,3,1) = sym('C44'); C(2,3,2,3) = sym('C44'); C(3,2,3,2) = sym('C44'); +C(1,2,2,1) = sym('C44'); C(2,1,1,2) = sym('C44'); C(1,3,3,1) = sym('C44'); +C(3,1,1,3) = sym('C44'); C(2,3,3,2) = sym('C44'); C(3,2,2,3) = sym('C44'); + +Q11 = sym('Q11'); Q12 = sym('Q12'); Q44 = sym('Q44'); + +e_ij = [sym('e_11'), sym('e_12'), sym('e_13'); ... + sym('e_21'), sym('e_22'), sym('e_23'); ... + sym('e_31'), sym('e_32'), sym('e_33')]; +Eigenstrain = sym(zeros(3,3)); +Eigenstrain(1,1) = sym( 'Q11 * P1^2 + Q12 * (P2^2 + P3^2);' ); +Eigenstrain(2,2) = sym( 'Q11 * P2^2 + Q12 * (P1^2 + P3^2)' ); +Eigenstrain(3,3) = sym( 'Q11 * P3^2 + Q12 * (P1^2 + P2^2)' ); +Eigenstrain(2,3) = sym( 'Q44 * P2 * P3' ); +Eigenstrain(1,3) = sym( 'Q44 * P1 * P3' ); +Eigenstrain(1,2) = sym( 'Q44 * P2 * P1' ); +Eigenstrain(3,2) = Eigenstrain(2,3); +Eigenstrain(3,1) = Eigenstrain(1,3); +Eigenstrain(2,1) = Eigenstrain(1,2); + +tot = sym('0'); +for i = 1 : 3 +for j = 1 : 3 +for k = 1 : 3 +for l = 1 : 3 + + tot = tot + 0.5 * C(i,j,k,l) * (e_ij(i,j) - Eigenstrain(i,j)) * (e_ij(k,l) - Eigenstrain(k,l)); + +end +end +end +end + +tot_1 = diff(tot,P1); +tot_2 = diff(tot,P2); +tot_3 = diff(tot,P3); + + +%% +e_k_lj = sym(zeros(3,3,3)); +for k = 1 : 3 +for l = 1 : 3 +for j = 1 : 3 + e_k_lj(k,l,j) = sym(sprintf('u%g%g_%g',k,l,j)); +end +end +end + +i = 1; +tot = 0; +for k = 1 : 3 +for l = 1 : 3 +for j = 1 : 3 + + tot = tot + C(i,j,k,l) * e_k_lj(k,l,j); + +end +end +end + + +%% +% Green's Tensor, +Green = sym(zeros(3,3)); +Green(1,1) = sym('G_11'); +Green(2,2) = sym('G_22'); +Green(3,3) = sym('G_33'); +Green(1,2) = sym('G_12'); +Green(1,3) = sym('G_13'); +Green(2,3) = sym('G_23'); +Green(2,1) = Green(1,2); +Green(3,1) = Green(1,3); +Green(3,2) = Green(2,3); + +sigma = sym(zeros(3,3)); +sigma(1,1) = sym('s_11'); +sigma(2,2) = sym('s_22'); +sigma(3,3) = sym('s_33'); +sigma(1,2) = sym('s_12'); +sigma(1,3) = sym('s_13'); +sigma(2,3) = sym('s_23'); +sigma(2,1) = sigma(1,2); +sigma(3,1) = sigma(1,3); +sigma(3,2) = sigma(2,3); + +k_vec = [sym('k1'), sym('k2'), sym('k3')]; + +e_ij = sym(zeros(3,3)); + +for i = 1 : 3 +for j = 1 : 3 + for n = 1 : 3 + for m = 1 : 3 + + e_ij(i,j) = e_ij(i,j) + 0.5 * (k_vec(j) * Green(i,n) + k_vec(i) * Green(j,n)) * k_vec(m) * sigma(n,m); + + end + end +end +end + + +%% + +Z_k = sym(zeros(3,1)); +e_grids = [sym('ex_3D'), sym('ey_3D'), sym('ez_3D')]; +d_k = [sym('d1_k'), sym('d2_k'), sym('d3_k')]; + +L_k = sym(zeros(3,3)); + +for i = 1 : 3 +for j = 1 : 3 +for k = 1 : 3 + L_k(i,j,k) = sym(sprintf('squeeze(L_k(%g,%g,%g))',i,j,k)); +end +end +end + +N_k = sym(zeros(3,3)); +for m = 1 : 3 +for p = 1 : 3 + for j = 1 : 3 + + N_k(m,p) = N_k(m,p) + e_grids(j) * L_k(m,j,p); + + end +end +end + +for p = 1 : 3 + for m = 1 : 3 + + Z_k(p) = Z_k(p) + e_grids(m) * N_k(m,p) / d_k(m); + + end +end + +V_k = sym(zeros(3,3)); +for i = 1 : 3 +for j = 1 : 3 + + V_k(i,j) = sym(sprintf('V_k%g%g',i,j)); + +end +end + +k_grids = [sym('kx_grid_3D'), sym('ky_grid_3D'), sym('kz_grid_3D')]; + +B_k_mnp = sym(zeros(3,3,3)); +for n = 1 : 3 +for m = 1 : 3 +for p = 1 : 3 + + B_k_mnp(m,n,p) = 0.5 * ( 1i * k_grids(n) * V_k(m,p) + 1i * k_grids(m) * V_k(n,p) ); + +end +end +end + +tot = ''; +for m = 1 : 3 +for n = 1 : 3 +for p = 1 : 3 + + fprintf('B_k_mnp(:,:,:,%g,%g,%g)=%s\n',m,n,p,char(B_k_mnp(m,n,p))) + +end +end +end + +%% +syms C11 Q11 C12 Q12 q11 q12 +eqns = [C11*Q11+2*C12*Q12 == q11, q12 == C11*Q12 + C12*(Q11+Q12)]; +vars = [Q11,Q12]; +[a,b] = solve(eqns,vars); + +q11_h = q11 + 2 * q12; +q22_h = q11 - q12; + +C11_h = C11 + 2 * C12; +C22_h = C11 - C12; + +simplify((1/3) * ((q11_h/C11_h) + (2*q22_h/C22_h)) - a) +simplify((1/3) * ((q11_h/C11_h) - (q22_h/C22_h)) - b) + +%% Calculate displacement field +q = sym(zeros(3,3,3,3)); + +q(1,1,1,1) = sym('q11'); q(2,2,2,2) = sym('q11'); q(3,3,3,3) = sym('q11'); +q(1,1,2,2) = sym('q12'); q(1,1,3,3) = sym('q12'); q(2,2,1,1) = sym('q12'); +q(2,2,3,3) = sym('q12'); q(3,3,1,1) = sym('q12'); q(3,3,2,2) = sym('q12'); +q(1,2,1,2) = sym('q44/2'); q(2,1,2,1) = sym('q44/2'); q(1,3,1,3) = sym('q44/2'); +q(3,1,3,1) = sym('q44/2'); q(2,3,2,3) = sym('q44/2'); q(3,2,3,2) = sym('q44/2'); +q(1,2,2,1) = sym('q44/2'); q(2,1,1,2) = sym('q44/2'); q(1,3,3,1) = sym('q44/2'); +q(3,1,1,3) = sym('q44/2'); q(2,3,3,2) = sym('q44/2'); q(3,2,2,3) = sym('q44/2'); + +L = sym(zeros(3,3,3)); + +delta = sym(eye(3,3)); + +P = [sym('P1'), sym('P2'), sym('P3')]; + +for m = 1 : 3 +for j = 1 : 3 +for p = 1 : 3 + for k = 1 : 3 + for l = 1 : 3 + + L(m,j,p) = L(m,j,p) + q(m,j,k,l) * ( delta(k,p) * P(l) + P(k) * delta(l,p) ); + + end + end +end +end +end + +%% +A=sym(zeros(6,6)); +q22_h = sym('q22_h'); +q12 = sym('q12'); +q11 = sym('q11'); +q44 = sym('q44'); + +B = sym(zeros(3,3)); +for i = 1 : 6 +for j = 1 : 6 + B(i,j) = sym(sprintf('B_%g%g',i,j)); +end +end + +% p = 1,2,3 ... A_pp + for p = 1 : 3 + A(p,p) = q22_h^2*B(p,p) + A(p,p); + end + + for p = 1 : 3 + for o = 1 : 3 + A(p,p) = 2*q12*q22_h*B(p,o) + A(p,p); + end + end + + for i = 1 : 3 + for p = 1 : 3 + for o = 1 : 3 + A(i,i) = A(i,i) + q12^2*B(p,o); + end + end + end + +A(1,2) = q22_h^2 * B(1,2); +for p = 1 : 3 + A(1,2) = A(1,2) - q12*q22_h*B(p,3); +end + +for p = 1 : 3 +for o = 1 : 3 + A(1,2) = A(1,2) + q11*q12*B(p,o); +end +end +A(2,1) = A(1,2); + +A(1,3) = q22_h^2 * B(1,3); +for p = 1 : 3 + A(1,3) = A(1,3) - q12*q22_h*B(p,2); +end + +for p = 1 : 3 +for o = 1 : 3 + A(1,3) = A(1,3) + q11*q12*B(p,o); +end +end +A(3,1) = A(1,3); + +A(2,3) = q22_h^2 * B(2,3); +for p = 1 : 3 + A(2,3) = A(2,3) - q12*q22_h*B(p,1); +end + +for p = 1 : 3 +for o = 1 : 3 + A(2,3) = A(2,3) + q11*q12*B(p,o); +end +end +A(3,2) = A(2,3); + +% o = 4,5,6 +for o = 4:6 + + A(1,o) = q22_h*q44*B(1,o); + + for p = 1 : 3 + A(1,o) = A(1,o) + q12*q44*B(p,o); + end + +end + + +% o = 4,5,6 +for o = 4:6 + + A(2,o) = q22_h*q44*B(2,o); + + for p = 1 : 3 + A(2,o) = A(2,o) + q12*q44*B(p,o); + end + +end + +% o = 4,5,6 +for o = 4:6 + + A(3,o) = q22_h*q44*B(3,o); + + for p = 1 : 3 + A(3,o) = A(3,o) + q12*q44*B(p,o); + end + +end + +for p = 4 : 6 +for o = 4 : 6 + A(p,o) = A(p,o) + q44^2*B(p,o); +end +end + +for i = 1 : 6 +for j = 1 : 6 + fprintf('A_%g%g=%s\n',i,j,char(A(i,j))); +end +end + +%% +C = sym(zeros(3,3,3,3)); + +C(1,1,1,1) = sym('C11'); C(2,2,2,2) = sym('C11'); C(3,3,3,3) = sym('C11'); +C(1,1,2,2) = sym('C12'); C(1,1,3,3) = sym('C12'); C(2,2,1,1) = sym('C12'); +C(2,2,3,3) = sym('C12'); C(3,3,1,1) = sym('C12'); C(3,3,2,2) = sym('C12'); +C(1,2,1,2) = sym('C44'); C(2,1,2,1) = sym('C44'); C(1,3,1,3) = sym('C44'); +C(3,1,3,1) = sym('C44'); C(2,3,2,3) = sym('C44'); C(3,2,3,2) = sym('C44'); +C(1,2,2,1) = sym('C44'); C(2,1,1,2) = sym('C44'); C(1,3,3,1) = sym('C44'); +C(3,1,1,3) = sym('C44'); C(2,3,3,2) = sym('C44'); C(3,2,2,3) = sym('C44'); + +e = sym(zeros(3,3)); +for i = 1 : 3 +for j = 1 : i + e(i,j) = sym(sprintf('e_%g%g',i,j)); +end +end + +e(1,2) = e(2,1); e(1,3) = e(3,1); e(2,3) = e(3,2); + +tot = sym(zeros(3,1)); +for i = 1 : 3 + for k = 1 : 3 + for l = 1 : 3 + tot(i) = tot(i) + C(i,3,k,l) * e(k,l); + end + end +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/RandomP.m",".m","645","16","P1 = zeros( Nx, Ny, Nz ); P2 = P1; P3 = P1; + +init_perturb = rand(Nx, Ny, Nz) > 0.5; % where to perturb +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; % how much to perturb +P1(init_perturb) = perturb_amt(init_perturb); +P1(~init_perturb) = -perturb_amt(~init_perturb); + +init_perturb = rand(Nx, Ny, Nz) > 0.5; +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; +P2(init_perturb) = perturb_amt(init_perturb); +P2(~init_perturb) = -perturb_amt(~init_perturb); + +init_perturb = rand(Nx, Ny, Nz) > 0.5; +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; +P3(init_perturb) = perturb_amt(init_perturb); +P3(~init_perturb) = -perturb_amt(~init_perturb);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/ThermalNoise.m",".m","550","11","% Thermal Noise +ThermConst = k_boltzmann * Temperature / (dx * dy * dz); +Thermal_Noise_Sigma = sqrt(2 * ThermConst); + +Thermal_Noise_1 = normrnd(0,Thermal_Noise_Sigma,Nx,Ny,Nz); +Thermal_Noise_2 = normrnd(0,Thermal_Noise_Sigma,Nx,Ny,Nz); +Thermal_Noise_3 = normrnd(0,Thermal_Noise_Sigma,Nx,Ny,Nz); + +Thermal_Noise_1_2Dk = fft_2d_slices(Thermal_Noise_1) .* in_film .* Nucleation_Sites; +Thermal_Noise_2_2Dk = fft_2d_slices(Thermal_Noise_2) .* in_film .* Nucleation_Sites; +Thermal_Noise_3_2Dk = fft_2d_slices(Thermal_Noise_3) .* in_film .* Nucleation_Sites;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/AxesSetup.m",".m","1308","37","%% Set up real space axis +x_axis = linspace(0, Lx, Nx)'; y_axis = linspace(0, Ly, Ny)'; z_axis = linspace(0, Lz, Nz)'; + +%% VERY IMPORTANT STEP!! Let us redefine zero, otherwise the exp() term will make our matrix solving go to shit... +z_axis = z_axis - z_axis((round(Nz/2))); + +dx = x_axis(2) - x_axis(1); dy = y_axis(2) - y_axis(1); dz = z_axis(2) - z_axis(1); +[y_grid, x_grid, z_grid] = meshgrid(x_axis, y_axis, z_axis); +% kx_grid(x,y,z) + +%% Fourier space vectors -> Gradient energy terms and things that use air + film + sub +kx = 2*pi/Lx*[0:Nx/2 -Nx/2+1:-1]'; +ky = 2*pi/Ly*[0:Ny/2 -Ny/2+1:-1]'; +kz = 2*pi/Lz*[0:Nz/2 -Nz/2+1:-1]'; +[ky_grid_3D,kx_grid_3D,kz_grid_3D] = meshgrid(kx,ky,kz); +[ky_grid_2D, kx_grid_2D] = meshgrid(kx, ky); + +k_mag_3D = sqrt(kx_grid_3D.^2 + ky_grid_3D.^2 + kz_grid_3D.^2); +ex_3D = kx_grid_3D ./ k_mag_3D; +ey_3D = ky_grid_3D ./ k_mag_3D; +ez_3D = kz_grid_3D ./ k_mag_3D; + +%% +if( sub_index > 0 ) + in_film = (z_grid > z_axis(sub_index)) & (z_grid <= z_axis(film_index)); + not_in_film = ~in_film; + not_in_film = +not_in_film; + in_film = +in_film; +else + in_film = 1; + not_in_film = 0; +end + +%% z axis +h_film = z_axis(film_index); % end of film +h_sub = z_axis(1); % where substrate ends...limit of elastic deformation allowed in substrate +h_int = z_axis(interface_index);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/colorGradient.m",".m","2484","87","function [grad,im]=colorGradient(c1,c2,depth) +% COLORGRADIENT allows you to generate a gradient between 2 given colors, +% that can be used as colormap in your figures. +% +% USAGE: +% +% [grad,im]=getGradient(c1,c2,depth) +% +% INPUT: +% - c1: color vector given as Intensity or RGB color. Initial value. +% - c2: same as c1. This is the final value of the gradient. +% - depth: number of colors or elements of the gradient. +% +% OUTPUT: +% - grad: a matrix of depth*3 elements containing colormap (or gradient). +% - im: a depth*20*3 RGB image that can be used to display the result. +% +% EXAMPLES: +% grad=colorGradient([1 0 0],[0.5 0.8 1],128); +% surf(peaks) +% colormap(grad); +% +% -------------------- +% [grad,im]=colorGradient([1 0 0],[0.5 0.8 1],128); +% image(im); %display an image with the color gradient. + +% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal +% v:1.0 22 May 2011. Initial release. + +%Check input arguments. +%input arguments must be 2 or 3. +error(nargchk(2, 3, nargin)); + +%If c1 or c2 is not a valid RGB vector return an error. +if numel(c1)~=3 + error('color c1 is not a valir RGB vector'); +end +if numel(c2)~=3 + error('color c2 is not a valir RGB vector'); +end + +if max(c1)>1&&max(c1)<=255 + %warn if RGB values are given instead of Intensity values. Convert and + %keep procesing. + warning('color c1 is not given as intensity values. Trying to convert'); + c1=c1./255; +elseif max(c1)>255||min(c1)<0 + error('C1 RGB values are not valid.') +end + +if max(c2)>1&&max(c2)<=255 + %warn if RGB values are given instead of Intensity values. Convert and + %keep procesing. + warning('color c2 is not given as intensity values. Trying to convert'); + c2=c2./255; +elseif max(c2)>255||min(c2)<0 + error('C2 RGB values are not valid.') +end +%default depth is 64 colors. Just in case we did not define that argument. +if nargin < 3 + depth=64; +end + +%determine increment step for each color channel. +dr=(c2(1)-c1(1))/(depth-1); +dg=(c2(2)-c1(2))/(depth-1); +db=(c2(3)-c1(3))/(depth-1); + +%initialize gradient matrix. +grad=zeros(depth,3); +%initialize matrix for each color. Needed for the image. Size 20*depth. +r=zeros(20,depth); +g=zeros(20,depth); +b=zeros(20,depth); +%for each color step, increase/reduce the value of Intensity data. +for j=1:depth + grad(j,1)=c1(1)+dr*(j-1); + grad(j,2)=c1(2)+dg*(j-1); + grad(j,3)=c1(3)+db*(j-1); + r(:,j)=grad(j,1); + g(:,j)=grad(j,2); + b(:,j)=grad(j,3); +end + +%merge R G B matrix and obtain our image. +im=cat(3,r,g,b); +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/CalcElasticEnergy.m",".m","1456","25","if( ELASTIC ) + CalculateStrain; + + b11 = 0.5*C11*(Q11^2 + 2*Q12^2) + C12*Q12*(2*Q11 + Q12); + b12 = C11*Q12*(2*Q11 + Q12) + C12*(Q11^2 + 3*Q12^2 + 2*Q11*Q12) + 2*C44*Q44^2; + + f1_elastic = -( (q11.*TotalStrain_11 + q12.*TotalStrain_22 + q12.*TotalStrain_33) .* (2.*P1) + 2.*q44.*(TotalStrain_12 .* P2 + TotalStrain_13 .* P3) ) + (4 .* (b11) .* P1.^2 + 2 .* (b12) .* ( P2.^2 + P3.^2 )) .* P1; + f2_elastic = -( (q11.*TotalStrain_22 + q12.*TotalStrain_11 + q12.*TotalStrain_33) .* (2.*P2) + 2.*q44.*(TotalStrain_12 .* P1 + TotalStrain_13 .* P3) ) + (4 .* (b11) .* P2.^2 + 2 .* (b12) .* ( P3.^2 + P1.^2 )) .* P2; + f3_elastic = -( (q11.*TotalStrain_33 + q12.*TotalStrain_11 + q12.*TotalStrain_22) .* (2.*P3) + 2.*q44.*(TotalStrain_23 .* P2 + TotalStrain_13 .* P1) ) + (4 .* (b11) .* P3.^2 + 2 .* (b12) .* ( P1.^2 + P2.^2 )) .* P3; + + f1_elastic = f1_elastic .* in_film .* Nucleation_Sites; + f2_elastic = f2_elastic .* in_film .* Nucleation_Sites; + f3_elastic = f3_elastic .* in_film .* Nucleation_Sites; + + f1_elastic_2Dk = fft_2d_slices(f1_elastic); + f2_elastic_2Dk = fft_2d_slices(f2_elastic); + f3_elastic_2Dk = fft_2d_slices(f3_elastic); +else + f1_elastic_2Dk = 0; f2_elastic_2Dk = 0; f3_elastic_2Dk = 0; + f1_elastic = 0; f2_elastic = 0; f3_elastic = 0; + TotalStrain_11 = 0; TotalStrain_22 = 0; + TotalStrain_33 = 0; TotalStrain_12 = 0; + TotalStrain_13 = 0; TotalStrain_23 = 0; + u_1 = 0; u_2 = 0; u_3 = 0; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Constants.m",".m","68","2","permittivity_0 = 8.85418782*1e-12; +k_boltzmann = 1.38064852 * 1e-23;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/GreenTensorSetup.m",".m","1015","39","%% Green's Tensor +Green = zeros(Nx,Ny,Nz,3,3); + +% For each k vector find Green's Tensor +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny +for k3_ind = 1 : Nz + + K_vec = [kx_grid_3D(k1_ind,k2_ind,k3_ind) ky_grid_3D(k1_ind,k2_ind,k3_ind) kz_grid_3D(k1_ind,k2_ind,k3_ind)]; % Fourier space vector + g_inv = zeros(3,3); + for i_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + for k_ind = 1 : 3 + g_inv(i_ind,j_ind) = g_inv(i_ind,j_ind) + C(i_ind,k_ind,j_ind,l_ind) * K_vec(k_ind) * K_vec(l_ind); + end + end + end + end + + Green(k1_ind,k2_ind,k3_ind,:,:) = inv(g_inv); + +end +end +end + +Green((kx==0),(ky==0),(kz==0),:,:) = 0; + +Green_11 = squeeze(Green(:,:,:,1,1)); +Green_12 = squeeze(Green(:,:,:,1,2)); +Green_13 = squeeze(Green(:,:,:,1,3)); + +Green_21 = squeeze(Green(:,:,:,2,1)); +Green_22 = squeeze(Green(:,:,:,2,2)); +Green_23 = squeeze(Green(:,:,:,2,3)); + +Green_31 = squeeze(Green(:,:,:,3,1)); +Green_32 = squeeze(Green(:,:,:,3,2)); +Green_33 = squeeze(Green(:,:,:,3,3));","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/EigenstrainInFilm.m",".m","3227","31","%% Eigenstrains +CalcEigenstrains + +%% Calculate the displacement field via Khachutaryan method +% For each k vector calculate displacement field +u_1_A_k = - C11.*Eigenstrain_11_k.*kx_grid_3D.*Green_11.*1i - C12.*Eigenstrain_22_k.*kx_grid_3D.*Green_11.*1i - C12.*Eigenstrain_33_k.*kx_grid_3D.*Green_11.*1i - C44.*Eigenstrain_12_k.*kx_grid_3D.*Green_12.*2i - C44.*Eigenstrain_13_k.*kx_grid_3D.*Green_13.*2i - C12.*Eigenstrain_11_k.*ky_grid_3D.*Green_12.*1i - C11.*Eigenstrain_22_k.*ky_grid_3D.*Green_12.*1i - C12.*Eigenstrain_33_k.*ky_grid_3D.*Green_12.*1i - C44.*Eigenstrain_12_k.*ky_grid_3D.*Green_11.*2i - C44.*Eigenstrain_23_k.*ky_grid_3D.*Green_13.*2i - C12.*Eigenstrain_11_k.*kz_grid_3D.*Green_13.*1i - C12.*Eigenstrain_22_k.*kz_grid_3D.*Green_13.*1i - C11.*Eigenstrain_33_k.*kz_grid_3D.*Green_13.*1i - C44.*Eigenstrain_13_k.*kz_grid_3D.*Green_11.*2i - C44.*Eigenstrain_23_k.*kz_grid_3D.*Green_12.*2i; +u_2_A_k = - C11.*Eigenstrain_11_k.*kx_grid_3D.*Green_21.*1i - C12.*Eigenstrain_22_k.*kx_grid_3D.*Green_21.*1i - C12.*Eigenstrain_33_k.*kx_grid_3D.*Green_21.*1i - C44.*Eigenstrain_12_k.*kx_grid_3D.*Green_22.*2i - C44.*Eigenstrain_13_k.*kx_grid_3D.*Green_23.*2i - C12.*Eigenstrain_11_k.*ky_grid_3D.*Green_22.*1i - C11.*Eigenstrain_22_k.*ky_grid_3D.*Green_22.*1i - C12.*Eigenstrain_33_k.*ky_grid_3D.*Green_22.*1i - C44.*Eigenstrain_12_k.*ky_grid_3D.*Green_21.*2i - C44.*Eigenstrain_23_k.*ky_grid_3D.*Green_23.*2i - C12.*Eigenstrain_11_k.*kz_grid_3D.*Green_23.*1i - C12.*Eigenstrain_22_k.*kz_grid_3D.*Green_23.*1i - C11.*Eigenstrain_33_k.*kz_grid_3D.*Green_23.*1i - C44.*Eigenstrain_13_k.*kz_grid_3D.*Green_21.*2i - C44.*Eigenstrain_23_k.*kz_grid_3D.*Green_22.*2i; +u_3_A_k = - C11.*Eigenstrain_11_k.*kx_grid_3D.*Green_31.*1i - C12.*Eigenstrain_22_k.*kx_grid_3D.*Green_31.*1i - C12.*Eigenstrain_33_k.*kx_grid_3D.*Green_31.*1i - C44.*Eigenstrain_12_k.*kx_grid_3D.*Green_32.*2i - C44.*Eigenstrain_13_k.*kx_grid_3D.*Green_33.*2i - C12.*Eigenstrain_11_k.*ky_grid_3D.*Green_32.*1i - C11.*Eigenstrain_22_k.*ky_grid_3D.*Green_32.*1i - C12.*Eigenstrain_33_k.*ky_grid_3D.*Green_32.*1i - C44.*Eigenstrain_12_k.*ky_grid_3D.*Green_31.*2i - C44.*Eigenstrain_23_k.*ky_grid_3D.*Green_33.*2i - C12.*Eigenstrain_11_k.*kz_grid_3D.*Green_33.*1i - C12.*Eigenstrain_22_k.*kz_grid_3D.*Green_33.*1i - C11.*Eigenstrain_33_k.*kz_grid_3D.*Green_33.*1i - C44.*Eigenstrain_13_k.*kz_grid_3D.*Green_31.*2i - C44.*Eigenstrain_23_k.*kz_grid_3D.*Green_32.*2i; + +% DC component = zero by def. +u_1_A_k((kx==0),(ky==0),(kz==0)) = 0; +u_2_A_k((kx==0),(ky==0),(kz==0)) = 0; +u_3_A_k((kx==0),(ky==0),(kz==0)) = 0; + +u_1_A = real( ifftn( u_1_A_k ) ); +u_2_A = real( ifftn( u_2_A_k ) ); +u_3_A = real( ifftn( u_3_A_k ) ); + +e_11_A_k = 1i .* kx_grid_3D .* u_1_A_k; +e_22_A_k = 1i .* ky_grid_3D .* u_2_A_k; +e_33_A_k = 1i .* kz_grid_3D .* u_3_A_k; +e_12_A_k = 0.5 * ( 1i .* kx_grid_3D .* u_2_A_k + 1i .* ky_grid_3D .* u_1_A_k ); +e_13_A_k = 0.5 * ( 1i .* kx_grid_3D .* u_3_A_k + 1i .* kz_grid_3D .* u_1_A_k ); +e_23_A_k = 0.5 * ( 1i .* kz_grid_3D .* u_2_A_k + 1i .* ky_grid_3D .* u_3_A_k ); + +e_11_A = real(ifftn(e_11_A_k)); +e_22_A = real(ifftn(e_22_A_k)); +e_33_A = real(ifftn(e_33_A_k)); +e_12_A = real(ifftn(e_12_A_k)); +e_13_A = real(ifftn(e_13_A_k)); +e_23_A = real(ifftn(e_23_A_k));","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/unfreezeColors.m",".m","3611","107","function unfreezeColors(h) +% unfreezeColors Restore colors of a plot to original indexed color. (v2.3) +% +% Useful if you want to apply a new colormap to plots whose +% colors were previously frozen with freezeColors. +% +% Usage: +% unfreezeColors unfreezes all objects in current axis, +% unfreezeColors(axh) same, but works on axis axh. axh can be vector. +% unfreezeColors(figh) same, but for all objects in figure figh. +% +% Has no effect on objects on which freezeColors was not already called. +% (Note: if colorbars were frozen using cbfreeze, use cbfreeze('off') to +% unfreeze them. See freezeColors for information on cbfreeze.) +% +% +% See also freezeColors, freezeColors_pub.html, cbfreeze. +% +% +% John Iversen (iversen@nsi.edu) 3/23/05 +% + +% Changes: +% JRI 9/1/06 now restores any object with frozen CData; +% can unfreeze an entire figure at once. +% JRI 4/7/10 Change documentation for colorbars + +% Free for all uses, but please retain the following: +% +% Original Author: +% John Iversen, 2005-10 +% john_iversen@post.harvard.edu + +error(nargchk(0,1,nargin,'struct')) + +appdatacode = 'JRI__freezeColorsData'; + +%default: operate on gca +if nargin < 1, + h = gca; +end + +if ~ishandle(h), + error('JRI:unfreezeColors:invalidHandle',... + 'The argument must be a valid graphics handle to a figure or axis') +end + +%if h is a figure, loop on its axes +if strcmp(get(h,'type'),'figure'), + h = get(h,'children'); +end + +for h1 = h', %loop on axes + + %process all children, acting only on those with saved CData + % ( in appdata JRI__freezeColorsData) + ch = findobj(h1); + + for hh = ch', + + %some object handles may be invalidated when their parent changes + % (e.g. restoring colors of a scattergroup unfortunately changes + % the handles of all its children). So, first check to make sure + % it's a valid handle + if ishandle(hh) + if isappdata(hh,appdatacode), + ad = getappdata(hh,appdatacode); + %get oroginal cdata + %patches have to be handled separately (see note in freezeColors) + if ~strcmp(get(hh,'type'),'patch'), + cdata = get(hh,'CData'); + else + cdata = get(hh,'faceVertexCData'); + cdata = permute(cdata,[1 3 2]); + end + indexed = ad{1}; + scalemode = ad{2}; + + %size consistency check + if all(size(indexed) == size(cdata(:,:,1))), + %ok, restore indexed cdata + if ~strcmp(get(hh,'type'),'patch'), + set(hh,'CData',indexed); + else + set(hh,'faceVertexCData',indexed); + end + %restore cdatamapping, if needed + g = get(hh); + if isfield(g,'CDataMapping'), + set(hh,'CDataMapping',scalemode); + end + %clear appdata + rmappdata(hh,appdatacode) + else + warning('JRI:unfreezeColors:internalCdataInconsistency',... + ['Could not restore indexed data: it is the wrong size. ' ... + 'Were the axis contents changed since the call to freezeColors?']) + end + + end %test if has our appdata + end %test ishandle + + end %loop on children + +end %loop on axes + +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/convert.m",".m","1116","42","function color = convert( P1, P2, P3, P1_min,P1_max,P2_min,P2_max,P3_min,P3_max ) +% convert P into a color + +% num = 1024; +% Area = hsv(num); +% Area_axis = linspace(-pi,pi,num); +% Phi = parula(num); +% Phi_axis = linspace(-pi/2,pi/2,num); +% +% +% % find where in the Area P is +% polar_angle = atan2(P2, P1); +% polar_angle = repmat(polar_angle,1,num); +% Area_axis = repmat(Area_axis,numel(P1),1); +% [~, ind] = min(abs(polar_angle - Area_axis),[],2); +% Area_val = Area(ind,:); +% +% % find where in the height P is +% Phi_axis = repmat(Phi_axis,numel(P1),1); +% phi_angle = acos( P3 ./ sqrt( P1.^2 + P2.^2 ) ); phi_angle = repmat(phi_angle,1,num); +% [~, ind] = min(abs(phi_angle - Phi_axis),[],2); +% Height_val = Phi(ind,:); +% +% color = cat(3,Area_val,Height_val); + + % normalize P + R = sqrt(P1.^2 + P2.^2 + P3.^2); + + P1 = P1 ./ R; + P2 = P2 ./ R; + P3 = P3 ./ R; + + R = (P3+1)/2; + G = (P1+1)/2; + B = (P2+1)/2; + + Area_val = [R,G,B]; + Height_val = [R,G,B]; + + color = cat(3,Area_val,Height_val); + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/SurfaceDepolEnergy.m",".m","144","8","%% Surface depolarization field +if( ELECTRIC == 1 && SURFACE_DEPOL == 1 ) + f3_surface_depol_2Dk = 0; +else + f3_surface_depol_2Dk = 0; +end + +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/EnergyDensities.m",".m","3969","78","% Landau Energy +f_landau = a1 .* ( P1.^2 + P2.^2 + P3.^2 ) + a11 .* ( P1.^4 + P2.^4 + P3.^4 ) + ... + a12 .* ( P1.^2 .* P2.^2 + P1.^2 .* P3.^2 + P2.^2 .* P3.^2 ) + ... + a111 .* ( P1.^6 + P2.^6 + P3.^6 ) + a112 .* ( P1.^4 .* (P2.^2 + P3.^2) + P2.^4 .* (P3.^2 + P1.^2) + P3.^4 .* (P1.^2 + P2.^2) ) + ... + a123 .* ( P1.^2 .* P2.^2 .* P3.^2 ) + ... + a1111 .* ( P1.^8 + P2.^8 + P3.^8 ) + ... + a1112 .* ( P1.^4 .* P2.^4 + P2.^4 .* P3.^4 + P1.^4 .* P3.^4 ) + ... + a1123 .* ( P1.^4 .* P2.^2 .* P3.^2 + P2.^4 .* P3.^2 .* P1.^2 + P3.^4 .* P1.^2 .* P2.^2 ); + +Eigenstrain_11 = Q11 * P1.^2 + Q12 .* (P2.^2 + P3.^2); +Eigenstrain_22 = Q11 * P2.^2 + Q12 .* (P1.^2 + P3.^2); +Eigenstrain_33 = Q11 * P3.^2 + Q12 .* (P1.^2 + P2.^2); +Eigenstrain_23 = Q44 * P2 .* P3; +Eigenstrain_13 = Q44 * P1 .* P3; +Eigenstrain_12 = Q44 * P1 .* P2; + +ElasticStrain_11 = TotalStrain_11 + TotalStrain_homo_11( P1, P2, P3 ) - Eigenstrain_11; +ElasticStrain_22 = TotalStrain_22 + TotalStrain_homo_22( P1, P2, P3 ) - Eigenstrain_22; +ElasticStrain_33 = TotalStrain_33 + TotalStrain_homo_33( P1, P2, P3 ) - Eigenstrain_33; +ElasticStrain_12 = TotalStrain_12 + TotalStrain_homo_12( P1, P2, P3 ) - Eigenstrain_12; +ElasticStrain_23 = TotalStrain_23 + TotalStrain_homo_23( P1, P2, P3 ) - Eigenstrain_23; +ElasticStrain_13 = TotalStrain_13 + TotalStrain_homo_13( P1, P2, P3 ) - Eigenstrain_13; + +f_elastic = (C11/2) .* ( ElasticStrain_11.^2 + ElasticStrain_22.^2 + ElasticStrain_33.^2 ) + ... + (C12) .* ( ElasticStrain_11 .* ElasticStrain_22 + ElasticStrain_22 .* ElasticStrain_33 + ElasticStrain_11 .* ElasticStrain_33 ) + ... + (2*C44) .* ( ElasticStrain_12.^2 + ElasticStrain_23.^2 + ElasticStrain_13.^2 ); + +% e11_tot = TotalStrain_11 + TotalStrain_homo_11( P1, P2, P3 ); +% e22_tot = TotalStrain_22 + TotalStrain_homo_22( P1, P2, P3 ); +% e33_tot = TotalStrain_33 + TotalStrain_homo_33( P1, P2, P3 ); +% e12_tot = TotalStrain_12 + TotalStrain_homo_12( P1, P2, P3 ); +% e23_tot = TotalStrain_23 + TotalStrain_homo_23( P1, P2, P3 ); +% e13_tot = TotalStrain_13 + TotalStrain_homo_13( P1, P2, P3 ); +% +% f_elastic_2 = b11 .* ( P1.^4 + P2.^4 + P3.^4 ) + b12 .* ( P1.^2 .* P2.^2 + P1.^2 .* P3.^2 + P2.^2 .* P3.^2 ) + ... +% (C11/2) .* ( e11_tot.^2 + e22_tot.^2 + e33_tot.^2 ) + ... +% (C12) .* ( e11_tot .* e22_tot + e22_tot .* e33_tot + e11_tot .* e33_tot ) + ... +% (2*C44) .* ( e12_tot.^2 + e23_tot.^2 + e13_tot.^2 ) + ... +% -( q11 .* e11_tot + q12 .* e22_tot + q12 .* e33_tot ) .* P1.^2 + ... +% -( q11 .* e22_tot + q12 .* e11_tot + q12 .* e33_tot ) .* P2.^2 + ... +% -( q11 .* e33_tot + q12 .* e11_tot + q12 .* e22_tot ) .* P3.^2 + ... +% -(2*q44) .* ( e12_tot .* P1 .* P2 + e23_tot .* P2 .* P3 + e13_tot .* P1 .* P3 ); + +P1_2Dk = fft_2d_slices(P1); P2_2Dk = fft_2d_slices(P2); P3_2Dk = fft_2d_slices(P3); + +P1_1 = ifft_2d_slices(P1_2Dk .* kx_grid_3D); +P1_2 = ifft_2d_slices(P1_2Dk .* ky_grid_3D); +P1_3 = finite_diff_x3_first_der(P1,dz); + +P2_1 = ifft_2d_slices(P2_2Dk .* kx_grid_3D); +P2_2 = ifft_2d_slices(P2_2Dk .* ky_grid_3D); +P2_3 = finite_diff_x3_first_der(P2,dz); + +P3_1 = ifft_2d_slices(P3_2Dk .* kx_grid_3D); +P3_2 = ifft_2d_slices(P3_2Dk .* ky_grid_3D); +P3_3 = finite_diff_x3_first_der(P3,dz); + +G12 = 0; H44 = 0.6 * G110; H14 = 0; +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; + +f_grad = (G11/2) * ( P1_1.^2 + P2_2.^2 + P3_3.^2 ) + ... + G12 .* ( P1_1 .* P2_2 + P2_2 .* P3_3 + P3_3 .* P1_1 ) + ... + (H44/2) .* ( P1_2.^2 + P2_1.^2 + P2_3.^2 + P3_2.^2 + P1_3.^2 + P3_1.^2 ) + ... + (H14 - G12) .* ( P1_2 .* P2_1 + P1_3 .* P3_1 + P2_3 .* P3_2 ); + +f_elec = (-1/2) .* ( E_1_depol .* P1 + E_2_depol .* P2 + E_3_depol .* P3 ); + +f_elec_ext = -( E_1_applied .* P1 + E_2_applied .* P2 + E_3_applied .* P3 ); + +F_landau = sum(sum(sum(f_landau))); +F_elastic = sum(sum(sum(f_elastic))); +F_grad = sum(sum(sum(f_grad))); +F_elec = sum(sum(sum(f_elec))); +F_elec_ext = sum(sum(sum(f_elec_ext))); + +[F_landau, F_elastic,F_grad,F_elec] + +F_tot = sum([F_landau, F_elastic,F_grad,F_elec]);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Visualize_3D.m",".m","5720","136","function out = Visualize_3D(P1,P2,P3,x_grid,y_grid,z_grid,interface_index,film_index,Nx,Ny,Nz_film) + P1_film = P1(:,:,interface_index:film_index); + P2_film = P2(:,:,interface_index:film_index); + P3_film = P3(:,:,interface_index:film_index); + + x_grid_film = x_grid(:,:,interface_index:film_index); + y_grid_film = y_grid(:,:,interface_index:film_index); + z_grid_film = z_grid(:,:,interface_index:film_index); + + P1_max = max(max(max(P1_film))); + P1_min = min(min(min(P1_film))); + + P2_max = max(max(max(P2_film))); + P2_min = min(min(min(P2_film))); + + P3_max = max(max(max(P3_film))); + P3_min = min(min(min(P3_film))); + + Nz_film = film_index - interface_index + 1; + + %% Get the sides of the cube... + yz_1_x = x_grid_film(1,:,:); yz_1_x = reshape(yz_1_x,Ny,Nz_film); + yz_1_y = y_grid_film(1,:,:); yz_1_y = reshape(yz_1_y,Ny,Nz_film); + yz_1_z = z_grid_film(1,:,:); yz_1_z = reshape(yz_1_z,Ny,Nz_film); + + yz_1_P1 = P1_film(1,:,:); yz_1_P1 = reshape(yz_1_P1,Ny*Nz_film,1); + yz_1_P2 = P2_film(1,:,:); yz_1_P2 = reshape(yz_1_P2,Ny*Nz_film,1); + yz_1_P3 = P3_film(1,:,:); yz_1_P3 = reshape(yz_1_P3,Ny*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(yz_1_P1,yz_1_P2,yz_1_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Ny,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Ny,Nz_film,3); + yz_1_color = (Area+Height)/2; + + surf(yz_1_x,yz_1_y,yz_1_z,yz_1_color); + hold on; + + %% Get the sides of the cube... + yz_2_x = x_grid_film(end,:,:); yz_2_x = reshape(yz_2_x,Ny,Nz_film); + yz_2_y = y_grid_film(end,:,:); yz_2_y = reshape(yz_2_y,Ny,Nz_film); + yz_2_z = z_grid_film(end,:,:); yz_2_z = reshape(yz_2_z,Ny,Nz_film); + + yz_2_P1 = P1_film(end,:,:); yz_2_P1 = reshape(yz_2_P1,Ny*Nz_film,1); + yz_2_P2 = P2_film(end,:,:); yz_2_P2 = reshape(yz_2_P2,Ny*Nz_film,1); + yz_2_P3 = P3_film(end,:,:); yz_2_P3 = reshape(yz_2_P3,Ny*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(yz_2_P1,yz_2_P2,yz_2_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Ny,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Ny,Nz_film,3); + yz_2_color = (Area+Height)/2; + + surf(yz_2_x,yz_2_y,yz_2_z,yz_2_color); + + + %% Get the sides of the cube... + xz_1_x = x_grid_film(:,1,:); xz_1_x = reshape(xz_1_x,Nx,Nz_film); + xz_1_y = y_grid_film(:,1,:); xz_1_y = reshape(xz_1_y,Nx,Nz_film); + xz_1_z = z_grid_film(:,1,:); xz_1_z = reshape(xz_1_z,Nx,Nz_film); + + xz_1_P1 = P1_film(:,1,:); xz_1_P1 = reshape(xz_1_P1,Nx*Nz_film,1); + xz_1_P2 = P2_film(:,1,:); xz_1_P2 = reshape(xz_1_P2,Nx*Nz_film,1); + xz_1_P3 = P3_film(:,1,:); xz_1_P3 = reshape(xz_1_P3,Nx*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xz_1_P1,xz_1_P2,xz_1_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Nz_film,3); + xz_1_color = (Area+Height)/2; + + surf(xz_1_x,xz_1_y,xz_1_z,xz_1_color); + + %% Get the sides of the cube... + xz_2_x = x_grid_film(:,end,:); xz_2_x = reshape(xz_2_x,Nx,Nz_film); + xz_2_y = y_grid_film(:,end,:); xz_2_y = reshape(xz_2_y,Nx,Nz_film); + xz_2_z = z_grid_film(:,end,:); xz_2_z = reshape(xz_2_z,Nx,Nz_film); + + xz_2_P1 = P1_film(:,end,:); xz_2_P1 = reshape(xz_2_P1,Nx*Nz_film,1); + xz_2_P2 = P2_film(:,end,:); xz_2_P2 = reshape(xz_2_P2,Nx*Nz_film,1); + xz_2_P3 = P3_film(:,end,:); xz_2_P3 = reshape(xz_2_P3,Nx*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xz_2_P1,xz_2_P2,xz_2_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Nz_film,3); + xz_2_color = (Area+Height)/2; + + surf(xz_2_x,xz_2_y,xz_2_z,xz_2_color); + + %% Get the sides of the cube... + xy_1_x = x_grid_film(:,:,1); xy_1_x = reshape(xy_1_x,Nx,Ny); + xy_1_y = y_grid_film(:,:,1); xy_1_y = reshape(xy_1_y,Nx,Ny); + xy_1_z = z_grid_film(:,:,1); xy_1_z = reshape(xy_1_z,Nx,Ny); + + xy_1_P1 = P1_film(:,:,1); xy_1_P1 = reshape(xy_1_P1,Nx*Ny,1); + xy_1_P2 = P2_film(:,:,1); xy_1_P2 = reshape(xy_1_P2,Nx*Ny,1); + xy_1_P3 = P3_film(:,:,1); xy_1_P3 = reshape(xy_1_P3,Nx*Ny,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xy_1_P1,xy_1_P2,xy_1_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Ny,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Ny,3); + xy_1_color = (Area+Height)/2; + + surf(xy_1_x,xy_1_y,xy_1_z,xy_1_color); + + %% Get the sides of the cube... + xy_2_x = x_grid_film(:,:,end); xy_2_x = reshape(xy_2_x,Nx,Ny); + xy_2_y = y_grid_film(:,:,end); xy_2_y = reshape(xy_2_y,Nx,Ny); + xy_2_z = z_grid_film(:,:,end); xy_2_z = reshape(xy_2_z,Nx,Ny); + + xy_2_P1 = P1_film(:,:,end); xy_2_P1 = reshape(xy_2_P1,Nx*Ny,1); + xy_2_P2 = P2_film(:,:,end); xy_2_P2 = reshape(xy_2_P2,Nx*Ny,1); + xy_2_P3 = P3_film(:,:,end); xy_2_P3 = reshape(xy_2_P3,Nx*Ny,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xy_2_P1,xy_2_P2,xy_2_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Ny,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Ny,3); + xy_2_color = (Area+Height)/2; + + surf(xy_2_x,xy_2_y,xy_2_z,xy_2_color); + + %% + axis([min(min(min(x_grid_film))) max(max(max(x_grid_film))) ... + min(min(min(y_grid_film))) max(max(max(y_grid_film))) ... + min(min(min(z_grid_film))) max(max(max(z_grid_film)))] ) + shading flat +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Render3D.m",".m","91","1","Visualize_3D(P1,P2,P3,x_grid*1e9,y_grid*1e9,z_grid*1e9,interface_index,film_index,Nx,Ny,Nz)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/CalcElecEnergy.m",".m","3035","82","if( ELECTRIC ) + + %% Solve particular solution within the entire sample... + P1_3Dk = fftn(P1); P2_3Dk = fftn(P2); P3_3Dk = fftn(P3); + + potential_A_k = -1i .* (kx_grid_3D .* P1_3Dk + ky_grid_3D .* P2_3Dk + kz_grid_3D .* P3_3Dk) ./ ... + ( permittivity_0 .* (k_electric_11 .* kx_grid_3D.^2 + k_electric_22 .* ky_grid_3D.^2 + k_electric_33 .* kz_grid_3D.^2) ); + potential_A_k(k_mag_3D == 0) = 0; + potential_A = real(ifftn(potential_A_k)); + + E_A_1_k = -1i .* kx_grid_3D .* potential_A_k; + E_A_2_k = -1i .* ky_grid_3D .* potential_A_k; + E_A_3_k = -1i .* kz_grid_3D .* potential_A_k; + + E_A_1 = real(ifftn(E_A_1_k)); + E_A_2 = real(ifftn(E_A_2_k)); + E_A_3 = real(ifftn(E_A_3_k)); + + %% Homogenous solution boundary condition application, 2D FT solution + C_mat = zeros(Nx,Ny,2); + potential_bc_interface = squeeze(potential_A(:,:,interface_index)); + potential_bc_film = squeeze(potential_A(:,:,film_index)); + potential_bc_interface_2Dk = -fft2(potential_bc_interface); + potential_bc_film_2Dk = -fft2(potential_bc_film); + potential_bc_given_mat = cat(3,potential_bc_interface_2Dk,potential_bc_film_2Dk); + + potential_B_2Dk = zeros(Nx,Ny,Nz); + potential_B_2Dk_d3 = zeros(Nx,Ny,Nz); + + for k1 = 1 : Nx + for k2 = 1 : Ny + + C_mat(k1,k2,:) = squeeze(electric_bc_mats_inv(k1,k2,:,:)) * squeeze(potential_bc_given_mat(k1,k2,:)); + + end + end + + C1 = squeeze(C_mat(:,:,1)); C2 = squeeze(C_mat(:,:,2)); + p = sqrt((k_electric_11*kx_grid_2D.^2 + k_electric_22*ky_grid_2D.^2)/k_electric_33); + for z_loop = 1 : numel(z_axis) + potential_B_2Dk(:,:,z_loop) = C1 .* exp(z_axis(z_loop) .* p) + C2 .* exp(-z_axis(z_loop) .* p); + potential_B_2Dk_d3(:,:,z_loop) = p .* C1 .* exp(z_axis(z_loop) .* p) - p .* C2 .* exp(-z_axis(z_loop) .* p); + end + + % Fourier space origin + C_origin = electric_bc_mats_inv_korigin * squeeze(potential_bc_given_mat(1,1,:)); + C1 = C_origin(1); C2 = C_origin(2); + potential_B_2Dk(1,1,:) = C1 * z_axis + C2; + potential_B_2Dk_d3(1,1,:) = C1; + + %% Total Potential + potential_B = ifft_2d_slices(potential_B_2Dk); + potential = potential_A + potential_B; + + % E field + E_B_2Dk_1 = -1i .* kx_grid_3D .* potential_B_2Dk; + E_B_2Dk_2 = -1i .* ky_grid_3D .* potential_B_2Dk; + E_B_2Dk_3 = -potential_B_2Dk_d3; + + E_B_1 = ifft_2d_slices(E_B_2Dk_1); + E_B_2 = ifft_2d_slices(E_B_2Dk_2); + E_B_3 = ifft_2d_slices(E_B_2Dk_3); + E_1_depol = E_A_1 + E_B_1; + E_2_depol = E_A_2 + E_B_2; + E_3_depol = E_A_3 + E_B_3; + + %% Electrical energy define + f1_elec = -0.5 * E_1_depol .* in_film .* Nucleation_Sites; + f2_elec = -0.5 * E_2_depol .* in_film .* Nucleation_Sites; + f3_elec = -0.5 * E_3_depol .* in_film .* Nucleation_Sites; + + f1_elec_2Dk = fft_2d_slices(f1_elec); + f2_elec_2Dk = fft_2d_slices(f2_elec); + f3_elec_2Dk = fft_2d_slices(f3_elec); + +else + + f1_elec_2Dk = 0; f2_elec_2Dk = 0; f3_elec_2Dk = 0; + E_1_depol = 0; E_2_depol = 0; E_3_depol = 0; + potential = 0; + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/CalcDielectric.m",".m","17","1","% Calc dielectric","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/ElectrostaticSetup.m",".m","614","19","electric_bc_mats_inv = zeros(Nx,Ny,2,2); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if(k1_ind ~= 1 || k2_ind ~= 1) + eta_1 = kx_grid_2D(k1_ind,k2_ind); + eta_2 = ky_grid_2D(k1_ind,k2_ind); + p = sqrt((k_electric_11*eta_1^2 + k_electric_22*eta_2^2)/k_electric_33); + + potential_sol_mat = [ exp(h_int*p), exp(-h_int*p); ... + exp(h_film*p), exp(-h_film*p)]; + + electric_bc_mats_inv(k1_ind,k2_ind,:,:) = inv(potential_sol_mat); + end +end +end + +electric_bc_mats_inv_korigin = inv( [h_int, 1;... + h_film, 1] );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/HomoStrainSetup.m",".m","1223","21","% Macroscopic BC, stress free eigenstrain +% TotalStrain_11_homo = @(P1, P2, P3) Q11 .* vol_avg(P1.^2) + Q12 .* (vol_avg(P2.^2) + vol_avg(P3.^2)); +% TotalStrain_22_homo = @(P1, P2, P3) Q11 .* vol_avg(P2.^2) + Q12 .* (vol_avg(P3.^2) + vol_avg(P1.^2)); +% TotalStrain_33_homo = @(P1, P2, P3) Q11 .* vol_avg(P3.^2) + Q12 .* (vol_avg(P1.^2) + vol_avg(P2.^2)); +% TotalStrain_23_homo = @(P1, P2, P3) Q44 .* vol_avg(P2.*P3); +% TotalStrain_13_homo = @(P1, P2, P3) Q44 .* vol_avg(P1.*P3); +% TotalStrain_12_homo = @(P1, P2, P3) Q44 .* vol_avg(P1.*P2); + +TotalStrain_homo_11 = @(P1, P2, P3) Us_11; +TotalStrain_homo_22 = @(P1, P2, P3) Us_22; +TotalStrain_homo_12 = @(P1, P2, P3) Us_12; +TotalStrain_homo_33 = @(P1, P2, P3) -( C12 * TotalStrain_homo_11(P1,P2,P3) + C12 * TotalStrain_homo_22(P1,P2,P3) ) / C44; +TotalStrain_homo_23 = @(P1, P2, P3) 0; +TotalStrain_homo_13 = @(P1, P2, P3) 0; + +% TotalStrain_11_homo = @(P1, P2, P3) Us; +% TotalStrain_22_homo = @(P1, P2, P3) Us; +% TotalStrain_12_homo = @(P1, P2, P3) 0; +% TotalStrain_33_homo = @(P1, P2, P3) Q11 .* vol_avg(P3.^2) + Q12 .* (vol_avg(P1.^2) + vol_avg(P2.^2)); +% TotalStrain_23_homo = @(P1, P2, P3) Q44 .* vol_avg(P2.*P3); +% TotalStrain_13_homo = @(P1, P2, P3) Q44 .* vol_avg(P1.*P3);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Main.m",".m","1301","57","clc; + +%% Setup stuff +Constants; +Setup; +AxesSetup; +Nucleate; +GreenTensorSetup; +HomoStrainSetup; + +%% Setup stuff +load_file_setup = sprintf('Setup_Mats_BTO_pct%g_%g%g%g.mat',BTO_pct,Nx,Ny,Nz); +if( exist(load_file_setup) ) + load(load_file_setup); +else + %% Setup energy stuff + if(VPA_ELASTIC_ON) + InfinitePlateSetup_vpa; + else + InfinitePlateSetup; + end + + if(VPA_ELECTRIC_ON) + ElectrostaticSetup_vpa; + else + ElectrostaticSetup; + end + save(load_file_setup,... + 'strain_bc_mats_inv','strain_bc_mat_inv_korigin',... + 'eigenvec_mat','eigenval_mat',... + 'electric_bc_mats_inv','electric_bc_mats_inv_korigin',... + 'Green_11','Green_12','Green_13',... + 'Green_21','Green_22','Green_23',... + 'Green_31','Green_32','Green_33'); +end + +%% Initial conditions +InitP; + +%% Energies +CalcElasticEnergy +CalcElecEnergy +ThermalNoise +LandauEnergy +SurfaceDepolEnergy +ExternalEFieldEnergy + +f1_2Dk = f1_landau_2Dk + f1_elec_2Dk + f1_elastic_2Dk + f1_ext_E_2Dk + Thermal_Noise_1_2Dk; +f2_2Dk = f2_landau_2Dk + f2_elec_2Dk + f2_elastic_2Dk + f2_ext_E_2Dk + Thermal_Noise_2_2Dk; +f3_2Dk = f3_landau_2Dk + f3_elec_2Dk + f3_elastic_2Dk + f3_ext_E_2Dk + Thermal_Noise_3_2Dk + f3_surface_depol_2Dk; + + +c = 0; % Flag for do while loop +error = inf; + +%% Main loop +MainLoop","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/ElectrostaticSetup_vpa.m",".m","734","22","% Use vpa to get more accurate inverted matrices + +electric_bc_mats_inv = zeros(Nx,Ny,2,2); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if(k1_ind ~= 1 || k2_ind ~= 1) + eta_1 = kx_grid_2D(k1_ind,k2_ind); + eta_2 = ky_grid_2D(k1_ind,k2_ind); + p = sqrt((k_electric_11*eta_1^2 + k_electric_22*eta_2^2)/k_electric_33); + + potential_sol_mat = [ exp(h_int*p), exp(-h_int*p); ... + exp(h_film*p), exp(-h_film*p)]; + + vpa_mat = vpa(potential_sol_mat); + electric_bc_mats_inv(k1_ind,k2_ind,:,:) = double(inv(vpa_mat)); + end +end +end + +electric_bc_mats_inv_korigin = double ( inv( vpa([h_int, 1;... + h_film, 1]) ) );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/CalculateStress.m",".m","2688","21","% Calculate Hetero Stress, Hetero Elastic Stress + +% Elastic Strain = Total Strain (A + B) - Eigenstrain - HomoStrain +ElasticStrain_11 = TotalStrain_11 - Eigenstrain_11 - TotalStrain_homo_11(P1,P2,P3); +ElasticStrain_22 = TotalStrain_22 - Eigenstrain_22 - TotalStrain_homo_22(P1,P2,P3); +ElasticStrain_33 = TotalStrain_33 - Eigenstrain_33 - TotalStrain_homo_33(P1,P2,P3); +ElasticStrain_12 = TotalStrain_12 - Eigenstrain_12 - TotalStrain_homo_12(P1,P2,P3); +ElasticStrain_13 = TotalStrain_13 - Eigenstrain_13 - TotalStrain_homo_13(P1,P2,P3); +ElasticStrain_23 = TotalStrain_23 - Eigenstrain_23 - TotalStrain_homo_23(P1,P2,P3); + +% Hetero Stress = C_ijkl * ElasticStrain_kl +HeteroStress_11 = ElasticStrain_11*C(1, 1, 1, 1) + ElasticStrain_12*C(1, 1, 1, 2) + ElasticStrain_12*C(1, 1, 2, 1) + ElasticStrain_13*C(1, 1, 1, 3) + ElasticStrain_13*C(1, 1, 3, 1) + ElasticStrain_22*C(1, 1, 2, 2) + ElasticStrain_23*C(1, 1, 2, 3) + ElasticStrain_23*C(1, 1, 3, 2) + ElasticStrain_33*C(1, 1, 3, 3); +HeteroStress_22 = ElasticStrain_11*C(2, 2, 1, 1) + ElasticStrain_12*C(2, 2, 1, 2) + ElasticStrain_12*C(2, 2, 2, 1) + ElasticStrain_13*C(2, 2, 1, 3) + ElasticStrain_13*C(2, 2, 3, 1) + ElasticStrain_22*C(2, 2, 2, 2) + ElasticStrain_23*C(2, 2, 2, 3) + ElasticStrain_23*C(2, 2, 3, 2) + ElasticStrain_33*C(2, 2, 3, 3); +HeteroStress_33 = ElasticStrain_11*C(3, 3, 1, 1) + ElasticStrain_12*C(3, 3, 1, 2) + ElasticStrain_12*C(3, 3, 2, 1) + ElasticStrain_13*C(3, 3, 1, 3) + ElasticStrain_13*C(3, 3, 3, 1) + ElasticStrain_22*C(3, 3, 2, 2) + ElasticStrain_23*C(3, 3, 2, 3) + ElasticStrain_23*C(3, 3, 3, 2) + ElasticStrain_33*C(3, 3, 3, 3); +HeteroStress_12 = ElasticStrain_11*C(1, 2, 1, 1) + ElasticStrain_12*C(1, 2, 1, 2) + ElasticStrain_12*C(1, 2, 2, 1) + ElasticStrain_13*C(1, 2, 1, 3) + ElasticStrain_13*C(1, 2, 3, 1) + ElasticStrain_22*C(1, 2, 2, 2) + ElasticStrain_23*C(1, 2, 2, 3) + ElasticStrain_23*C(1, 2, 3, 2) + ElasticStrain_33*C(1, 2, 3, 3); +HeteroStress_13 = ElasticStrain_11*C(1, 3, 1, 1) + ElasticStrain_12*C(1, 3, 1, 2) + ElasticStrain_12*C(1, 3, 2, 1) + ElasticStrain_13*C(1, 3, 1, 3) + ElasticStrain_13*C(1, 3, 3, 1) + ElasticStrain_22*C(1, 3, 2, 2) + ElasticStrain_23*C(1, 3, 2, 3) + ElasticStrain_23*C(1, 3, 3, 2) + ElasticStrain_33*C(1, 3, 3, 3); +HeteroStress_23 = ElasticStrain_11*C(2, 3, 1, 1) + ElasticStrain_12*C(2, 3, 1, 2) + ElasticStrain_12*C(2, 3, 2, 1) + ElasticStrain_13*C(2, 3, 1, 3) + ElasticStrain_13*C(2, 3, 3, 1) + ElasticStrain_22*C(2, 3, 2, 2) + ElasticStrain_23*C(2, 3, 2, 3) + ElasticStrain_23*C(2, 3, 3, 2) + ElasticStrain_33*C(2, 3, 3, 3); + +% TotalStress = HeteroStress + HomoStress +% HomoStress from macroscopic BC +% Thin film: HomoStress_13 = HomoStress_23 = HomoStress_33 = 0","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/R_Phases.m",".m","838","19","r1_plus = ( P1 > 0.2 ) & ( P2 > 0.2 ) & ( P3 > 0.2 ); +r2_plus = ( P1 < -0.2 ) & ( P2 > 0.2 ) & ( P3 > 0.2 ); +r3_plus = ( P1 < -0.2 ) & ( P2 < -0.2 ) & ( P3 > 0.2 ); +r4_plus = ( P1 > 0.2 ) & ( P2 < -0.2 ) & ( P3 > 0.2 ); + +r1_minus = ( P1 < -0.2 ) & ( P2 < -0.2 ) & ( P3 < -0.2 ); +r2_minus = ( P1 > 0.2 ) & ( P2 < -0.2 ) & ( P3 < -0.2 ); +r3_minus = ( P1 > 0.2 ) & ( P2 > 0.2 ) & ( P3 < -0.2 ); +r4_minus = ( P1 < -0.2 ) & ( P2 > 0.2 ) & ( P3 < -0.2 ); + +sum(sum(sum(r1_plus))) / sum(sum(sum(in_film))) +sum(sum(sum(r2_plus))) / sum(sum(sum(in_film))) +sum(sum(sum(r3_plus))) / sum(sum(sum(in_film))) +sum(sum(sum(r4_plus))) / sum(sum(sum(in_film))) + +sum(sum(sum(r1_minus))) / sum(sum(sum(in_film))) +sum(sum(sum(r2_minus))) / sum(sum(sum(in_film))) +sum(sum(sum(r3_minus))) / sum(sum(sum(in_film))) +sum(sum(sum(r4_minus))) / sum(sum(sum(in_film)))","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/vol_avg.m",".m","64","5","function out = vol_avg( f ) + + out = mean(mean(mean(f))); + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/GradEnergy.m",".m","559","13","%% Gradient Free Energy +% Treat the z term not in FFT... +P1_d3_d3 = finite_diff_x3_second_der(P1_prev_2Dk,dz); +P2_d3_d3 = finite_diff_x3_second_der(P2_prev_2Dk,dz); +P3_d3_d3 = finite_diff_x3_second_der(P3_prev_2Dk,dz); + +G1_no_d3 = G11 * kx_grid_3D.^2 + H44 * ky_grid_3D.^2; +G2_no_d3 = G11 * ky_grid_3D.^2 + H44 * kx_grid_3D.^2; +G3_no_d3 = H44 * (kx_grid_3D.^2 + ky_grid_3D.^2); + +G1_d3_part = H44 * P1_d3_d3 .* in_film .* Nucleation_Sites; +G2_d3_part = H44 * P2_d3_d3 .* in_film .* Nucleation_Sites; +G3_d3_part = G11 * P3_d3_d3 .* in_film .* Nucleation_Sites; ","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/SaveData.m",".m","1325","34","save(sprintf('%sfinal__%g Us11__%g Us22__%gC__%gkV-cm__%s.mat',PATH,Us_11*1e2,Us_22*1e2,Temperature,E_1_applied/1e5,STRING),... + 'P1','P2','P3',... + 'P1_prev','P2_prev','P3_prev',... + ... + 'a1','a1_T','a11','a111','a1111','a1112','a112','a1122','a1123','a12','a123',... + ... + 'C11','C12','C44','C',... + 'TotalStrain_11','TotalStrain_22','TotalStrain_33','TotalStrain_12','TotalStrain_13','TotalStrain_23',... + 'u_1','u_2','u_3',... + 'TotalStrain_homo_11','TotalStrain_homo_22','TotalStrain_homo_33','TotalStrain_homo_12','TotalStrain_homo_13','TotalStrain_homo_23',... + ... + 'q11','q12','q44',... + 'Q11','Q12','Q44',... + ... + 'E_1_applied','E_2_applied','E_3_applied',... + 'E_1_depol','E_2_depol','E_3_depol',... + 'k_electric_11','k_electric_22','k_electric_33',... + 'potential',... + ... + 'G11','G12','H14','H44','G110',... + 'dt',... + 'l_0',... + 'h_film','h_int','h_sub',... + 'interface_index','film_index',... + 'x_axis','y_axis','z_axis',... + 'x_grid','y_grid','z_grid',... + 'Nx','Ny','Nz',... + ... + 'VPA_ELECTRIC_ON','VPA_ELASTIC_ON','ELASTIC','HET_ELASTIC_RELAX','ELECTRIC',... + 'SURFACE_DEPOL','NUCLEATE','ThermConst','LOAD',... + ... + 'Temperature','Us_11','Us_22','Us_12',... + 'errors','in_film','Nucleation_Sites'... + );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/MainLoop.m",".m","1816","64","if( 7 ~= exist(PATH,'dir')) + mkdir(PATH); +end + +errors = zeros(saves(end),1); + +while (c == 0 || error > epsilon) && c < saves(end) + + % saving + if( sum(c == saves) == 1 ) + save(sprintf('%s%g t__%g Us11__%g Us22__%gC__%gkV-cm__%s.mat',PATH,c,Us_11*1e2,Us_22*1e2,Temperature,E_1_applied/1e5,STRING),'P1','P2','P3'); + end + + % Previous iteration + P1_prev_2Dk = P1_2Dk; + f1_prev_2Dk = f1_2Dk; + + P2_prev_2Dk = P2_2Dk; + f2_prev_2Dk = f2_2Dk; + + P3_prev_2Dk = P3_2Dk; + f3_prev_2Dk = f3_2Dk; + + P1_prev = P1; + P2_prev = P2; + P3_prev = P3; + + % Next iteration + GradEnergy % d3_part uses previous P's + P1_2Dk = (( P1_prev_2Dk + dt .* -f1_prev_2Dk + dt .* G1_d3_part ) ./ ( 1 + dt .* G1_no_d3 )); + P2_2Dk = (( P2_prev_2Dk + dt .* -f2_prev_2Dk + dt .* G2_d3_part ) ./ ( 1 + dt .* G2_no_d3 )); + P3_2Dk = (( P3_prev_2Dk + dt .* -f3_prev_2Dk + dt .* G3_d3_part ) ./ ( 1 + dt .* G3_no_d3 )); + + P1 = ifft_2d_slices(P1_2Dk); + P2 = ifft_2d_slices(P2_2Dk); + P3 = ifft_2d_slices(P3_2Dk); + + %% Energies + CalcElasticEnergy + CalcElecEnergy + ThermalNoise + LandauEnergy + SurfaceDepolEnergy + ExternalEFieldEnergy + + f1_2Dk = f1_landau_2Dk + f1_elec_2Dk + f1_elastic_2Dk + f1_ext_E_2Dk + Thermal_Noise_1_2Dk; + f2_2Dk = f2_landau_2Dk + f2_elec_2Dk + f2_elastic_2Dk + f2_ext_E_2Dk + Thermal_Noise_2_2Dk; + f3_2Dk = f3_landau_2Dk + f3_elec_2Dk + f3_elastic_2Dk + f3_ext_E_2Dk + Thermal_Noise_3_2Dk + f3_surface_depol_2Dk; + + c = c + 1; + + % Progress + error = max( [sum(sum(sum(abs(P1-P1_prev)))); sum(sum(sum(abs(P2-P2_prev)))); sum(sum(sum(abs(P3-P3_prev))))] ); + errors(c) = error; + % print error + if( mod(c, 50) == 0 ) + Visualize + drawnow + error + end + +end + +SaveData","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/LatticeStrain.m",".m","3727","75","%% NSO +a_110_NSO=sqrt(5.7761026^2+5.5761705^2); a_001_NSO=8.0033835; +a_NSO=1/4*(a_110_NSO+a_001_NSO); +%% SSO +a_110_SSO=sqrt(5.758612^2+5.5279832^2); a_001_SSO=7.9627969; +a_SSO=1/4*(a_110_SSO+a_001_SSO); +%% GSO +a_110_GSO=sqrt(5.7454058^2+5.4805002^2); a_001_GSO=7.9314013; +a_GSO=1/4*(a_110_GSO+a_001_GSO); +%% TSO +a_110_TSO=sqrt(5.7299335^2+5.4638353^2); a_001_TSO=7.9164596; +a_TSO=1/4*(a_110_TSO+a_001_TSO); +%% DSO +a_110_DSO=sqrt(5.7163901^2+5.4400236^2); a_001_DSO=7.9031349; +a_DSO=1/4*(a_110_DSO+a_001_DSO); +%% BST family +aBTO=4.006; aSTO=3.905; +s11STOs=3.52*10^-12; s12STOs=-0.85*10^-12; s44STOs=7.87*10^-12; % unit: J^-1*m^3 +s11BTOs=8.33*10^-12; s12BTOs=-2.68*10^-12; s44BTOs=9.24*10^-12; % unit: J^-1*m^3 +tau_BT=(s11BTOs+2*s12BTOs)/(s11STOs+2*s12STOs); +delta_BT=(aBTO-aSTO)/aSTO; +%% BT +x=1; +deltaST=-x*delta_BT/((1-x)*tau_BT+(1+delta_BT)*x); +deltaBT=(1-x)*tau_BT*delta_BT/((1-x)*tau_BT+(1+delta_BT)*x); +a_BT=aBTO*x+aSTO*(1-x); +% a_BT=((1-x)*tau_BT*aSTO+x*aBTO)/((1-x)*tau_BT+x); +s_BT=[(aSTO-a_BT)/a_BT,(a_GSO-a_BT)/a_BT,(a_SSO-a_BT)/a_BT,(a_NSO-a_BT)/a_BT]'*100; +% s_BT=[(a_GSO-a_BT)/a_GSO,(a_SSO-a_BT)/a_SSO,(a_NSO-a_BT)/a_NSO]'*100; +%% BST80/20 +x=0.8; +deltaST=-x*delta_BT/((1-x)*tau_BT+(1+delta_BT)*x); +deltaBT=(1-x)*tau_BT*delta_BT/((1-x)*tau_BT+(1+delta_BT)*x); +a_BST_80_20=aBTO*x+aSTO*(1-x); +% a_BST_80_20=((1-x)*tau_BT*aSTO+x*aBTO)/((1-x)*tau_BT+x); +s_BST_80_20=[(aSTO-a_BST_80_20)/a_BST_80_20,(a_GSO-a_BST_80_20)/a_BST_80_20,(a_SSO-a_BST_80_20)/a_BST_80_20,(a_NSO-a_BST_80_20)/a_BST_80_20]'*100; +% s_BST_80_20=[(a_GSO-a_BST_80_20)/a_GSO,(a_SSO-a_BST_80_20)/a_SSO,(a_NSO-a_BST_80_20)/a_NSO]'*100; +%% BST70/30 +x=0.7; +deltaST=-x*delta_BT/((1-x)*tau_BT+(1+delta_BT)*x); +deltaBT=(1-x)*tau_BT*delta_BT/((1-x)*tau_BT+(1+delta_BT)*x); +a_BST_70_30=aBTO*x+aSTO*(1-x); +% a_BST_70_30=((1-x)*tau_BT*aSTO+x*aBTO)/((1-x)*tau_BT+x); +s_BST_70_30=[(aSTO-a_BST_70_30)/a_BST_70_30,(a_GSO-a_BST_70_30)/a_BST_70_30,(a_SSO-a_BST_70_30)/a_BST_70_30,(a_NSO-a_BST_70_30)/a_BST_70_30]'*100; +% s_BST_70_30=[(a_GSO-a_BST_70_30)/a_GSO,(a_SSO-a_BST_70_30)/a_SSO,(a_NSO-a_BST_70_30)/a_NSO]'*100; +%% BST60/40 +x=0.6; +deltaST=-x*delta_BT/((1-x)*tau_BT+(1+delta_BT)*x); +deltaBT=(1-x)*tau_BT*delta_BT/((1-x)*tau_BT+(1+delta_BT)*x); +a_BST_60_40=aBTO*x+aSTO*(1-x); +% a_BST_60_40=((1-x)*tau_BT*aSTO+x*aBTO)/((1-x)*tau_BT+x); +s_BST_60_40=[(aSTO-a_BST_60_40)/a_BST_60_40,(a_GSO-a_BST_60_40)/a_BST_60_40,(a_SSO-a_BST_60_40)/a_BST_60_40,(a_NSO-a_BST_60_40)/a_BST_60_40]'*100; +% s_BST_60_40=[(a_GSO-a_BST_60_40)/a_GSO,(a_SSO-a_BST_60_40)/a_SSO,(a_NSO-a_BST_60_40)/a_NSO]'*100; +%% PT family +aPTO=3.97; aSTO=3.905; +s11STOs=3.52*10^-12; s12STOs=-0.85*10^-12; s44STOs=7.87*10^-12; % unit: J^-1*m^3 +s11PTOs=8.0*10^-12; s12PTOs=-2.5*10^-12; s44PTOs=9*10^-12; % unit: J*m^3*C^-2 +tau_PT=(s11PTOs+2*s12PTOs)/(s11STOs+2*s12STOs); +delta_PT=(aPTO-aSTO)/aSTO; +%% PT +x=1; +deltaST=-x*delta_PT/((1-x)*tau_PT+(1+delta_PT)*x); +deltaPT=(1-x)*tau_PT*delta_PT/((1-x)*tau_PT+(1+delta_PT)*x); +% a_PST_65_35=aPTO*x+aSTO*(1-x); +a_PT=((1-x)*tau_PT*aSTO+x*aPTO)/((1-x)*tau_PT+x); +s_PT=[(a_DSO-a_PT)/a_PT,(a_TSO-a_PT)/a_PT,(a_GSO-a_PT)/a_PT,(a_SSO-a_PT)/a_PT,(a_NSO-a_PT)/a_PT]'*100; +% s_PT=[(a_DSO-a_PT)/a_DSO,(a_TSO-a_PT)/a_TSO,(a_GSO-a_PT)/a_GSO,(a_SSO-a_PT)/a_SSO,(a_NSO-a_PT)/a_NSO]'*100; +%% PST65/35 +x=0.65; +deltaST=-x*delta_PT/((1-x)*tau_PT+(1+delta_PT)*x); +deltaPT=(1-x)*tau_PT*delta_PT/((1-x)*tau_PT+(1+delta_PT)*x); +% a_PST_65_35=aPTO*x+aSTO*(1-x); +a_PST_65_35=((1-x)*tau_PT*aSTO+x*aPTO)/((1-x)*tau_PT+x); +s_PST_65_35=[(a_DSO-a_PST_65_35)/a_PST_65_35,(a_GSO-a_PST_65_35)/a_PST_65_35,(a_SSO-a_PST_65_35)/a_PST_65_35,(a_NSO-a_PST_65_35)/a_PST_65_35]'*100; +% s_PST_65_35=[(a_DSO-a_PST_65_35)/a_DSO,(a_GSO-a_PST_65_35)/a_GSO,(a_SSO-a_PST_65_35)/a_SSO,(a_NSO-a_PST_65_35)/a_NSO]'*100;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Pretty.m",".m","323","8","Render3D +dx = x_axis(2) - x_axis(1); +dy = y_axis(2) - y_axis(1); +dz = z_axis(2) - z_axis(1); + +axis([min(x_axis)*1e9, max(x_axis)*1e9, min(y_axis)*1e9, max(y_axis)*1e9,... + min(z_axis)*1e9, (min(z_axis)+(max(x_axis)-min(x_axis)))*1e9]); +set(gca,'xtick',[]);set(gca,'ytick',[]);set(gca,'ztick',[]);set(gca,'Visible','off')","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/freezeColors.m",".m","9815","276","function freezeColors(varargin) +% freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3) +% +% Problem: There is only one colormap per figure. This function provides +% an easy solution when plots using different colomaps are desired +% in the same figure. +% +% freezeColors freezes the colors of graphics objects in the current axis so +% that subsequent changes to the colormap (or caxis) will not change the +% colors of these objects. freezeColors works on any graphics object +% with CData in indexed-color mode: surfaces, images, scattergroups, +% bargroups, patches, etc. It works by converting CData to true-color rgb +% based on the colormap active at the time freezeColors is called. +% +% The original indexed color data is saved, and can be restored using +% unfreezeColors, making the plot once again subject to the colormap and +% caxis. +% +% +% Usage: +% freezeColors applies to all objects in current axis (gca), +% freezeColors(axh) same, but works on axis axh. +% +% Example: +% subplot(2,1,1); imagesc(X); colormap hot; freezeColors +% subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc... +% +% Note: colorbars must also be frozen. Due to Matlab 'improvements' this can +% no longer be done with freezeColors. Instead, please +% use the function CBFREEZE by Carlos Adrian Vargas Aguilera +% that can be downloaded from the MATLAB File Exchange +% (http://www.mathworks.com/matlabcentral/fileexchange/24371) +% +% h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar) +% +% For additional examples, see test/test_main.m +% +% Side effect on render mode: freezeColors does not work with the painters +% renderer, because Matlab doesn't support rgb color data in +% painters mode. If the current renderer is painters, freezeColors +% changes it to zbuffer. This may have unexpected effects on other aspects +% of your plots. +% +% See also unfreezeColors, freezeColors_pub.html, cbfreeze. +% +% +% John Iversen (iversen@nsi.edu) 3/23/05 +% + +% Changes: +% JRI (iversen@nsi.edu) 4/19/06 Correctly handles scaled integer cdata +% JRI 9/1/06 should now handle all objects with cdata: images, surfaces, +% scatterplots. (v 2.1) +% JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded) +% JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3) +% JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it. +% JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf) +% JRI 4/7/10 Change documentation for colorbars + +% Hidden option for NaN colors: +% Missing data are often represented by NaN in the indexed color +% data, which renders transparently. This transparency will be preserved +% when freezing colors. If instead you wish such gaps to be filled with +% a real color, add 'nancolor',[r g b] to the end of the arguments. E.g. +% freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]), +% where [r g b] is a color vector. This works on images & pcolor, but not on +% surfaces. +% Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes +% attributed in the code. + +% Free for all uses, but please retain the following: +% Original Author: +% John Iversen, 2005-10 +% john_iversen@post.harvard.edu + +appdatacode = 'JRI__freezeColorsData'; + +[h, nancolor] = checkArgs(varargin); + +%gather all children with scaled or indexed CData +cdatah = getCDataHandles(h); + +%current colormap +cmap = colormap; +nColors = size(cmap,1); +cax = caxis; + +% convert object color indexes into colormap to true-color data using +% current colormap +for hh = cdatah', + g = get(hh); + + %preserve parent axis clim + parentAx = getParentAxes(hh); + originalClim = get(parentAx, 'clim'); + + % Note: Special handling of patches: For some reason, setting + % cdata on patches created by bar() yields an error, + % so instead we'll set facevertexcdata instead for patches. + if ~strcmp(g.Type,'patch'), + cdata = g.CData; + else + cdata = g.FaceVertexCData; + end + + %get cdata mapping (most objects (except scattergroup) have it) + if isfield(g,'CDataMapping'), + scalemode = g.CDataMapping; + else + scalemode = 'scaled'; + end + + %save original indexed data for use with unfreezeColors + siz = size(cdata); + setappdata(hh, appdatacode, {cdata scalemode}); + + %convert cdata to indexes into colormap + if strcmp(scalemode,'scaled'), + %4/19/06 JRI, Accommodate scaled display of integer cdata: + % in MATLAB, uint * double = uint, so must coerce cdata to double + % Thanks to O Yamashita for pointing this need out + idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors); + else %direct mapping + idx = cdata; + %10/8/09 in case direct data is non-int (e.g. image;freezeColors) + % (Floor mimics how matlab converts data into colormap index.) + % Thanks to D Armyr for the catch + idx = floor(idx); + end + + %clamp to [1, nColors] + idx(idx<1) = 1; + idx(idx>nColors) = nColors; + + %handle nans in idx + nanmask = isnan(idx); + idx(nanmask)=1; %temporarily replace w/ a valid colormap index + + %make true-color data--using current colormap + realcolor = zeros(siz); + for i = 1:3, + c = cmap(idx,i); + c = reshape(c,siz); + c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified) + realcolor(:,:,i) = c; + end + + %apply new true-color color data + + %true-color is not supported in painters renderer, so switch out of that + if strcmp(get(gcf,'renderer'), 'painters'), + set(gcf,'renderer','zbuffer'); + end + + %replace original CData with true-color data + if ~strcmp(g.Type,'patch'), + set(hh,'CData',realcolor); + else + set(hh,'faceVertexCData',permute(realcolor,[1 3 2])) + end + + %restore clim (so colorbar will show correct limits) + if ~isempty(parentAx), + set(parentAx,'clim',originalClim) + end + +end %loop on indexed-color objects + + +% ============================================================================ % +% Local functions + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% getCDataHandles -- get handles of all descendents with indexed CData +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function hout = getCDataHandles(h) +% getCDataHandles Find all objects with indexed CData + +%recursively descend object tree, finding objects with indexed CData +% An exception: don't include children of objects that themselves have CData: +% for example, scattergroups are non-standard hggroups, with CData. Changing +% such a group's CData automatically changes the CData of its children, +% (as well as the children's handles), so there's no need to act on them. + +error(nargchk(1,1,nargin,'struct')) + +hout = []; +if isempty(h),return;end + +ch = get(h,'children'); +for hh = ch' + g = get(hh); + if isfield(g,'CData'), %does object have CData? + %is it indexed/scaled? + if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1, + hout = [hout; hh]; %#ok %yes, add to list + end + else %no CData, see if object has any interesting children + hout = [hout; getCDataHandles(hh)]; %#ok + end +end + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% getParentAxes -- return handle of axes object to which a given object belongs +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +function hAx = getParentAxes(h) +% getParentAxes Return enclosing axes of a given object (could be self) + +error(nargchk(1,1,nargin,'struct')) +%object itself may be an axis +if strcmp(get(h,'type'),'axes'), + hAx = h; + return +end + +parent = get(h,'parent'); +if (strcmp(get(parent,'type'), 'axes')), + hAx = parent; +else + hAx = getParentAxes(parent); +end + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% checkArgs -- Validate input arguments +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function [h, nancolor] = checkArgs(args) +% checkArgs Validate input arguments to freezeColors + +nargs = length(args); +error(nargchk(0,3,nargs,'struct')) + +%grab handle from first argument if we have an odd number of arguments +if mod(nargs,2), + h = args{1}; + if ~ishandle(h), + error('JRI:freezeColors:checkArgs:invalidHandle',... + 'The first argument must be a valid graphics handle (to an axis)') + end + % 4/2010 check if object to be frozen is a colorbar + if strcmp(get(h,'Tag'),'Colorbar'), + if ~exist('cbfreeze.m'), + warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',... + ['You seem to be attempting to freeze a colorbar. This no longer'... + 'works. Please read the help for freezeColors for the solution.']) + else + cbfreeze(h); + return + end + end + args{1} = []; + nargs = nargs-1; +else + h = gca; +end + +%set nancolor if that option was specified +nancolor = [nan nan nan]; +if nargs == 2, + if strcmpi(args{end-1},'nancolor'), + nancolor = args{end}; + if ~all(size(nancolor)==[1 3]), + error('JRI:freezeColors:checkArgs:badColorArgument',... + 'nancolor must be [r g b] vector'); + end + nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0; + else + error('JRI:freezeColors:checkArgs:unrecognizedOption',... + 'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1}) + end +end + + +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/CalcEigenstrains.m",".m","780","17","%% Eigenstrains +Eigenstrain_11 = Q11 * P1.^2 + Q12 .* (P2.^2 + P3.^2); +Eigenstrain_22 = Q11 * P2.^2 + Q12 .* (P1.^2 + P3.^2); +Eigenstrain_33 = Q11 * P3.^2 + Q12 .* (P1.^2 + P2.^2); +Eigenstrain_23 = q44 * P2 .* P3 / ( 2 * C44 ); +Eigenstrain_13 = q44 * P1 .* P3 / ( 2 * C44 ); +Eigenstrain_12 = q44 * P1 .* P2 / ( 2 * C44 ); +Eigenstrain_21 = Eigenstrain_12; Eigenstrain_31 = Eigenstrain_13; Eigenstrain_32 = Eigenstrain_23; + +Eigenstrain_11_k = fftn(Eigenstrain_11); +Eigenstrain_22_k = fftn(Eigenstrain_22); +Eigenstrain_33_k = fftn(Eigenstrain_33); +Eigenstrain_23_k = fftn(Eigenstrain_23); +Eigenstrain_13_k = fftn(Eigenstrain_13); +Eigenstrain_12_k = fftn(Eigenstrain_12); +Eigenstrain_21_k = Eigenstrain_12_k; Eigenstrain_31_k = Eigenstrain_13_k; Eigenstrain_32_k = Eigenstrain_23_k; +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/LandauEnergy.m",".m","1659","28","%% Landau Free Energy +f1_landau = ( P1 .* ( ... + 2 .* a1 + 4 .* a11 .* P1.^2 + 2 .* a12 .* ( P2.^2 + P3.^2 ) + ... + 6 .* a111 .* P1.^4 + 2 .* a112 .* ( P2.^4 + P3.^4 + 2 .* P1.^2 .* ( P2.^2 + P3.^2 ) ) + ... + 2 .* a123 .* P2.^2 .* P3.^2 + ... + 8 .* a1111 .* P1.^6 + 2 .* a1112.* ( P2.^6 + P3.^6 + 3 .* P1.^4 .* ( P2.^2 + P3.^2 ) ) + ... + 4 .* a1122 .* P1.^2 .* ( P2.^4 + P3.^4 ) + ... + 2 .* a1123 .* ( 2 .* P1.^2 .* P2.^2 .* P3.^2 + P2.^2 .* P3.^2 .* ( P2.^2 + P3.^2 ) ) ) ) .* in_film .* Nucleation_Sites; + +f2_landau = ( P2 .* ( ... + 2 .* a1 + 4 .* a11 .* P2.^2 + 2 .* a12 .* ( P3.^2 + P1.^2 ) + ... + 6 .* a111 .* P2.^4 + 2 .* a112 .* ( P3.^4 + P1.^4 + 2 .* P2.^2 .* ( P3.^2 + P1.^2 ) ) + ... + 2 .* a123 .* P3.^2 .* P1.^2 + ... + 8 .* a1111 .* P2.^6 + 2 .* a1112.* ( P3.^6 + P1.^6 + 3 .* P2.^4 .* ( P3.^2 + P1.^2 ) ) + ... + 4 .* a1122 .* P2.^2 .* ( P3.^4 + P1.^4 ) + ... + 2 .* a1123 .* ( 2 .* P2.^2 .* P3.^2 .* P1.^2 + P3.^2 .* P1.^2 .* ( P3.^2 + P1.^2 ) ) ) ) .* in_film .* Nucleation_Sites; + +f3_landau = ( P3 .* ( ... + 2 .* a1 + 4 .* a11 .* P3.^2 + 2 .* a12 .* ( P1.^2 + P2.^2 ) + ... + 6 .* a111 .* P3.^4 + 2 .* a112 .* ( P1.^4 + P2.^4 + 2 .* P3.^2 .* ( P1.^2 + P2.^2 ) ) + ... + 2 .* a123 .* P1.^2 .* P2.^2 + ... + 8 .* a1111 .* P3.^6 + 2 .* a1112.* ( P1.^6 + P2.^6 + 3 .* P3.^4 .* ( P1.^2 + P2.^2 ) ) + ... + 4 .* a1122 .* P3.^2 .* ( P1.^4 + P2.^4 ) + ... + 2 .* a1123 .* ( 2 .* P3.^2 .* P1.^2 .* P2.^2 + P1.^2 .* P2.^2 .* ( P1.^2 + P2.^2 ) ) ) ) .* in_film .* Nucleation_Sites; + +f1_landau_2Dk = fft_2d_slices(f1_landau); +f2_landau_2Dk = fft_2d_slices(f2_landau); +f3_landau_2Dk = fft_2d_slices(f3_landau);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/CalculateStrain.m",".m","1398","49","if(HET_ELASTIC_RELAX) + EigenstrainInFilm; + InfinitePlate; +else % Don't do heterogenous strain relaxation + u_1_A = 0; + u_2_A = 0; + u_3_A = 0; + + u_1_B = 0; + u_2_B = 0; + u_3_B = 0; + + e_11_A = 0; + e_22_A = 0; + e_33_A = 0; + e_12_A = 0; + e_13_A = 0; + e_23_A = 0; + + e_11_B = 0; + e_22_B = 0; + e_33_B = 0; + e_12_B = 0; + e_13_B = 0; + e_23_B = 0; +end + +% e_11_A + e_11_B = TotalStrain_het_11 +% TotalStrain_het_11 = e_11_A + e_11_B; +% TotalStrain_het_22 = e_22_A + e_22_B; +% TotalStrain_het_33 = e_33_A + e_33_B; +% TotalStrain_het_12 = e_12_A + e_12_B; +% TotalStrain_het_13 = e_13_A + e_13_B; +% TotalStrain_het_23 = e_23_A + e_23_B; +% TotalStrain_het_21 = TotalStrain_12_het; +% TotalStrain_het_31 = TotalStrain_13_het; +% TotalStrain_het_32 = TotalStrain_23_het; + + +u_1 = u_1_A + u_1_B; u_2 = u_2_A + u_2_B; u_3 = u_3_A + u_3_B; +TotalStrain_11 = e_11_A + e_11_B + TotalStrain_homo_11(P1,P2,P3); +TotalStrain_22 = e_22_A + e_22_B + TotalStrain_homo_22(P1,P2,P3); +TotalStrain_33 = e_33_A + e_33_B + TotalStrain_homo_33(P1,P2,P3); +TotalStrain_23 = e_23_A + e_23_B + TotalStrain_homo_23(P1,P2,P3); +TotalStrain_13 = e_13_A + e_13_B + TotalStrain_homo_13(P1,P2,P3); +TotalStrain_12 = e_12_A + e_12_B + TotalStrain_homo_12(P1,P2,P3); +TotalStrain_32 = TotalStrain_23; +TotalStrain_21 = TotalStrain_12; +TotalStrain_31 = TotalStrain_13;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Hysteresis.m",".m","2644","116","%% Nucleation sites, have 0 free energy change... +Setup + +% Nucleation_Sites = +(rand(Nx,Ny,Nz) < (1-0.01)) .* in_film; +L = 5; +Nucleation_Sites = ones(Nx,Ny,Nz); +xy_edges = 8; +z_edges = 2; +for i = 1 : 7 + Nucleation_Sites(randi([xy_edges,Nx-L+1-xy_edges])+(0:L-1),randi([xy_edges,Ny-L+1-xy_edges])+(0:L-1),randi([z_edges,Nz-L+1-z_edges])+(0:L-1)) = 0; +end + +% Percent of nucleation sites +Nucleation_pct = abs(sum(sum(sum(Nucleation_Sites-1)))/(Nx*Ny*(film_index-interface_index+1))); + +%% Hysteresis Loops + +% Run 0 kV/cm + +% +Load = 1; +E_fields_tot = [0, 1e2, 1e3, 1e4, 1e5, 5e5, 1e6, 2e6, 3e6, 4e6, 5e6, 6e6, 7e6, 8e6, 9e6, 1e7]; +E_vectors = []; +P_vectors = []; + +%% +E_fields = E_fields_tot(2:end); + +for E_1_applied = E_fields + + folder = sprintf('%gkV-cm',E_1_applied/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +%% +E_fields = E_fields_tot(1:end-1); +E_fields = fliplr(E_fields); + +for E_1_applied = E_fields + + folder = sprintf('%g_2kV-cm',E_1_applied/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +%% +E_fields = -E_fields_tot(2:end); + +for E_1_applied = E_fields + + folder = sprintf('%gkV-cm',E_1_applied/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +%% +E_fields = -E_fields_tot(1:end-1); +E_fields = fliplr(E_fields); + +for E_1_applied = E_fields + + folder = sprintf('%g_2kV-cm',E_1_applied/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +save('PE','P_vectors','E_vectors');","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Nucleate.m",".m","562","16","%% Nucleation sites, have 0 free energy change... +% Nucleation_Sites = +(rand(Nx,Ny,Nz) < (1-0.01)) .* in_film; +if( NUCLEATE ) + L = 5; + Nucleation_Sites = ones(Nx,Ny,Nz); + xy_edges = 8; + z_edges = 2; + for i = 1 : 7 + Nucleation_Sites(randi([xy_edges,Nx-L+1-xy_edges])+(0:L-1),randi([xy_edges,Ny-L+1-xy_edges])+(0:L-1),randi([z_edges,Nz-L+1-z_edges])+(0:L-1)) = 0; + end + + % Percent of nucleation sites + Nucleation_pct = abs(sum(sum(sum(Nucleation_Sites-1)))/(Nx*Ny*(film_index-interface_index+1))); +else + Nucleation_Sites = 1; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/InfinitePlateSetup_vpa.m",".m","3850","92","U = zeros(3,3); +m = [0, 0, 1]; +for i_ind = 1 : 3 +for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + U(i_ind,k_ind) = U(i_ind,k_ind) + C(i_ind,j_ind,k_ind,l_ind) * m(j_ind) * m(l_ind); + end + end +end +end + +R = zeros(Nx,Ny,3,3); W = zeros(numel(kx),numel(ky),3,3); +eigenvec_mat = zeros(Nx,Ny,6,6); % the eigenvalues and eigenvectors found at each k vector pt +eigenval_mat = zeros(Nx,Ny,6); % the eigenvalues and eigenvectors found at each k vector pt +mat_mat = zeros(numel(kx),numel(ky),6,6); + +for k1_ind = 1 : numel(kx) +for k2_ind = 1 : numel(ky) + + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Origin, different solution, be mindful of dividing by k vector as well! + + n = [ kx_grid_2D(k1_ind,k2_ind), ky_grid_2D(k1_ind,k2_ind), 0 ] ./ sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ) ; + + for i_ind = 1 : 3 + for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + R(k1_ind,k2_ind,i_ind,k_ind) = R(k1_ind,k2_ind,i_ind,k_ind) + C(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * m(l_ind); + W(k1_ind,k2_ind,i_ind,k_ind) = W(k1_ind,k2_ind,i_ind,k_ind) + C(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * n(l_ind); + end + end + end + end + + R_mat = squeeze(R(k1_ind,k2_ind,:,:)); + W_mat = squeeze(W(k1_ind,k2_ind,:,:)); + + + N1 = -inv(U)*R_mat'; N2 = inv(U); N3 = R_mat*inv(U)*R_mat'-W_mat; + mat = [N1, N2; N3, N1']; + vpa_mat = vpa(mat); + + [eigenvec, eigenval] = eig(vpa_mat); + eigenvec = double(eigenvec); + eigenval = diag(double(eigenval)); + + mat_mat(k1_ind,k2_ind,:,:) = mat; + eigenvec_mat(k1_ind,k2_ind,:,:) = eigenvec; + eigenval_mat(k1_ind,k2_ind,:) = eigenval; + + end +end +end + +%% BC matrix solutions +bc_mats = zeros(Nx,Ny,6,6); +strain_bc_mats_inv = zeros(Nx,Ny,6,6); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Because we divide by K^2 to make matrices better + K = sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ); + bc_mat = zeros(6,6); + % [ d1 * eigenvec(1,1) + d2 * eigenvec(1,2) + + % d1 * eigenvec(2,1) + d2 * eigenvec(2,2) + + % d1 * eigenvec(3,1) + d2 * eigenvec(3,2) + + % d1 * eigenvec(4,1) + d2 * eigenvec(4,2) + + for m = 1 : 6 % the eigenvalue -> column of eigenvec_mat ~ eigenvector + for k_ind = 1 : 3 % eigenvector a, scale by K + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_sub*1i*K); + end + % rescale by K^-1 to avoid conditioning errors... need to rescale + % the given value as well! + for k_ind = 4 : 6 % eigenvector b + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_film*1i*K) * 1i * K / K^2; + end + end + bc_mats(k1_ind,k2_ind,:,:) = bc_mat; + + vpa_mat = vpa(bc_mat); + strain_bc_mats_inv(k1_ind,k2_ind,:,:) = double(inv(vpa_mat)); + end +end +end + +strain_bc_mat_inv_korigin = double( inv( vpa([ h_sub 1 0 0 0 0 ; ... + 0 0 h_sub 1 0 0 ; ... + 0 0 0 0 h_sub 1 ; ... + C(1,3,1,3) 0 C(1,3,2,3) 0 C(1,3,3,3) 0 ; ... + C(2,3,1,3) 0 C(2,3,2,3) 0 C(2,3,3,3) 0 ; ... + C(3,3,1,3) 0 C(3,3,2,3) 0 C(3,3,3,3) 0 ]) ) );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/InfinitePlateSetup.m",".m","3464","87","U = zeros(3,3); +m = [0, 0, 1]; +for i_ind = 1 : 3 +for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + U(i_ind,k_ind) = U(i_ind,k_ind) + C(i_ind,j_ind,k_ind,l_ind) * m(j_ind) * m(l_ind); + end + end +end +end + +R = zeros(Nx,Ny,3,3); W = zeros(numel(kx),numel(ky),3,3); +eigenvec_mat = zeros(Nx,Ny,6,6); % the eigenvalues and eigenvectors found at each k vector pt +eigenval_mat = zeros(Nx,Ny,6); % the eigenvalues and eigenvectors found at each k vector pt +mat_mat = zeros(numel(kx),numel(ky),6,6); + +for k1_ind = 1 : numel(kx) +for k2_ind = 1 : numel(ky) + + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Origin, different solution, be mindful of dividing by k vector as well! + + n = [ kx_grid_2D(k1_ind,k2_ind), ky_grid_2D(k1_ind,k2_ind), 0 ] ./ sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ) ; + + for i_ind = 1 : 3 + for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + R(k1_ind,k2_ind,i_ind,k_ind) = R(k1_ind,k2_ind,i_ind,k_ind) + C(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * m(l_ind); + W(k1_ind,k2_ind,i_ind,k_ind) = W(k1_ind,k2_ind,i_ind,k_ind) + C(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * n(l_ind); + end + end + end + end + + R_mat = squeeze(R(k1_ind,k2_ind,:,:)); + W_mat = squeeze(W(k1_ind,k2_ind,:,:)); + + + N1 = -inv(U)*R_mat'; N2 = inv(U); N3 = R_mat*inv(U)*R_mat'-W_mat; + mat = [N1, N2; N3, N1']; + + [eigenvec, eigenval] = eig(mat,'vector'); + + mat_mat(k1_ind,k2_ind,:,:) = mat; + eigenvec_mat(k1_ind,k2_ind,:,:) = eigenvec; + eigenval_mat(k1_ind,k2_ind,:) = eigenval; + + end +end +end + +%% BC matrix solutions +bc_mats = zeros(Nx,Ny,6,6); +strain_bc_mats_inv = zeros(Nx,Ny,6,6); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Because we divide by K^2 to make matrices better + K = sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ); + bc_mat = zeros(6,6); + % [ d1 * eigenvec(1,1) + d2 * eigenvec(1,2) + + % d1 * eigenvec(2,1) + d2 * eigenvec(2,2) + + % d1 * eigenvec(3,1) + d2 * eigenvec(3,2) + + % d1 * eigenvec(4,1) + d2 * eigenvec(4,2) + + for m = 1 : 6 % the eigenvalue -> column of eigenvec_mat ~ eigenvector + for k_ind = 1 : 3 % eigenvector a, scale by K + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_sub*1i*K); + end + % rescale by K^-1 to avoid conditioning errors... need to rescale + % the given value as well! + for k_ind = 4 : 6 % eigenvector b + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_film*1i*K) * 1i * K / K^2; + end + end + bc_mats(k1_ind,k2_ind,:,:) = bc_mat; + strain_bc_mats_inv(k1_ind,k2_ind,:,:) = inv(bc_mat); + end +end +end + +strain_bc_mat_inv_korigin = inv([ h_sub 1 0 0 0 0 ; ... + 0 0 h_sub 1 0 0 ; ... + 0 0 0 0 h_sub 1 ; ... + C(1,3,1,3) 0 C(1,3,2,3) 0 C(1,3,3,3) 0 ; ... + C(2,3,1,3) 0 C(2,3,2,3) 0 C(2,3,3,3) 0 ; ... + C(3,3,1,3) 0 C(3,3,2,3) 0 C(3,3,3,3) 0 ]);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/finite_diff_x3_second_der.m",".m","528","16","function out = finite_diff_x3_second_der( mat, dz ) + + [~,~,Nz] = size(mat); + out = mat; + + for i = 2 : Nz - 1 + out(:,:,i) = (1/dz^2) * (mat(:,:,i+1) - 2*mat(:,:,i) + mat(:,:,i-1)); + end + + out(:,:,1) = (mat(:,:,2) - mat(:,:,1)) / dz; % approx d/dx3 ~ forward difference + out(:,:,1) = (out(:,:,2) - out(:,:,1)) / dz; % approx d^2/dx3^2 ~ using another forward difference + + out(:,:,end) = (mat(:,:,end) - mat(:,:,end-1)) / dz; + out(:,:,end) = (out(:,:,end) - out(:,:,end-1)) / dz; + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Visualize.m",".m","1049","25","% subplot(2,3,1); +% surf(z_axis,y_axis,squeeze(P3(:,16,:))); shading interp; view(0,90); axis([min(z_axis) max(z_axis) min(y_axis) max(y_axis)]); colormap parula; +% xlabel('Y (m)'); ylabel('Z (m)'); colorbar +% freezeColors + +subplot(2,2,1); +surf(x_axis*1e9,y_axis*1e9,P3(:,:,film_index)); shading interp; view(0,90); +axis([min(x_axis)*1e9 max(x_axis)*1e9 min(y_axis)*1e9 max(y_axis)*1e9]); colormap parula; +% xlabel('X (m)'); ylabel('Y (m)'); +freezeColors + +subplot(2,2,2); +angle = atan2(P2,P1); surf(x_axis*1e9,y_axis*1e9,angle(:,:,film_index)); view(0,90); colormap hsv; shading interp; +axis([min(x_axis)*1e9 max(x_axis)*1e9 min(y_axis)*1e9 max(y_axis)*1e9]); +caxis([-pi pi]); +% xlabel('X (m)'); ylabel('Y (m)'); +freezeColors + +subplot(2,2,3); +semilogy(errors(1:c)); + +subplot(2,2,4); +% Visualize_3D(P1,P2,P3,x_grid*1e9,y_grid*1e9,z_grid*1e9,interface_index,film_index,Nx,Ny,Nz) +surf(z_axis*1e9,y_axis*1e9,squeeze(P1(:,1,:))); colormap parula; shading interp; view(0,90); +axis([min(z_axis)*1e9 max(z_axis)*1e9 min(y_axis)*1e9 max(y_axis)*1e9]); ","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/InitP.m",".m","370","12","% Initial Conditions +if( LOAD ) + load('init.mat','P1','P2','P3'); +else + RandomP; +end + +% Thin film simulation +P1(:,:,1:sub_index) = 0; P2(:,:,1:sub_index) = 0; P3(:,:,1:sub_index) = 0; +P1(:,:,film_index+1:end) = 0; P2(:,:,film_index+1:end) = 0; P3(:,:,film_index+1:end) = 0; + +P1_2Dk = fft_2d_slices( P1 ); P2_2Dk = fft_2d_slices( P2 ); P3_2Dk = fft_2d_slices( P3 );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/fft_2d_slices.m",".m","160","12","function out = fft_2d_slices( mat ) + + out = mat; + [~, ~, z] = size(mat); + + for i = 1 : z + + out(:,:,i) = fft2(squeeze(mat(:,:,i))); + + end + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/ExternalEFieldEnergy.m",".m","307","9","%% External field +f1_ext_E = -E_1_applied .* in_film .* Nucleation_Sites; +f2_ext_E = -E_2_applied .* in_film .* Nucleation_Sites; +f3_ext_E = -E_3_applied .* in_film .* Nucleation_Sites; + +f1_ext_E_2Dk = fft_2d_slices(f1_ext_E); +f2_ext_E_2Dk = fft_2d_slices(f2_ext_E); +f3_ext_E_2Dk = fft_2d_slices(f3_ext_E); +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/ifft_2d_slices.m",".m","168","12","function out = ifft_2d_slices( mat ) + + out = mat; + [~, ~, z] = size(mat); + + for i = 1 : z + + out(:,:,i) = real(ifft2(squeeze(mat(:,:,i)))); + + end + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/InfinitePlate.m",".m","6198","147","%% Application of Boundary Conditions +% bc in real space +% bc applied on the top surface in k space +% Eigenstrain_11 = Q11 * P1.^2 + Q12 .* (P2.^2 + P3.^2); +% Eigenstrain_22 = Q11 * P2.^2 + Q12 .* (P1.^2 + P3.^2); +% Eigenstrain_33 = Q11 * P3.^2 + Q12 .* (P1.^2 + P2.^2); +% Eigenstrain_23 = Q44 * P2 .* P3; +% Eigenstrain_13 = Q44 * P1 .* P3; +% Eigenstrain_12 = Q44 * P1 .* P2; +% Eigenstrain_21 = Eigenstrain_12; Eigenstrain_31 = Eigenstrain_13; Eigenstrain_32 = Eigenstrain_23; +% +% Eigenstrain_11_k = fftn(Eigenstrain_11); +% Eigenstrain_22_k = fftn(Eigenstrain_22); +% Eigenstrain_33_k = fftn(Eigenstrain_33); +% Eigenstrain_23_k = fftn(Eigenstrain_23); +% Eigenstrain_13_k = fftn(Eigenstrain_13); +% Eigenstrain_12_k = fftn(Eigenstrain_12); +% Eigenstrain_21_k = Eigenstrain_12_k; Eigenstrain_31_k = Eigenstrain_13_k; Eigenstrain_32_k = Eigenstrain_23_k; + +% 3D fft diff.. +bc_film_1_3Dk = C44.*(Eigenstrain_13_k - kx_grid_3D.*u_3_A_k.*1i) + C44.*(Eigenstrain_13_k - kz_grid_3D.*u_1_A_k.*1i); +bc_film_2_3Dk = C44.*(Eigenstrain_23_k - ky_grid_3D.*u_3_A_k.*1i) + C44.*(Eigenstrain_23_k - kz_grid_3D.*u_2_A_k.*1i); +bc_film_3_3Dk = C12.*(Eigenstrain_11_k - kx_grid_3D.*u_1_A_k.*1i) + C12.*(Eigenstrain_22_k - ky_grid_3D.*u_2_A_k.*1i) + C11.*(Eigenstrain_33_k - kz_grid_3D.*u_3_A_k.*1i); + +% real space bc +% bc applied on the top surface (surface of the film) in real space +bc_film_1 = real(ifftn(squeeze(bc_film_1_3Dk))); +bc_film_2 = real(ifftn(squeeze(bc_film_2_3Dk))); +bc_film_3 = real(ifftn(squeeze(bc_film_3_3Dk))); + +bc_film_1 = squeeze(bc_film_1(:,:,film_index)); +bc_film_2 = squeeze(bc_film_2(:,:,film_index)); +bc_film_3 = squeeze(bc_film_3(:,:,film_index)); + +% Strain free substrate +bc_sub_1 = -squeeze(u_1_A(:,:,1)); +bc_sub_2 = -squeeze(u_2_A(:,:,1)); +bc_sub_3 = -squeeze(u_3_A(:,:,1)); + +%% fft2 the bc +bc_film_1_2Dk = fft2(bc_film_1); +bc_film_2_2Dk = fft2(bc_film_2); +bc_film_3_2Dk = fft2(bc_film_3); + +% Orders of magnitude larger... so let's make the matrix better to work with +rescaling_mat = sqrt( kx_grid_2D.^2 + ky_grid_2D.^2 ).^2; +rescaling_mat(1,1) = 1; +bc_film_1_2Dk = bc_film_1_2Dk ./ rescaling_mat; +bc_film_2_2Dk = bc_film_2_2Dk ./ rescaling_mat; +bc_film_3_2Dk = bc_film_3_2Dk ./ rescaling_mat; + +bc_sub_1_2Dk = fft2(bc_sub_1); +bc_sub_2_2Dk = fft2(bc_sub_2); +bc_sub_3_2Dk = fft2(bc_sub_3); + +bc_given_k_space = cat(4,bc_sub_1_2Dk,bc_sub_2_2Dk,bc_sub_3_2Dk,bc_film_1_2Dk,bc_film_2_2Dk,bc_film_3_2Dk); +d_sols = zeros(numel(kx),numel(ky),6); + +%% Apply the boundary conditions to get the solution to the diff. eq. +for k1 = 1 : Nx +for k2 = 1 : Ny + % Solve the matrix problem + d_sols(k1,k2,:) = squeeze(strain_bc_mats_inv(k1,k2,:,:)) * squeeze(bc_given_k_space(k1,k2,:)); +end +end + +%% Construct the solution in the 2D k-space, kx,ky,z +u_B_2Dk_mat = zeros(Nx,Ny,Nz,3); +u_B_2Dk_d3_mat = zeros(Nx,Ny,Nz,3); + +q_1 = squeeze(d_sols(:,:,1)); +q_2 = squeeze(d_sols(:,:,2)); +q_3 = squeeze(d_sols(:,:,3)); +q_4 = squeeze(d_sols(:,:,4)); +q_5 = squeeze(d_sols(:,:,5)); +q_6 = squeeze(d_sols(:,:,6)); + +p_1 = squeeze(eigenval_mat(:,:,1)); +p_2 = squeeze(eigenval_mat(:,:,2)); +p_3 = squeeze(eigenval_mat(:,:,3)); +p_4 = squeeze(eigenval_mat(:,:,4)); +p_5 = squeeze(eigenval_mat(:,:,5)); +p_6 = squeeze(eigenval_mat(:,:,6)); + +for l = 1 : 3 + for z_loop = 1 : numel(z_axis); + K = sqrt( kx_grid_2D.^2 + ky_grid_2D.^2 ); + + a_vec_1 = squeeze(eigenvec_mat(:,:,l,1)); + a_vec_2 = squeeze(eigenvec_mat(:,:,l,2)); + a_vec_3 = squeeze(eigenvec_mat(:,:,l,3)); + a_vec_4 = squeeze(eigenvec_mat(:,:,l,4)); + a_vec_5 = squeeze(eigenvec_mat(:,:,l,5)); + a_vec_6 = squeeze(eigenvec_mat(:,:,l,6)); + + u_B_2Dk_mat(:,:,z_loop,l) = q_1 .* a_vec_1 .* exp(p_1.*z_axis(z_loop).*1i.*K) + ... + q_2 .* a_vec_2 .* exp(p_2.*z_axis(z_loop).*1i.*K) + ... + q_3 .* a_vec_3 .* exp(p_3.*z_axis(z_loop).*1i.*K) + ... + q_4 .* a_vec_4 .* exp(p_4.*z_axis(z_loop).*1i.*K) + ... + q_5 .* a_vec_5 .* exp(p_5.*z_axis(z_loop).*1i.*K) + ... + q_6 .* a_vec_6 .* exp(p_6.*z_axis(z_loop).*1i.*K); + u_B_2Dk_d3_mat(:,:,z_loop,l) = ( q_1 .* a_vec_1 .* exp(p_1.*z_axis(z_loop).*1i.*K) .* p_1 + ... + q_2 .* a_vec_2 .* exp(p_2.*z_axis(z_loop).*1i.*K) .* p_2 + ... + q_3 .* a_vec_3 .* exp(p_3.*z_axis(z_loop).*1i.*K) .* p_3 + ... + q_4 .* a_vec_4 .* exp(p_4.*z_axis(z_loop).*1i.*K) .* p_4 + ... + q_5 .* a_vec_5 .* exp(p_5.*z_axis(z_loop).*1i.*K) .* p_5 + ... + q_6 .* a_vec_6 .* exp(p_6.*z_axis(z_loop).*1i.*K) .* p_6 ) .* 1i .* K; + end +end + +% 2D origin point... +d_sols(1,1,:) = strain_bc_mat_inv_korigin * squeeze(bc_given_k_space(1,1,:)); + +q = squeeze(d_sols(1,1,:)); +u_B_2Dk_mat(1,1,:,1) = q(1) * z_axis + q(2); +u_B_2Dk_mat(1,1,:,2) = q(3) * z_axis + q(4); +u_B_2Dk_mat(1,1,:,3) = q(5) * z_axis + q(6); +u_B_2Dk_d3_mat(1,1,:,1) = q(1); +u_B_2Dk_d3_mat(1,1,:,2) = q(3); +u_B_2Dk_d3_mat(1,1,:,3) = q(5); + +u_1_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,1)); +u_2_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,2)); +u_3_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,3)); +u_1_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,1)); +u_2_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,2)); +u_3_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,3)); + +%% Calculate the strains, e_ij = 0.5 * (u_i,j + u_j,i) +e_11_B_2Dk = u_1_B_2Dk .* 1i .* kx_grid_3D; +e_22_B_2Dk = u_2_B_2Dk .* 1i .* ky_grid_3D; +e_33_B_2Dk = u_3_B_2Dk_d3; +e_23_B_2Dk = 0.5 * (u_2_B_2Dk_d3 + 1i .* ky_grid_3D .* u_3_B_2Dk); +e_13_B_2Dk = 0.5 * (u_1_B_2Dk_d3 + 1i .* kx_grid_3D .* u_3_B_2Dk); +e_12_B_2Dk = 0.5 * (1i .* ky_grid_3D .* u_1_B_2Dk + 1i .* kx_grid_3D .* u_2_B_2Dk); + +%% Final outputs +u_1_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,1))); +u_2_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,2))); +u_3_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,3))); + +e_11_B = ifft_2d_slices(e_11_B_2Dk); +e_22_B = ifft_2d_slices(e_22_B_2Dk); +e_33_B = ifft_2d_slices(e_33_B_2Dk); +e_23_B = ifft_2d_slices(e_23_B_2Dk); +e_13_B = ifft_2d_slices(e_13_B_2Dk); +e_12_B = ifft_2d_slices(e_12_B_2Dk);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/NonRandomInit.m",".m","751","27","%% +RandomP; + +% Remember changing first variable is y axis!! +% P(y,x,z); + +P1(1:20,:,:) = P1(1:20,:,:) - 0.003; +P2(1:20,:,:) = P2(1:20,:,:) - 0.003; +P3(1:20,:,:) = P3(1:20,:,:) - 0.003; + +P1(21:44,:,:) = P1(21:44,:,:) + 0.0015; +P2(21:44,:,:) = P2(21:44,:,:) - 0.003; +P3(21:44,:,:) = P3(21:44,:,:) - 0.003; +P1(21:44,:,end-20:end) = P1(21:44,:,end-20:end) + 0.0015; +P1(21:44,:,end-15:end) = P1(21:44,:,end-15:end) + 0.0015; +P1(21:44,:,end-10:end) = P1(21:44,:,end-10:end) + 0.0015; +P1(21:44,:,end-5:end) = P1(21:44,:,end-5:end) + 0.0015; + +P1(45:end,:,:) = P1(45:end,:,:) - 0.003; +P2(45:end,:,:) = P2(45:end,:,:) - 0.003; +P3(45:end,:,:) = P3(45:end,:,:) - 0.003; + +P1 = P1 .* in_film; +P2 = P2 .* in_film; +P3 = P3 .* in_film; + +save('init.mat','P1','P2','P3');","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/CalcP.m",".m","303","10","% Calculate P within the film +P1_film = P1(:,:,interface_index:film_index); +P2_film = P2(:,:,interface_index:film_index); +P3_film = P3(:,:,interface_index:film_index); + +P1_val = vol_avg(abs(P1_film)) +P2_val = vol_avg(abs(P2_film)) +P3_val = vol_avg(abs(P3_film)) + +P_val = sqrt(P1_val^2+P2_val^2+P3_val^2)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/DomainPctCalc.m",".m","2913","74","%% For P1 ~ P2 ~ P3 within the domain +% Polar Angle +R = sqrt( P1.^2 + P2.^2 + P3.^2 ); +Theta = acos( P3 ./ R ); % -> [0,pi] +Phi = atan2( P2, P1 ); % -> [-pi,pi] + +threshold_P1 = 5e-2; % P1 ~ 0 +threshold_P2 = 5e-2; % P2 ~ 0 +threshold_P3 = 5e-2; % P3 ~ 0 + +total_el = sum(sum(sum( P1 ~= 0))); + +%% Tetragonal +a1 = ( abs(P1) > threshold_P1 ) & ( abs(P2) < threshold_P2 ) & ( abs(P3) < threshold_P3 ); +a2 = ( abs(P1) < threshold_P1 ) & ( abs(P2) > threshold_P2 ) & ( abs(P3) < threshold_P3 ); +c = ( abs(P1) < threshold_P1 ) & ( abs(P2) < threshold_P2 ) & ( abs(P3) > threshold_P3 ); + + +%% Orthorhombic +O12 = ( abs(P1) > threshold_P1 ) & ( abs(P2) > threshold_P2 ) & ( abs(P3) < threshold_P3 ); +O13 = ( abs(P1) > threshold_P1 ) & ( abs(P2) < threshold_P2 ) & ( abs(P3) > threshold_P3 ); +O23 = ( abs(P1) < threshold_P1 ) & ( abs(P2) > threshold_P2 ) & ( abs(P3) > threshold_P3 ); + + +%% Rhombohedral +r = ( abs(P1) > threshold_P1 ) & ( abs(P2) > threshold_P2 ) & ( abs(P3) > threshold_P3 ); + +%% Calc +a1_calc = sum(sum(sum(a1))) /total_el; +a2_calc = sum(sum(sum(a2))) /total_el; +c_calc = sum(sum(sum(c))) / total_el; + +O12_calc = sum(sum(sum(O12))) / total_el; +O13_calc = sum(sum(sum(O13))) / total_el; +O23_calc = sum(sum(sum(O23))) / total_el; + +r_calc = sum(sum(sum(r))) / total_el; + +Names = {'a1','a2','c','O12','O13','O23','r'} +Pcts = [a1_calc,a2_calc,c_calc,O12_calc,O13_calc,O23_calc,r_calc] +Avg_val = [ mean(mean(mean(abs(P1)))); mean(mean(mean(abs(P2)))); mean(mean(mean(abs(P3))))]' + + + +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Trash +% %% Tetragonal +% % a1/a2 domain, Theta ~pi/2 ; Phi ~ 0, pi/2, pi, -pi, -pi/2 +% a1_a2 = ( abs(Theta - (pi/2)) < threshold_angle ) & ... +% ( abs(abs(Phi) - pi) < threshold_angle | abs(abs(Phi) - (pi/2)) < threshold_angle ) ; +% +% % c domain, Theta ~0,pi ; Phi ~0 +% c = ( Theta < threshold_angle | abs(Theta - pi) < threshold_angle ) & ... +% ( abs(P1) < threshold_mag & abs(P2) < threshold_mag ); +% +% %% Orthorhombic +% % aa1/aa2 domain, Theta ~pi/2, Phi ~ pi/4, 3*pi/4, -pi/4, -3*pi/4 +% aa1_aa2 = ( abs(Theta - (pi/2)) < threshold_angle ) & ... +% ( abs(abs(Phi) - (pi/4)) < threshold_angle | abs(abs(Phi) - (3*pi/4)) < threshold_angle ) ; +% +% % P1 ~ P3, P2 ~ 0 +% % Theta ~ pi/4, 3pi/4 ; Phi ~ 0, pi +% a1_c = ( abs(Theta - (pi/4)) < threshold_angle | abs(Theta - (3*pi/4)) < threshold_angle ) & ... +% ( abs(Phi) < threshold_angle | abs(abs(Phi) - pi) < threshold_angle ); +% +% % P1 ~ 0, P2 ~ P3 +% % Theta ~ pi/4, 3pi/4 ; Phi ~ pi/2, 3pi/2 +% a2_c = ( abs(Theta - (pi/4)) < threshold_angle | abs(Theta - (3*pi/4)) < threshold_angle ) & ... +% ( abs(abs(Phi) - (pi/2)) < threshold_angle | abs(abs(Phi) - (3*pi/2)) < threshold_angle ); +% +% +% %% Rhombohedral +% r = ( abs(Theta - (pi/6)) < threshold_angle | abs(Theta - (5*pi/6)) < threshold_angle ) & ... +% ( abs(abs(Phi) - (pi/4)) < threshold_angle | abs(abs(Phi) - (3*pi/4)) + threshold_angle );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/finite_diff_x3_first_der.m",".m","389","14","function out = finite_diff_x3_first_der( mat, dz ) + + [~,~,Nz] = size(mat); + out = mat; + + for i = 2 : Nz - 1 + out(:,:,i) = (1/dz) * ( (-1/2) * mat(:,:,i-1) + (1/2) * mat(:,:,i+1) ); + end + + % approximate endpoints using forward difference + out(:,:,1) = ( mat(:,:,2) - mat(:,:,1) ) / dz; + out(:,:,end) = ( mat(:,:,end) - mat(:,:,end-1) ) / dz; + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Isotropic/InfinitePlateIsotropic.m",".m","5340","129","%% Application of Boundary Conditions +% 3D fft diff.. +bc_film_1_3Dk = C44.*(Eigenstrain_13_k - kx_grid_3D.*u_3_A_k.*1i) + C44.*(Eigenstrain_13_k - kz_grid_3D.*u_1_A_k.*1i); +bc_film_2_3Dk = C44.*(Eigenstrain_23_k - ky_grid_3D.*u_3_A_k.*1i) + C44.*(Eigenstrain_23_k - kz_grid_3D.*u_2_A_k.*1i); +bc_film_3_3Dk = C12.*(Eigenstrain_11_k - kx_grid_3D.*u_1_A_k.*1i) + C12.*(Eigenstrain_22_k - ky_grid_3D.*u_2_A_k.*1i) + C11.*(Eigenstrain_33_k - kz_grid_3D.*u_3_A_k.*1i); + +% real space bc +% bc applied on the top surface in real space +bc_film_1 = real(ifftn(squeeze(bc_film_1_3Dk))); +bc_film_2 = real(ifftn(squeeze(bc_film_2_3Dk))); +bc_film_3 = real(ifftn(squeeze(bc_film_3_3Dk))); + +bc_film_1 = squeeze(bc_film_1(:,:,end)); +bc_film_2 = squeeze(bc_film_2(:,:,end)); +bc_film_3 = squeeze(bc_film_3(:,:,end)); + +% Strain free substrate +bc_sub_1 = -squeeze(u_1_A(:,:,1)); +bc_sub_2 = -squeeze(u_2_A(:,:,1)); +bc_sub_3 = -squeeze(u_3_A(:,:,1)); + +%% fft2 the bc +bc_film_1_2Dk = fft2(bc_film_1); +bc_film_2_2Dk = fft2(bc_film_2); +bc_film_3_2Dk = fft2(bc_film_3); + +% Orders of magnitude larger... so let's make the matrix better to work with +rescaling_mat = sqrt( kx_grid_2D.^2 + ky_grid_2D.^2 ).^2; +rescaling_mat(1,1) = 1; +bc_film_1_2Dk = bc_film_1_2Dk ./ rescaling_mat; +bc_film_2_2Dk = bc_film_2_2Dk ./ rescaling_mat; +bc_film_3_2Dk = bc_film_3_2Dk ./ rescaling_mat; + +bc_sub_1_2Dk = fft2(bc_sub_1); +bc_sub_2_2Dk = fft2(bc_sub_2); +bc_sub_3_2Dk = fft2(bc_sub_3); + +bc_given_k_space = cat(4,bc_sub_1_2Dk,bc_sub_2_2Dk,bc_sub_3_2Dk,bc_film_1_2Dk,bc_film_2_2Dk,bc_film_3_2Dk); +d_sols = zeros(numel(kx),numel(ky),6); + +%% Apply the boundary conditions to get the solution to the diff. eq. +for k1 = 1 : Nx +for k2 = 1 : Ny + % Solve the matrix problem + d_sols(k1,k2,:) = squeeze(strain_bc_mats_inv(k1,k2,:,:)) * squeeze(bc_given_k_space(k1,k2,:)); +end +end + +%% Construct the solution in the 2D k-space, kx,ky,z +u_B_2Dk_mat = zeros(Nx,Ny,Nz,3); +u_B_2Dk_d3_mat = zeros(Nx,Ny,Nz,3); + +q_1 = squeeze(d_sols(:,:,1)); +q_2 = squeeze(d_sols(:,:,2)); +q_3 = squeeze(d_sols(:,:,3)); +q_4 = squeeze(d_sols(:,:,4)); +q_5 = squeeze(d_sols(:,:,5)); +q_6 = squeeze(d_sols(:,:,6)); + +p_1 = squeeze(eigenval_mat(:,:,1)); +p_2 = squeeze(eigenval_mat(:,:,2)); +p_3 = squeeze(eigenval_mat(:,:,3)); +p_4 = squeeze(eigenval_mat(:,:,4)); +p_5 = squeeze(eigenval_mat(:,:,5)); +p_6 = squeeze(eigenval_mat(:,:,6)); + +for l = 1 : 3 + for z_loop = 1 : numel(z_axis); + K = sqrt( kx_grid_2D.^2 + ky_grid_2D.^2 ); + + a_vec_1 = squeeze(eigenvec_mat(:,:,l,1)); + a_vec_2 = squeeze(eigenvec_mat(:,:,l,2)); + a_vec_3 = squeeze(eigenvec_mat(:,:,l,3)); + a_vec_4 = squeeze(eigenvec_mat(:,:,l,4)); + a_vec_5 = squeeze(eigenvec_mat(:,:,l,5)); + a_vec_6 = squeeze(eigenvec_mat(:,:,l,6)); + + u_B_2Dk_mat(:,:,z_loop,l) = q_1 .* a_vec_1 .* exp(p_1.*z_axis(z_loop).*1i.*K) + ... + q_2 .* a_vec_2 .* exp(p_2.*z_axis(z_loop).*1i.*K) + ... + q_3 .* a_vec_3 .* exp(p_3.*z_axis(z_loop).*1i.*K) + ... + q_4 .* a_vec_4 .* exp(p_4.*z_axis(z_loop).*1i.*K) + ... + q_5 .* a_vec_5 .* exp(p_5.*z_axis(z_loop).*1i.*K) + ... + q_6 .* a_vec_6 .* exp(p_6.*z_axis(z_loop).*1i.*K); + u_B_2Dk_d3_mat(:,:,z_loop,l) = ( q_1 .* a_vec_1 .* exp(p_1.*z_axis(z_loop).*1i.*K) .* p_1 + ... + q_2 .* a_vec_2 .* exp(p_2.*z_axis(z_loop).*1i.*K) .* p_2 + ... + q_3 .* a_vec_3 .* exp(p_3.*z_axis(z_loop).*1i.*K) .* p_3 + ... + q_4 .* a_vec_4 .* exp(p_4.*z_axis(z_loop).*1i.*K) .* p_4 + ... + q_5 .* a_vec_5 .* exp(p_5.*z_axis(z_loop).*1i.*K) .* p_5 + ... + q_6 .* a_vec_6 .* exp(p_6.*z_axis(z_loop).*1i.*K) .* p_6 ) .* 1i .* K; + end +end + +% 2D origin point... +d_sols(1,1,:) = strain_bc_mat_inv_korigin * squeeze(bc_given_k_space(1,1,:)); + +q = squeeze(d_sols(1,1,:)); +u_B_2Dk_mat(1,1,:,1) = q(1) * z_axis + q(2); +u_B_2Dk_mat(1,1,:,2) = q(3) * z_axis + q(4); +u_B_2Dk_mat(1,1,:,3) = q(5) * z_axis + q(6); +u_B_2Dk_d3_mat(1,1,:,1) = q(1); +u_B_2Dk_d3_mat(1,1,:,2) = q(3); +u_B_2Dk_d3_mat(1,1,:,3) = q(5); + +u_1_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,1)); +u_2_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,2)); +u_3_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,3)); +u_1_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,1)); +u_2_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,2)); +u_3_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,3)); + +%% Calculate the strains, e_ij = 0.5 * (u_i,j + u_j,i) +e_11_B_2Dk = u_1_B_2Dk .* 1i .* kx_grid_3D; +e_22_B_2Dk = u_2_B_2Dk .* 1i .* ky_grid_3D; +e_33_B_2Dk = u_3_B_2Dk_d3; +e_23_B_2Dk = 0.5 * (u_2_B_2Dk_d3 + 1i .* ky_grid_3D .* u_3_B_2Dk); +e_13_B_2Dk = 0.5 * (u_1_B_2Dk_d3 + 1i .* kx_grid_3D .* u_3_B_2Dk); +e_12_B_2Dk = 0.5 * (1i .* ky_grid_3D .* u_1_B_2Dk + 1i .* kx_grid_3D .* u_2_B_2Dk); + +%% Final outputs +u_1_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,1))); +u_2_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,2))); +u_3_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,3))); + +e_11_B = ifft_2d_slices(e_11_B_2Dk); +e_22_B = ifft_2d_slices(e_22_B_2Dk); +e_33_B = ifft_2d_slices(e_33_B_2Dk); +e_23_B = ifft_2d_slices(e_23_B_2Dk); +e_13_B = ifft_2d_slices(e_13_B_2Dk); +e_12_B = ifft_2d_slices(e_12_B_2Dk);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Isotropic/GreenTensorSetupIsotropic.m",".m","1645","26","Shear_Mod = 0.69 * 1e11; +Poisson_Ratio = 0.35; + +Green_11 = (( 1 / Shear_Mod ) - ( (kx_grid_3D .* kx_grid_3D) ./ (2 .* Shear_Mod .* (1 - Poisson_Ratio) .* k_mag_3D.^2) )) ./ k_mag_3D.^2; +Green_12 = (( 0 / Shear_Mod ) - ( (kx_grid_3D .* ky_grid_3D) ./ (2 .* Shear_Mod .* (1 - Poisson_Ratio) .* k_mag_3D.^2) )) ./ k_mag_3D.^2; +Green_13 = (( 0 / Shear_Mod ) - ( (kx_grid_3D .* kz_grid_3D) ./ (2 .* Shear_Mod .* (1 - Poisson_Ratio) .* k_mag_3D.^2) )) ./ k_mag_3D.^2; + +Green_21 = (( 0 / Shear_Mod ) - ( (ky_grid_3D .* kx_grid_3D) ./ (2 .* Shear_Mod .* (1 - Poisson_Ratio) .* k_mag_3D.^2) )) ./ k_mag_3D.^2; +Green_22 = (( 1 / Shear_Mod ) - ( (ky_grid_3D .* ky_grid_3D) ./ (2 .* Shear_Mod .* (1 - Poisson_Ratio) .* k_mag_3D.^2) )) ./ k_mag_3D.^2; +Green_23 = (( 0 / Shear_Mod ) - ( (ky_grid_3D .* kz_grid_3D) ./ (2 .* Shear_Mod .* (1 - Poisson_Ratio) .* k_mag_3D.^2) )) ./ k_mag_3D.^2; + +Green_31 = (( 0 / Shear_Mod ) - ( (kx_grid_3D .* kz_grid_3D) ./ (2 .* Shear_Mod .* (1 - Poisson_Ratio) .* k_mag_3D.^2) )) ./ k_mag_3D.^2; +Green_32 = (( 0 / Shear_Mod ) - ( (ky_grid_3D .* kz_grid_3D) ./ (2 .* Shear_Mod .* (1 - Poisson_Ratio) .* k_mag_3D.^2) )) ./ k_mag_3D.^2; +Green_33 = (( 1 / Shear_Mod ) - ( (kz_grid_3D .* kz_grid_3D) ./ (2 .* Shear_Mod .* (1 - Poisson_Ratio) .* k_mag_3D.^2) )) ./ k_mag_3D.^2; + +Green_11((kx==0),(ky==0),(kz==0)) = 0; +Green_12((kx==0),(ky==0),(kz==0)) = 0; +Green_13((kx==0),(ky==0),(kz==0)) = 0; + +Green_21((kx==0),(ky==0),(kz==0)) = 0; +Green_22((kx==0),(ky==0),(kz==0)) = 0; +Green_23((kx==0),(ky==0),(kz==0)) = 0; + +Green_31((kx==0),(ky==0),(kz==0)) = 0; +Green_32((kx==0),(ky==0),(kz==0)) = 0; +Green_33((kx==0),(ky==0),(kz==0)) = 0;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Isotropic/InfinitePlateSetupIsotropic.m",".m","112","2","eigenval_mat = [1i, 1i, 1i, -1i, -1i, -1i]; +eigenvec_mat = [ -1i .* ky_grid_2D ./ ( Shear_Mod .* kx_grid_2D ), ","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Other Setup/BFO.m",".m","5253","197","%% BFO +% All in MKS units + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 0 && ELASTIC; + +ELECTRIC = 0; +SURFACE_DEPOL = 0; + +LOAD = 0; % Load initial conditions from file +NUCLEATE = 0; + +%% Grid +Nx = 8; Ny = Nx; Nz = 36; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 32; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +T = 27; % in C +Us = 1e-2; % unitless misfit strain + +epsilon = 1e-2; +NOISE = 0; +saves = [0 : 1000 : 10000]; + +ThermConst = 0; % 0 no noise... + +%% Elastic Tensor +Poisson_mod = 0.35; +Shear_mod = 0.69 * 1e11; +Elastic_mod = Shear_mod * 2 * (1 + Poisson_mod); + +S11 = 1 / Elastic_mod; +S12 = -Poisson_mod / Elastic_mod; +S44 = (1 + Poisson_mod) / Elastic_mod; + +C11 = (S11+S12)/((S11-S12)*(S11+2*S12)); +C12 = -S12/((S11-S12)*(S11+2*S12)); +C44 = 1/S44; + + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + +%% Electrostriction +Q11 = 0.032; +Q12 = -0.016; +Q44 = 0.01; + +q11 = C11 * Q11 + 2 * C12 * Q12; +q12 = C11 * Q12 + C12 * ( Q11 + Q12 ); +q44 = 2 * C44 * Q44; + +% q11_h = q11 + 2 * q12; +% q22_h = q11 - q12; +% C11_h = C11 + 2 * C12; +% C22_h = C11 - C12; +% +% Q11 = (1/3) * ( (q11_h/C11_h) + (2 * q22_h/C22_h) ); +% Q12 = (1/3) * ( (q11_h/C11_h) - (q22_h/C22_h) ); +% Q44 = q44 / (2 * C44); + +%% LGD Constants, stress free Pb Zr(1-x) Tix O3 +% x = 1 +a1_T = @(T) 4.9 * ((T-273)-1103) * 1e5; % T in C +a1 = a1_T(T); +a11 = 5.42 * 1e8; +a12 = 1.54 * 1e8; +a111 = 0; +a112 = 0; +a123 = 0; +a1111 = 0; +a1112 = 0; +a1122 = 0; +a1123 = 0; + +%% Simulation grid in real space +l_0 = 1e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = 0.5*l_0*(Nz-1); + +% Set up real space axis +x_axis = linspace(0, Lx, Nx)'; y_axis = linspace(0, Ly, Ny)'; z_axis = linspace(0, Lz, Nz)'; + +%% VERY IMPORTANT STEP!! Let us redefine zero, otherwise the exp() term will make our matrix solving go to shit... +z_axis = z_axis - z_axis((round(Nz/2))); + +dx = x_axis(2) - x_axis(1); dy = y_axis(2) - y_axis(1); dz = z_axis(2) - z_axis(1); +[x_grid, y_grid, z_grid] = meshgrid(x_axis, y_axis, z_axis); +% kx_grid(y,x,z) + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = dx^2 * a0; +G11 = 0.6 * G110; +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = 0.6 * G110; % H44 = G44 + G44' + +%% Fourier space vectors -> Gradient energy terms and things that use air + film + sub +kx = 2*pi/Lx*[0:Nx/2 -Nx/2+1:-1]'; +ky = 2*pi/Ly*[0:Ny/2 -Ny/2+1:-1]'; +kz = 2*pi/Lz*[0:Nz/2 -Nz/2+1:-1]'; +[kx_grid_3D,ky_grid_3D,kz_grid_3D] = meshgrid(kx,ky,kz); +[kx_grid_2D, ky_grid_2D] = meshgrid(kx, ky); + +k_mag_3D = sqrt(kx_grid_3D.^2 + ky_grid_3D.^2 + kz_grid_3D.^2); +ex_3D = kx_grid_3D ./ k_mag_3D; +ey_3D = ky_grid_3D ./ k_mag_3D; +ez_3D = kz_grid_3D ./ k_mag_3D; + +%% Run time setup +t_0 = 1/a0; +dt = 0.01/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% +if( sub_index > 0 ) + in_film = (z_grid > z_axis(sub_index)) & (z_grid <= z_axis(film_index)); + not_in_film = ~in_film; + not_in_film = +not_in_film; + in_film = +in_film; +else + in_film = 1; + not_in_film = 0; +end + +%% Electrical +permittivity_0 = 8.85418782*1e-12; +k11 = 1000; k22 = k11; k33 = k11; +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; + +%% Transform matrix +% Transform from crystal to global film reference +Transform = [1 0 0; 0 1/sqrt(2) 1/sqrt(2); 0 -1/sqrt(2) 1/sqrt(2)]; + +%% z axis +h_film = z_axis(film_index); % end of film +h_sub = z_axis(1); % where substrate ends...limit of elastic deformation allowed in substrate +h_int = z_axis(interface_index); + +%% Green's Tensor +Green = zeros(Nx,Ny,Nz,3,3); + +% For each k vector find Green's Tensor +for k1 = 1 : Nx +for k2 = 1 : Ny +for k3 = 1 : Nz + + K_vec = [kx_grid_3D(k1,k2,k3) ky_grid_3D(k1,k2,k3) kz_grid_3D(k1,k2,k3)]; % Fourier space vector + g_inv = zeros(3,3); + for i_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + for k_ind = 1 : 3 + g_inv(i_ind,j_ind) = g_inv(i_ind,j_ind) + C(i_ind,k_ind,j_ind,l_ind) * K_vec(k_ind) * K_vec(l_ind); + end + end + end + end + + Green(k1,k2,k3,:,:) = inv(g_inv); + +end +end +end + +Green((kx==0),(ky==0),(kz==0),:,:) = 0; + +%% Nucleation sites, have 0 free energy change... +% Nucleation_Sites = +(rand(Nx,Ny,Nz) < (1-0.01)) .* in_film; +if( NUCLEATE ) + L = 5; + Nucleation_Sites = ones(Nx,Ny,Nz); + xy_edges = 8; + z_edges = 2; + for i = 1 : 7 + Nucleation_Sites(randi([xy_edges,Nx-L+1-xy_edges])+(0:L-1),randi([xy_edges,Ny-L+1-xy_edges])+(0:L-1),randi([z_edges,Nz-L+1-z_edges])+(0:L-1)) = 0; + end + + % Percent of nucleation sites + Nucleation_pct = abs(sum(sum(sum(Nucleation_Sites-1)))/(Nx*Ny*(film_index-interface_index+1))); +else + Nucleation_Sites = 1; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Other Setup/Setup_1.m",".m","3405","118","% http://www.ems.psu.edu/~chen/publications/YL2005APL.pdf + +Nx = 128; Ny = Nx; Nz = 36; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 32; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +T = 25; % in C +Us = 0e-2; +epsilon = 1e-3; +NOISE = 0; +saves = [0 : 1000 : 50000]; + +%% E field applied +E1 = 0; E2 = 0; E3 = 0; + +%% Elastic Tensor +% BTO +C11 = 1.78 * 1e11; +C12 = 0.964 * 1e11; +C44 = 1.22 * 1e11; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + +%% Electrostriction +Q11 = 0.10; +Q12 = -0.034; +Q44 = 0.029; + +q11 = C11 * Q11 + 2 * C12 * Q12; +q12 = C11 * Q12 + C12 * (Q11 + Q12); +q44 = 2 * C44 * Q44; + +%% LGD Constants, stress free BTO +a1_T = @(T) 4.124 * (T - 115) * 1e5; +a1 = a1_T(T); +a11 = -2.097 * 1e8; +a12 = 7.974 * 1e8; +a111 = 1.294 * 1e9; +a112 = -1.950 * 1e9; +a123 = -2.5 * 1e9; +a1111 = 3.863 * 1e10; +a1112 = 2.529 * 1e10; +a1122 = 1.637 * 1e10; +a1123 = 1.367 * 1e10; + +%% +b11 = 0.5*C11*(Q11^2 + 2*Q12^2) + C12*Q12*(2*Q11 + Q12); +b12 = C11*Q12*(2*Q11 + Q12) + C12*(Q11^2 + 3*Q12^2 + 2*Q11*Q12) + 2*C44*Q44^2; + +%% Simulation grid in real space +l_0 = 1e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = 0.5*l_0*(Nz-1); + +% Set up real space axis +x_axis = linspace(0, Lx, Nx)'; y_axis = linspace(0, Ly, Ny)'; z_axis = linspace(0, Lz, Nz)'; + +%% VERY IMPORTANT STEP!! Let us redefine zero, otherwise the exp() term will make our matrix solving go to shit... +z_axis = z_axis - z_axis((round(Nz/2))); + +dx = x_axis(2) - x_axis(1); dy = y_axis(2) - y_axis(1); dz = z_axis(2) - z_axis(1); +[x_grid, y_grid, z_grid] = meshgrid(x_axis, y_axis, z_axis); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = dx^2 * a0; +G11 = 0.6 * G110; +G14 = 0; +G44 = 0.6 * G110; + +%% Fourier space vectors -> Gradient energy terms and things that use air + film + sub +kx = 2*pi/Lx*[0:Nx/2 -Nx/2+1:-1]'; +ky = 2*pi/Ly*[0:Ny/2 -Ny/2+1:-1]'; +kz = 2*pi/Lz*[0:Nz/2 -Nz/2+1:-1]'; +[kx_grid_3D,ky_grid_3D,kz_grid_3D] = meshgrid(kx,ky,kz); +[kx_grid_2D, ky_grid_2D] = meshgrid(kx, ky); + +k_mag_3D = sqrt(kx_grid_3D.^2 + ky_grid_3D.^2 + kz_grid_3D.^2); +ex_3D = kx_grid_3D ./ k_mag_3D; +ey_3D = ky_grid_3D ./ k_mag_3D; +ez_3D = kz_grid_3D ./ k_mag_3D; + +%% Run time setup +t_0 = 1/a0; +dt = 0.025/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% +if( sub_index > 0 ) + in_film = (z_grid > z_axis(sub_index)) & (z_grid <= z_axis(film_index)); + not_in_film = ~in_film; + not_in_film = +not_in_film; + in_film = +in_film; +else + in_film = 1; + not_in_film = 0; +end + +%% Electrical +permittivity_0 = 8.85418782*1e-12; +k11 = 100; k22 = k11; k33 = k11; +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; + +%% z axis +h_film = z_axis(film_index); % end of film +h_sub = z_axis(1); % where substrate ends...limit of elastic deformation allowed in substrate +h_int = z_axis(interface_index);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Other Setup/BST.m",".m","7089","225","%% BST, All in MKS units + +% Run inputs +LOAD = 0; % 1 = Load initial conditions from file called init.mat, 0 = random P initial conditions +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; % in V/m, 1e5 V/m = 1 kV/cm +T = 27; % in C +Us_11 = 0.5068e-2; % unitless misfit strain +Us_22 = Us_11; % anisotropic misfit strain +% BST composition +BTO_pct = 0.8; STO_pct = 1 - BTO_pct; + + + + + +%% ---- Nothing needed to modify below ---- %% + +%% Convergence +epsilon = 1e-2; % convergence criterion +saves = [0 : 1000 : 20000]; % save after this many iterations + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 1 && ELASTIC; % automatically 0 if no elastic energy +% no heterogenous elastic relaxation if no elastic energy + +ELECTRIC = 1; +SURFACE_DEPOL = 0; % depolarization energy due to uncompensated surface charges + +NUCLEATE = 0; % nucleation sites, places that don't change during temporal evolution, 1 -> during hysteresis calcs + +ThermConst = 0; % No thermal energy + +%% Grid +Nx = 32; Ny = Nx; Nz = 36; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 32; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +%% BTO = http://www.ems.psu.edu/~chen/publications/YL2005APL.pdf +C11_BTO = 1.78 * 1e11; +C12_BTO = 0.964 * 1e11; +C44_BTO = 1.22 * 1e11; + +Q11_BTO = 0.10; +Q12_BTO = -0.034; +Q44_BTO = 0.029; + +a1_BTO = @(T) 4.124 * ( T - 115 ) * 1e5; +a11_BTO = -2.097 * 1e8; +a12_BTO = 7.974 * 1e8; +a111_BTO = 1.294 * 1e9; +a112_BTO = -1.950 * 1e9; +a123_BTO = -2.5 * 1e9; +a1111_BTO = 3.863 * 1e10; +a1112_BTO = 2.529 * 1e10; +a1122_BTO = 1.637 * 1e10; +a1123_BTO = 1.367 * 1e10; + +%% STO, Table VII, Table I last column +% http://www.wolframalpha.com/input/?i=1+dyn%2Fcm%5E2 +% 1 dyn/cm^2 = 0.1 Pa +C11_STO = 3.36 * 1e11; +C12_STO = 1.07 * 1e11; +C44_STO = 1.27 * 1e11; + +% STO Yu Luan Li PRB 184112, Table II +% 1 cm^4 / esu^2 = 8.988 * 1e10 m^4 / C^2 +% http://www.wolframalpha.com/input/?i=(1+cm)%5E4%2F(3.3356e-10+coulomb)%5E2 +Q11_STO = 4.57 * 1e-2; +Q12_STO = -1.348 * 1e-2; +Q44_STO = 0.957 * 1e-2; + +% STO Yu Luan Li PRB 184112, Table III a1 (1st, from ref 6, 16, 22), Table +% VII a11, a12, a1 +% Shirokov, Yuzyu, PRB 144118, Table I STO in parantheses + +% 1 cm^2 * dyn / esu^2 = 8.9876 * 1e9 J * m^2 / C +a1_STO = @(T) 4.05 * 1e7 * ( coth( 54 / (T+273) ) - coth(54/30) ); + +% 1 cm^6 * dyn / esu^4 = 8.0776 * 1e20 J * m^5 / C^4 +a11_STO = 17 * 1e8; +a12_STO = 13.7 * 1e8; + +a111_STO = 0; +a112_STO = 0; +a123_STO = 0; +a1111_STO = 0; +a1112_STO = 0; +a1122_STO = 0; +a1123_STO = 0; + +%% Elastic Tensor +C11 = C11_BTO * BTO_pct + C11_STO * STO_pct; +C12 = C12_BTO * BTO_pct + C12_STO * STO_pct; +C44 = C44_BTO * BTO_pct + C44_STO * STO_pct; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + +%% Electrostriction +q11_BTO = C11_BTO * Q11_BTO + 2 * C12_BTO * Q12_BTO; +q12_BTO = C11_BTO * Q12_BTO + C12_BTO * (Q11_BTO + Q12_BTO); +q44_BTO = 2 * C44_BTO * Q44_BTO; + +q11_STO = C11_STO * Q11_STO + 2 * C12_STO * Q12_STO; +q12_STO = C11_STO * Q12_STO + C12_STO * (Q11_STO + Q12_STO); +q44_STO = 2 * C44_STO * Q44_STO; + +q11 = q11_BTO * BTO_pct + q11_STO * STO_pct; +q12 = q12_BTO * BTO_pct + q12_STO * STO_pct; +q44 = q44_BTO * BTO_pct + q44_STO * STO_pct; + +q11_h = q11 + 2 * q12; +q22_h = q11 - q12; +C11_h = C11 + 2 * C12; +C22_h = C11 - C12; + +Q11 = (1/3) * ( (q11_h/C11_h) + (2 * q22_h/C22_h) ); +Q12 = (1/3) * ( (q11_h/C11_h) - (q22_h/C22_h) ); +Q44 = q44 / (2 * C44); + +%% LGD Constants, stress free BTO +a1_T = @(T) a1_BTO(T) * BTO_pct + a1_STO(T) * STO_pct; +a1 = a1_T(T); +a11 = a11_BTO * BTO_pct + a11_STO * STO_pct; +a12 = a12_BTO * BTO_pct + a12_STO * STO_pct; +a111 = a111_BTO * BTO_pct + a111_STO * STO_pct; +a112 = a112_BTO * BTO_pct + a112_STO * STO_pct; +a123 = a123_BTO * BTO_pct + a123_STO * STO_pct; +a1111 = a1111_BTO * BTO_pct + a1111_STO * STO_pct; +a1112 = a1112_BTO * BTO_pct + a1112_STO * STO_pct; +a1122 = a1122_BTO * BTO_pct + a1122_STO * STO_pct; +a1123 = a1123_BTO * BTO_pct + a1123_STO * STO_pct; + +%% +b11 = 0.5*C11*(Q11^2 + 2*Q12^2) + C12*Q12*(2*Q11 + Q12); +b12 = C11*Q12*(2*Q11 + Q12) + C12*(Q11^2 + 3*Q12^2 + 2*Q11*Q12) + 2*C44*Q44^2; + +%% Simulation grid in real space +l_0 = 1e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = 0.5*l_0*(Nz-1); + +% Set up real space axis +x_axis = linspace(0, Lx, Nx)'; y_axis = linspace(0, Ly, Ny)'; z_axis = linspace(0, Lz, Nz)'; + +%% VERY IMPORTANT STEP!! Let us redefine zero, otherwise the exp() term will make our matrix solving go to shit... +z_axis = z_axis - z_axis((round(Nz/2))); + +dx = x_axis(2) - x_axis(1); dy = y_axis(2) - y_axis(1); dz = z_axis(2) - z_axis(1); +[x_grid, y_grid, z_grid] = meshgrid(x_axis, y_axis, z_axis); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = dx^2 * a0; +G11 = 0.6 * G110; +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = 0.6 * G110; % H44 = G44 + G44' + +%% Fourier space vectors -> Gradient energy terms and things that use air + film + sub +kx = 2*pi/Lx*[0:Nx/2 -Nx/2+1:-1]'; +ky = 2*pi/Ly*[0:Ny/2 -Ny/2+1:-1]'; +kz = 2*pi/Lz*[0:Nz/2 -Nz/2+1:-1]'; +[kx_grid_3D,ky_grid_3D,kz_grid_3D] = meshgrid(kx,ky,kz); +[kx_grid_2D, ky_grid_2D] = meshgrid(kx, ky); + +k_mag_3D = sqrt(kx_grid_3D.^2 + ky_grid_3D.^2 + kz_grid_3D.^2); +ex_3D = kx_grid_3D ./ k_mag_3D; +ey_3D = ky_grid_3D ./ k_mag_3D; +ez_3D = kz_grid_3D ./ k_mag_3D; + +%% Run time setup +t_0 = 1/a0; +dt = 0.01/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% +if( sub_index > 0 ) + in_film = (z_grid > z_axis(sub_index)) & (z_grid <= z_axis(film_index)); + not_in_film = ~in_film; + not_in_film = +not_in_film; + in_film = +in_film; +else + in_film = 1; + not_in_film = 0; +end + +%% Electrical +permittivity_0 = 8.85418782*1e-12; +k11 = 1000; k22 = k11; k33 = k11; + +%% z axis +h_film = z_axis(film_index); % end of film +h_sub = z_axis(1); % where substrate ends...limit of elastic deformation allowed in substrate +h_int = z_axis(interface_index); + +%% Nucleation sites, have 0 free energy change... +if( NUCLEATE ) + % Nucleation_Sites = +(rand(Nx,Ny,Nz) < (1-0.01)) .* in_film; + Nucleation_Size = 5; + Nucleation_Sites = ones(Nx,Ny,Nz); + xy_edges = 8; + z_edges = 2; + for i = 1 : 7 + Nucleation_Sites(randi([xy_edges,Nx-Nucleation_Size+1-xy_edges])+(0:Nucleation_Size-1),randi([xy_edges,Ny-Nucleation_Size+1-xy_edges])+(0:Nucleation_Size-1),randi([z_edges,Nz-Nucleation_Size+1-z_edges])+(0:Nucleation_Size-1)) = 0; + end + + % Percent of nucleation sites + Nucleation_pct = abs(sum(sum(sum(Nucleation_Sites-1)))/(Nx*Ny*(film_index-interface_index+1))); +else + Nucleation_Sites = 1; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Other Setup/Setup_BST.m",".m","5644","187","%% BST +% All in MKS units + +LOAD = 1; +SURFACE_DEPOL = 0; +Nx = 64; Ny = Nx; Nz = 36; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 32; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +T = 17; % in C +Us = 0.05e-2; % unitless misfit strain +% BST composition +BTO_pct = 0.8; STO_pct = 1 - BTO_pct; + +epsilon = 1e-5; +NOISE = 0; +saves = [0 : 1000 : 20000]; + + +%% BTO = http://www.ems.psu.edu/~chen/publications/YL2005APL.pdf +C11_BTO = 1.78 * 1e11; +C12_BTO = 0.964 * 1e11; +C44_BTO = 1.22 * 1e11; + +Q11_BTO = 0.10; +Q12_BTO = -0.034; +Q44_BTO = 0.029; + +a1_BTO = @(T) 4.124 * ( T - 115 ) * 1e5; +a11_BTO = -2.097 * 1e8; +a12_BTO = 7.974 * 1e8; +a111_BTO = 1.294 * 1e9; +a112_BTO = -1.950 * 1e9; +a123_BTO = -2.5 * 1e9; +a1111_BTO = 3.863 * 1e10; +a1112_BTO = 2.529 * 1e10; +a1122_BTO = 1.637 * 1e10; +a1123_BTO = 1.367 * 1e10; + +%% STO, Table VII, Table I last column +% http://www.wolframalpha.com/input/?i=1+dyn%2Fcm%5E2 +% 1 dyn/cm^2 = 0.1 Pa +C11_STO = 3.36 * 1e11; +C12_STO = 1.07 * 1e11; +C44_STO = 1.27 * 1e11; + +% STO Yu Luan Li PRB 184112, Table II +% 1 cm^4 / esu^2 = 8.988 * 1e10 m^4 / C^2 +% http://www.wolframalpha.com/input/?i=(1+cm)%5E4%2F(3.3356e-10+coulomb)%5E2 +Q11_STO = 4.57 * 1e-2; +Q12_STO = -1.348 * 1e-2; +Q44_STO = 0.957 * 1e-2; + +% STO Yu Luan Li PRB 184112, Table III a1 (1st, from ref 6, 16, 22), Table +% VII a11, a12, a1 +% Shirokov, Yuzyu, PRB 144118, Table I STO in parantheses + +% 1 cm^2 * dyn / esu^2 = 8.9876 * 1e9 J * m^2 / C +a1_STO = @(T) 4.05 * 1e7 * ( coth( 54 / (T+273) ) - coth(54/30) ); + +% 1 cm^6 * dyn / esu^4 = 8.0776 * 1e20 J * m^5 / C^4 +a11_STO = 17 * 1e8; +a12_STO = 13.7 * 1e8; + +a111_STO = 0; +a112_STO = 0; +a123_STO = 0; +a1111_STO = 0; +a1112_STO = 0; +a1122_STO = 0; +a1123_STO = 0; + +%% Elastic Tensor +C11 = C11_BTO * BTO_pct + C11_STO * STO_pct; +C12 = C12_BTO * BTO_pct + C12_STO * STO_pct; +C44 = C44_BTO * BTO_pct + C44_STO * STO_pct; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + +%% Electrostriction +q11_BTO = C11_BTO * Q11_BTO + 2 * C12_BTO * Q12_BTO; +q12_BTO = C11_BTO * Q12_BTO + C12_BTO * (Q11_BTO + Q12_BTO); +q44_BTO = 2 * C44_BTO * Q44_BTO; + +q11_STO = C11_STO * Q11_STO + 2 * C12_STO * Q12_STO; +q12_STO = C11_STO * Q12_STO + C12_STO * (Q11_STO + Q12_STO); +q44_STO = 2 * C44_STO * Q44_STO; + +q11 = q11_BTO * BTO_pct + q11_STO * STO_pct; +q12 = q12_BTO * BTO_pct + q12_STO * STO_pct; +q44 = q44_BTO * BTO_pct + q44_STO * STO_pct; + +q11_h = q11 + 2 * q12; +q22_h = q11 - q12; +C11_h = C11 + 2 * C12; +C22_h = C11 - C12; + +Q11 = (1/3) * ( (q11_h/C11_h) + (2 * q22_h/C22_h) ); +Q12 = (1/3) * ( (q11_h/C11_h) - (q22_h/C22_h) ); +Q44 = q44 / (2 * C44); + +%% LGD Constants, stress free BTO +a1_T = @(T) a1_BTO(T) * BTO_pct + a1_STO(T) * STO_pct; +a1 = a1_T(T); +a11 = a11_BTO * BTO_pct + a11_STO * STO_pct; +a12 = a12_BTO * BTO_pct + a12_STO * STO_pct; +a111 = a111_BTO * BTO_pct + a111_STO * STO_pct; +a112 = a112_BTO * BTO_pct + a112_STO * STO_pct; +a123 = a123_BTO * BTO_pct + a123_STO * STO_pct; +a1111 = a1111_BTO * BTO_pct + a1111_STO * STO_pct; +a1112 = a1112_BTO * BTO_pct + a1112_STO * STO_pct; +a1122 = a1122_BTO * BTO_pct + a1122_STO * STO_pct; +a1123 = a1123_BTO * BTO_pct + a1123_STO * STO_pct; + +%% +b11 = 0.5*C11*(Q11^2 + 2*Q12^2) + C12*Q12*(2*Q11 + Q12); +b12 = C11*Q12*(2*Q11 + Q12) + C12*(Q11^2 + 3*Q12^2 + 2*Q11*Q12) + 2*C44*Q44^2; + +%% Simulation grid in real space +l_0 = 1e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = 0.5*l_0*(Nz-1); + +% Set up real space axis +x_axis = linspace(0, Lx, Nx)'; y_axis = linspace(0, Ly, Ny)'; z_axis = linspace(0, Lz, Nz)'; + +%% VERY IMPORTANT STEP!! Let us redefine zero, otherwise the exp() term will make our matrix solving go to shit... +z_axis = z_axis - z_axis((round(Nz/2))); + +dx = x_axis(2) - x_axis(1); dy = y_axis(2) - y_axis(1); dz = z_axis(2) - z_axis(1); +[x_grid, y_grid, z_grid] = meshgrid(x_axis, y_axis, z_axis); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = dx^2 * a0; +G11 = 0.6 * G110; +G14 = 0; +G44 = 0.6 * G110; + +%% Fourier space vectors -> Gradient energy terms and things that use air + film + sub +kx = 2*pi/Lx*[0:Nx/2 -Nx/2+1:-1]'; +ky = 2*pi/Ly*[0:Ny/2 -Ny/2+1:-1]'; +kz = 2*pi/Lz*[0:Nz/2 -Nz/2+1:-1]'; +[kx_grid_3D,ky_grid_3D,kz_grid_3D] = meshgrid(kx,ky,kz); +[kx_grid_2D, ky_grid_2D] = meshgrid(kx, ky); + +k_mag_3D = sqrt(kx_grid_3D.^2 + ky_grid_3D.^2 + kz_grid_3D.^2); +ex_3D = kx_grid_3D ./ k_mag_3D; +ey_3D = ky_grid_3D ./ k_mag_3D; +ez_3D = kz_grid_3D ./ k_mag_3D; + +%% Run time setup +t_0 = 1/a0; +dt = 0.00125/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% +if( sub_index > 0 ) + in_film = (z_grid > z_axis(sub_index)) & (z_grid <= z_axis(film_index)); + not_in_film = ~in_film; + not_in_film = +not_in_film; + in_film = +in_film; +else + in_film = 1; + not_in_film = 0; +end + +%% Electrical +permittivity_0 = 8.85418782*1e-12; +k11 = 1000; k22 = k11; k33 = k11; +E_1_applied = 1000*1e5; E_2_applied = 0; E_3_applied = 0; + +%% z axis +h_film = z_axis(film_index); % end of film +h_sub = z_axis(1); % where substrate ends...limit of elastic deformation allowed in substrate +h_int = z_axis(interface_index);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Other Setup/Setup_BTO.m",".m","3378","115","% http://www.ems.psu.edu/~chen/publications/YL2005APL.pdf +SURFACE_DEPOL = 0; +Nx = 32; Ny = Nx; Nz = 36; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 32; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +T = 25; % in C +Us = -1e-2; +epsilon = 1e-3; +NOISE = 0; +saves = [0 : 500 : 2000]; + +%% Elastic Tensor +% BTO +C11 = 1.78 * 1e11; +C12 = 0.964 * 1e11; +C44 = 1.22 * 1e11; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + +%% Electrostriction +Q11 = 0.10; +Q12 = -0.034; +Q44 = 0.029; + +q11 = C11 * Q11 + 2 * C12 * Q12; +q12 = C11 * Q12 + C12 * (Q11 + Q12); +q44 = 2 * C44 * Q44; + +%% LGD Constants, stress free BTO +a1_T = @(T) 4.124 * (T - 115) * 1e5; +a1 = a1_T(T); +a11 = -2.097 * 1e8; +a12 = 7.974 * 1e8; +a111 = 1.294 * 1e9; +a112 = -1.950 * 1e9; +a123 = -2.5 * 1e9; +a1111 = 3.863 * 1e10; +a1112 = 2.529 * 1e10; +a1122 = 1.637 * 1e10; +a1123 = 1.367 * 1e10; + +%% +b11 = 0.5*C11*(Q11^2 + 2*Q12^2) + C12*Q12*(2*Q11 + Q12); +b12 = C11*Q12*(2*Q11 + Q12) + C12*(Q11^2 + 3*Q12^2 + 2*Q11*Q12) + 2*C44*Q44^2; + +%% Simulation grid in real space +l_0 = 1e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = 0.5*l_0*(Nz-1); + +% Set up real space axis +x_axis = linspace(0, Lx, Nx)'; y_axis = linspace(0, Ly, Ny)'; z_axis = linspace(0, Lz, Nz)'; + +%% VERY IMPORTANT STEP!! Let us redefine zero, otherwise the exp() term will make our matrix solving go to shit... +z_axis = z_axis - z_axis((round(Nz/2))); + +dx = x_axis(2) - x_axis(1); dy = y_axis(2) - y_axis(1); dz = z_axis(2) - z_axis(1); +[x_grid, y_grid, z_grid] = meshgrid(x_axis, y_axis, z_axis); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = dx^2 * a0; +G11 = 0.6 * G110; +G14 = 0; +G44 = 0.6 * G110; + +%% Fourier space vectors -> Gradient energy terms and things that use air + film + sub +kx = 2*pi/Lx*[0:Nx/2 -Nx/2+1:-1]'; +ky = 2*pi/Ly*[0:Ny/2 -Ny/2+1:-1]'; +kz = 2*pi/Lz*[0:Nz/2 -Nz/2+1:-1]'; +[kx_grid_3D,ky_grid_3D,kz_grid_3D] = meshgrid(kx,ky,kz); +[kx_grid_2D, ky_grid_2D] = meshgrid(kx, ky); + +k_mag_3D = sqrt(kx_grid_3D.^2 + ky_grid_3D.^2 + kz_grid_3D.^2); +ex_3D = kx_grid_3D ./ k_mag_3D; +ey_3D = ky_grid_3D ./ k_mag_3D; +ez_3D = kz_grid_3D ./ k_mag_3D; + +%% Run time setup +t_0 = 1/a0; +dt = 0.00125/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% +if( sub_index > 0 ) + in_film = (z_grid > z_axis(sub_index)) & (z_grid <= z_axis(film_index)); + not_in_film = ~in_film; + not_in_film = +not_in_film; + in_film = +in_film; +else + in_film = 1; + not_in_film = 0; +end + +%% Electrical +permittivity_0 = 8.85418782*1e-12; +k11 = 10; k22 = k11; k33 = k11; +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; + +%% z axis +h_film = z_axis(film_index); % end of film +h_sub = z_axis(1); % where substrate ends...limit of elastic deformation allowed in substrate +h_int = z_axis(interface_index);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Other Setup/Setup_PTO.m",".m","3298","117","SURFACE_DEPOL = 0; +Nx = 32; Ny = Nx; Nz = 32; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 30; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +T = 25; +Us = -0.2e-2; +epsilon = 1e-4; +NOISE = 0; +saves = [0 : 1000 : 5000]; + +%% Elastic Tensor +% PTO +C11 = 1.746 * 1e11; +C12 = 7.937 * 1e10; +C44 = 1.111 * 1e11; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + +%% Electrostriction +% PTO +Q11 = 0.089; +Q12 = -0.026; +Q44 = 0.03375; + +q11 = C11 * Q11 + 2 * C12 * Q12; +q12 = C11 * Q12 + C12 * (Q11 + Q12); +q44 = 2 * C44 * Q44; + +%% LGD Constants, stress free BTO +a1 = 3.8 * ( T - 479 ) * 1e5; +a11 = -7.3 * 1e7; +a12 = 7.5 * 1e8; +a111 = 2.6 * 1e8; +a112 = 6.1 * 1e8; +a123 = -3.7 * 1e9; +a1111 = 0 * 1e10; +a1112 = 0 * 1e10; +a1122 = 0 * 1e10; +a1123 = 0 * 1e10; + +%% +b11 = 0.5*C11*(Q11^2 + 2*Q12^2) + C12*Q12*(2*Q11 + Q12); +b12 = C11*Q12*(2*Q11 + Q12) + C12*(Q11^2 + 3*Q12^2 + 2*Q11*Q12) + 2*C44*Q44^2; + +%% Gradient Free Energy +G110 = 1.73e-10; + +G11 = 0.6 * G110; +G14 = 0; +G44 = 0.6 * G110; + +a0 = abs(3.8*(25-479)*1e5); +l_0 = sqrt(G110 / a0); + +%% Simulation grid in real space +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = 0.5*l_0*(Nz-1); + +% Set up real space axis +x_axis = linspace(0, Lx, Nx)'; y_axis = linspace(0, Ly, Ny)'; z_axis = linspace(0, Lz, Nz)'; + +%% VERY IMPORTANT STEP!! Let us redefine zero, otherwise the exp() term will make our matrix solving go to shit... +z_axis = z_axis - z_axis((round(Nz/2))); + +dx = x_axis(2) - x_axis(1); dy = y_axis(2) - y_axis(1); dz = z_axis(2) - z_axis(1); +[x_grid, y_grid, z_grid] = meshgrid(x_axis, y_axis, z_axis); + +%% Fourier space vectors -> Gradient energy terms and things that use air + film + sub +kx = 2*pi/Lx*[0:Nx/2 -Nx/2+1:-1]'; +ky = 2*pi/Ly*[0:Ny/2 -Ny/2+1:-1]'; +kz = 2*pi/Lz*[0:Nz/2 -Nz/2+1:-1]'; +[kx_grid_3D,ky_grid_3D,kz_grid_3D] = meshgrid(kx,ky,kz); +[kx_grid_2D, ky_grid_2D] = meshgrid(kx, ky); + +k_mag_3D = sqrt(kx_grid_3D.^2 + ky_grid_3D.^2 + kz_grid_3D.^2); +ex_3D = kx_grid_3D ./ k_mag_3D; +ey_3D = ky_grid_3D ./ k_mag_3D; +ez_3D = kz_grid_3D ./ k_mag_3D; + +%% Run time setup +t_0 = 1/a0; +dt = 0.01/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% +if( sub_index > 0 ) + in_film = (z_grid > z_axis(sub_index)) & (z_grid <= z_axis(film_index)); + not_in_film = ~in_film; + not_in_film = +not_in_film; + in_film = +in_film; +else + in_film = 1; + not_in_film = 0; +end + +%% Electrical +permittivity_0 = 8.85418782*1e-12; +k11 = 66; k22 = k11; k33 = k11; +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; + +%% z axis +h_film = z_axis(film_index); % end of film +h_sub = z_axis(1); % where substrate ends...limit of elastic deformation allowed in substrate +h_int = z_axis(interface_index); +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Other Setup/New folder/Setup_BST.m",".m","4957","165","% Run inputs +LOAD = 0; % 1 = Load initial conditions from file called init.mat, 0 = random P initial conditions +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; % in V/m, 1e5 V/m = 1 kV/cm +T = 17; % in C +Us_11 = 0.5068e-2; % unitless misfit strain +Us_22 = Us_11; % anisotropic misfit strain +% BST composition +BTO_pct = 0.8; STO_pct = 1 - BTO_pct; + + + + + +%% ---- Nothing needed to modify below ---- %% + +%% Convergence +epsilon = 1e-2; % convergence criterion +saves = [0 : 1000 : 20000]; % save after this many iterations + +%% Grid Size +Nx = 64; Ny = Nx; Nz = 36; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 32; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 1 && ELASTIC; % automatically 0 if no elastic energy +% no heterogenous elastic relaxation if no elastic energy + +ELECTRIC = 1; +SURFACE_DEPOL = 0; % depolarization energy due to uncompensated surface charges + +NUCLEATE = 0; % nucleation sites, places that don't change during temporal evolution, 1 -> during hysteresis calcs + +ThermConst = 0; % No thermal energy + +%% BTO = http://www.ems.psu.edu/~chen/publications/YL2005APL.pdf +C11_BTO = 1.78 * 1e11; +C12_BTO = 0.964 * 1e11; +C44_BTO = 1.22 * 1e11; + +Q11_BTO = 0.10; +Q12_BTO = -0.034; +Q44_BTO = 0.029; + +a1_BTO = @(T) 4.124 * ( T - 115 ) * 1e5; +a11_BTO = -2.097 * 1e8; +a12_BTO = 7.974 * 1e8; +a111_BTO = 1.294 * 1e9; +a112_BTO = -1.950 * 1e9; +a123_BTO = -2.5 * 1e9; +a1111_BTO = 3.863 * 1e10; +a1112_BTO = 2.529 * 1e10; +a1122_BTO = 1.637 * 1e10; +a1123_BTO = 1.367 * 1e10; + +%% STO, Table VII, Table I last column +% http://www.wolframalpha.com/input/?i=1+dyn%2Fcm%5E2 +% 1 dyn/cm^2 = 0.1 Pa +C11_STO = 3.36 * 1e11; +C12_STO = 1.07 * 1e11; +C44_STO = 1.27 * 1e11; + +% STO Yu Luan Li PRB 184112, Table II +% 1 cm^4 / esu^2 = 8.988 * 1e10 m^4 / C^2 +% http://www.wolframalpha.com/input/?i=(1+cm)%5E4%2F(3.3356e-10+coulomb)%5E2 +Q11_STO = 4.57 * 1e-2; +Q12_STO = -1.348 * 1e-2; +Q44_STO = 0.957 * 1e-2; + +% STO Yu Luan Li PRB 184112, Table III a1 (1st, from ref 6, 16, 22), Table +% VII a11, a12, a1 +% Shirokov, Yuzyu, PRB 144118, Table I STO in parantheses + +% 1 cm^2 * dyn / esu^2 = 8.9876 * 1e9 J * m^2 / C +a1_STO = @(T) 4.05 * 1e7 * ( coth( 54 / (T+273) ) - coth(54/30) ); + +% 1 cm^6 * dyn / esu^4 = 8.0776 * 1e20 J * m^5 / C^4 +a11_STO = 17 * 1e8; +a12_STO = 13.7 * 1e8; + +a111_STO = 0; +a112_STO = 0; +a123_STO = 0; +a1111_STO = 0; +a1112_STO = 0; +a1122_STO = 0; +a1123_STO = 0; + +%% Elastic Tensor +C11 = C11_BTO * BTO_pct + C11_STO * STO_pct; +C12 = C12_BTO * BTO_pct + C12_STO * STO_pct; +C44 = C44_BTO * BTO_pct + C44_STO * STO_pct; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + +%% Electrostriction +q11_BTO = C11_BTO * Q11_BTO + 2 * C12_BTO * Q12_BTO; +q12_BTO = C11_BTO * Q12_BTO + C12_BTO * (Q11_BTO + Q12_BTO); +q44_BTO = 2 * C44_BTO * Q44_BTO; + +q11_STO = C11_STO * Q11_STO + 2 * C12_STO * Q12_STO; +q12_STO = C11_STO * Q12_STO + C12_STO * (Q11_STO + Q12_STO); +q44_STO = 2 * C44_STO * Q44_STO; + +q11 = q11_BTO * BTO_pct + q11_STO * STO_pct; +q12 = q12_BTO * BTO_pct + q12_STO * STO_pct; +q44 = q44_BTO * BTO_pct + q44_STO * STO_pct; + +q11_h = q11 + 2 * q12; +q22_h = q11 - q12; +C11_h = C11 + 2 * C12; +C22_h = C11 - C12; + +Q11 = (1/3) * ( (q11_h/C11_h) + (2 * q22_h/C22_h) ); +Q12 = (1/3) * ( (q11_h/C11_h) - (q22_h/C22_h) ); +Q44 = q44 / (2 * C44); + +%% LGD Constants, stress free BTO +a1_T = @(T) a1_BTO(T) * BTO_pct + a1_STO(T) * STO_pct; +a1 = a1_T(T); +a11 = a11_BTO * BTO_pct + a11_STO * STO_pct; +a12 = a12_BTO * BTO_pct + a12_STO * STO_pct; +a111 = a111_BTO * BTO_pct + a111_STO * STO_pct; +a112 = a112_BTO * BTO_pct + a112_STO * STO_pct; +a123 = a123_BTO * BTO_pct + a123_STO * STO_pct; +a1111 = a1111_BTO * BTO_pct + a1111_STO * STO_pct; +a1112 = a1112_BTO * BTO_pct + a1112_STO * STO_pct; +a1122 = a1122_BTO * BTO_pct + a1122_STO * STO_pct; +a1123 = a1123_BTO * BTO_pct + a1123_STO * STO_pct; + +%% Simulation Size +l_0 = 1e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = 0.5*l_0*(Nz-1); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = l_0^2 * a0; +G11 = 0.6 * G110; +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = 0.6 * G110; % H44 = G44 + G44' + +%% Run time setup +t_0 = 1/a0; +dt = 0.0125/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% Electrical +permittivity_0 = 8.85418782*1e-12; +k11 = 1000; k22 = k11; k33 = k11;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Other Setup/New folder/Setup_BFO_2.m",".m","3095","104","% Run inputs +LOAD = 1; % 1 = Load initial conditions from file called init.mat, 0 = random P initial conditions +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; % in V/m, 1e5 V/m = 1 kV/cm +T = 27; % in C +Us_11 = 0; % unitless misfit strain +Us_22 = Us_11; % anisotropic misfit strain +PATH = '.\'; +STRING = 'BFO small Q44'; % Material Name +VPA_ELECTRIC_ON = 1; % numerical errors when doing electric energy, so we need to use vpa +VPA_ELASTIC_ON = 0; + +%% ---- Nothing needed to modify below ---- %% +% BFO Constants http://www.mmm.psu.edu/JXZhang2008_JAP_Computersimulation.pdf + +%% Convergence +epsilon = 1e-10; % convergence criterion +saves = [0 : 500 : 100000]; % save after this many iterations + +%% Grid Size +Nx = 32; Ny = Nx; Nz = 32; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 28; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 1 && ELASTIC; % automatically 0 if no elastic energy +% no heterogenous elastic relaxation if no elastic energy + +ELECTRIC = 1; +SURFACE_DEPOL = 0; % depolarization energy due to uncompensated surface charges + +NUCLEATE = 0; % nucleation sites, places that don't change during temporal evolution, 1 -> during hysteresis calcs + +ThermConst = 0; % No thermal energy + +%% Elastic Tensor +Poisson_Ratio = 0.35; +Shear_Mod = 0.69 * 1e11; + +C11 = 2 * Shear_Mod * ( 1 - Poisson_Ratio ) / ( 1 - 2 * Poisson_Ratio ); +C12 = 2 * Shear_Mod * Poisson_Ratio / ( 1 - 2 * Poisson_Ratio ); +C44 = Shear_Mod; + +C12 = 1.62 * 1e11; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + + +%% Electrostriction +Q11 = 0.032; % Q1111 = Q11 +Q12 = -0.016; % Q1122 = Q12 +Q44 = 0.01 * 2; % 2 * Q1212 = Q44 + +q11 = C11 * Q11 + 2 * C12 * Q12; +q12 = C11 * Q12 + C12 * ( Q11 + Q12 ); +q44 = 2 * C44 * Q44; + +%% LGD Constants, stress free BTO +a1_T = @(T) 4.9 * ((T+273)-1103) * 1e5; % T in C +a1 = a1_T(T); +a11 = 5.42 * 1e8; +a12 = 1.54 * 1e8; +a111 = 0; +a112 = 0; +a123 = 0; +a1111 = 0; +a1112 = 0; +a1122 = 0; +a1123 = 0; + +%% Simulation Size +l_0 = 0.5e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = l_0*(Nz-1); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = l_0^2 * a0; +G11 = 0.6 * G110; + +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = G11; % H44 = G44 + G44' + +%% Run time setup +t_0 = 1/a0; +dt = 0.0125/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% Electrical +k_electric_11 = 500; k_electric_22 = k_electric_11; k_electric_33 = k_electric_11;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(100)/Random P nucleate test/RandomP.m",".m","962","30","P1 = zeros( Nx, Ny, Nz ); P2 = P1; P3 = P1; + +init_perturb = rand(Nx, Ny, Nz) > 0.5; % where to perturb +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; % how much to perturb +P1(init_perturb) = perturb_amt(init_perturb); +P1(~init_perturb) = -perturb_amt(~init_perturb); + +init_perturb = rand(Nx, Ny, Nz) > 0.5; +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; +P2(init_perturb) = perturb_amt(init_perturb); +P2(~init_perturb) = -perturb_amt(~init_perturb); + +init_perturb = rand(Nx, Ny, Nz) > 0.5; +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; +P3(init_perturb) = perturb_amt(init_perturb); +P3(~init_perturb) = -perturb_amt(~init_perturb); + +L = 5; +init_sites = ones(Nx,Ny,Nz); +xy_edges = 8; +z_edges = 2; +for i = 1 : 7 + init_sites(randi([xy_edges,Nx-L+1-xy_edges])+(0:L-1),randi([xy_edges,Ny-L+1-xy_edges])+(0:L-1),randi([z_edges,Nz-L+1-z_edges])+(0:L-1)) = 0; +end + +P1 = P1 + init_sites * 1e-1; +P2 = P2 + init_sites * 1e-1; +P3 = P3 + init_sites * 1e-1; + +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/RandomP.m",".m","733","16","P1_FilmRef = zeros( Nx, Ny, Nz ); P2_FilmRef = P1_FilmRef; P3_FilmRef = P1_FilmRef; + +init_perturb = rand(Nx, Ny, Nz) > 0.5; % where to perturb +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; % how much to perturb +P1_FilmRef(init_perturb) = perturb_amt(init_perturb); +P1_FilmRef(~init_perturb) = -perturb_amt(~init_perturb); + +init_perturb = rand(Nx, Ny, Nz) > 0.5; +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; +P2_FilmRef(init_perturb) = perturb_amt(init_perturb); +P2_FilmRef(~init_perturb) = -perturb_amt(~init_perturb); + +init_perturb = rand(Nx, Ny, Nz) > 0.5; +perturb_amt = abs( rand(Nx, Ny, Nz) - 0.5 ) * 1e-2; +P3_FilmRef(init_perturb) = perturb_amt(init_perturb); +P3_FilmRef(~init_perturb) = -perturb_amt(~init_perturb);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/ThermalNoise.m",".m","493","10","% Thermal Noise +Thermal_Noise_Sigma = sqrt(2 * ThermConst); + +Thermal_Noise_1 = normrnd(0,Thermal_Noise_Sigma,Nx,Ny,Nz); +Thermal_Noise_2 = normrnd(0,Thermal_Noise_Sigma,Nx,Ny,Nz); +Thermal_Noise_3 = normrnd(0,Thermal_Noise_Sigma,Nx,Ny,Nz); + +Thermal_Noise_1_2Dk = fft_2d_slices(Thermal_Noise_1) .* in_film .* Nucleation_Sites; +Thermal_Noise_2_2Dk = fft_2d_slices(Thermal_Noise_2) .* in_film .* Nucleation_Sites; +Thermal_Noise_3_2Dk = fft_2d_slices(Thermal_Noise_3) .* in_film .* Nucleation_Sites;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/AxesSetup.m",".m","1308","37","%% Set up real space axis +x_axis = linspace(0, Lx, Nx)'; y_axis = linspace(0, Ly, Ny)'; z_axis = linspace(0, Lz, Nz)'; + +%% VERY IMPORTANT STEP!! Let us redefine zero, otherwise the exp() term will make our matrix solving go to shit... +z_axis = z_axis - z_axis((round(Nz/2))); + +dx = x_axis(2) - x_axis(1); dy = y_axis(2) - y_axis(1); dz = z_axis(2) - z_axis(1); +[y_grid, x_grid, z_grid] = meshgrid(x_axis, y_axis, z_axis); +% kx_grid(y,x,z) + +%% Fourier space vectors -> Gradient energy terms and things that use air + film + sub +kx = 2*pi/Lx*[0:Nx/2 -Nx/2+1:-1]'; +ky = 2*pi/Ly*[0:Ny/2 -Ny/2+1:-1]'; +kz = 2*pi/Lz*[0:Nz/2 -Nz/2+1:-1]'; +[ky_grid_3D,kx_grid_3D,kz_grid_3D] = meshgrid(kx,ky,kz); +[ky_grid_2D, kx_grid_2D] = meshgrid(kx, ky); + +k_mag_3D = sqrt(kx_grid_3D.^2 + ky_grid_3D.^2 + kz_grid_3D.^2); +ex_3D = kx_grid_3D ./ k_mag_3D; +ey_3D = ky_grid_3D ./ k_mag_3D; +ez_3D = kz_grid_3D ./ k_mag_3D; + +%% +if( sub_index > 0 ) + in_film = (z_grid > z_axis(sub_index)) & (z_grid <= z_axis(film_index)); + not_in_film = ~in_film; + not_in_film = +not_in_film; + in_film = +in_film; +else + in_film = 1; + not_in_film = 0; +end + +%% z axis +h_film = z_axis(film_index); % end of film +h_sub = z_axis(1); % where substrate ends...limit of elastic deformation allowed in substrate +h_int = z_axis(interface_index);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/colorGradient.m",".m","2484","87","function [grad,im]=colorGradient(c1,c2,depth) +% COLORGRADIENT allows you to generate a gradient between 2 given colors, +% that can be used as colormap in your figures. +% +% USAGE: +% +% [grad,im]=getGradient(c1,c2,depth) +% +% INPUT: +% - c1: color vector given as Intensity or RGB color. Initial value. +% - c2: same as c1. This is the final value of the gradient. +% - depth: number of colors or elements of the gradient. +% +% OUTPUT: +% - grad: a matrix of depth*3 elements containing colormap (or gradient). +% - im: a depth*20*3 RGB image that can be used to display the result. +% +% EXAMPLES: +% grad=colorGradient([1 0 0],[0.5 0.8 1],128); +% surf(peaks) +% colormap(grad); +% +% -------------------- +% [grad,im]=colorGradient([1 0 0],[0.5 0.8 1],128); +% image(im); %display an image with the color gradient. + +% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal +% v:1.0 22 May 2011. Initial release. + +%Check input arguments. +%input arguments must be 2 or 3. +error(nargchk(2, 3, nargin)); + +%If c1 or c2 is not a valid RGB vector return an error. +if numel(c1)~=3 + error('color c1 is not a valir RGB vector'); +end +if numel(c2)~=3 + error('color c2 is not a valir RGB vector'); +end + +if max(c1)>1&&max(c1)<=255 + %warn if RGB values are given instead of Intensity values. Convert and + %keep procesing. + warning('color c1 is not given as intensity values. Trying to convert'); + c1=c1./255; +elseif max(c1)>255||min(c1)<0 + error('C1 RGB values are not valid.') +end + +if max(c2)>1&&max(c2)<=255 + %warn if RGB values are given instead of Intensity values. Convert and + %keep procesing. + warning('color c2 is not given as intensity values. Trying to convert'); + c2=c2./255; +elseif max(c2)>255||min(c2)<0 + error('C2 RGB values are not valid.') +end +%default depth is 64 colors. Just in case we did not define that argument. +if nargin < 3 + depth=64; +end + +%determine increment step for each color channel. +dr=(c2(1)-c1(1))/(depth-1); +dg=(c2(2)-c1(2))/(depth-1); +db=(c2(3)-c1(3))/(depth-1); + +%initialize gradient matrix. +grad=zeros(depth,3); +%initialize matrix for each color. Needed for the image. Size 20*depth. +r=zeros(20,depth); +g=zeros(20,depth); +b=zeros(20,depth); +%for each color step, increase/reduce the value of Intensity data. +for j=1:depth + grad(j,1)=c1(1)+dr*(j-1); + grad(j,2)=c1(2)+dg*(j-1); + grad(j,3)=c1(3)+db*(j-1); + r(:,j)=grad(j,1); + g(:,j)=grad(j,2); + b(:,j)=grad(j,3); +end + +%merge R G B matrix and obtain our image. +im=cat(3,r,g,b); +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/CalcElasticEnergy.m",".m","6582","22","if( ELASTIC ) + CalculateStrain; + + f1_elastic = (- C11.*Q11 - C11.*Q12 - C12.*Q11 - 3.*C12.*Q12 - 2.*C44.*Q44).*TotalStrain_FilmRef_11.*P1_FilmRef + ((2.*C44.*Q44)/3 - (5.*C11.*Q12)/3 - (5.*C12.*Q11)/3 - (7.*C12.*Q12)/3 - (C11.*Q11)/3).*TotalStrain_FilmRef_22.*P1_FilmRef + ((4.*C44.*Q44)/3 - (4.*C11.*Q12)/3 - (4.*C12.*Q11)/3 - (8.*C12.*Q12)/3 - (2.*C11.*Q11)/3).*TotalStrain_FilmRef_33.*P1_FilmRef + ((2.*C11.*Q12)/3 - (2.*C11.*Q11)/3 + (2.*C12.*Q11)/3 - (2.*C12.*Q12)/3 - (8.*C44.*Q44)/3).*TotalStrain_FilmRef_12.*P2_FilmRef + ((2.*2.^(1/2).*C11.*Q12)/3 - (2.*2.^(1/2).*C11.*Q11)/3 + (2.*2.^(1/2).*C12.*Q11)/3 - (2.*2.^(1/2).*C12.*Q12)/3 + (4.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_12.*P3_FilmRef + ((2.*2.^(1/2).*C11.*Q12)/3 - (2.*2.^(1/2).*C11.*Q11)/3 + (2.*2.^(1/2).*C12.*Q11)/3 - (2.*2.^(1/2).*C12.*Q12)/3 + (4.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_13.*P2_FilmRef + ((4.*C11.*Q12)/3 - (4.*C11.*Q11)/3 + (4.*C12.*Q11)/3 - (4.*C12.*Q12)/3 - (4.*C44.*Q44)/3).*TotalStrain_FilmRef_13.*P3_FilmRef + ((2.*2.^(1/2).*C11.*Q12)/3 - (2.*2.^(1/2).*C11.*Q11)/3 + (2.*2.^(1/2).*C12.*Q11)/3 - (2.*2.^(1/2).*C12.*Q12)/3 + (4.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_23.*P1_FilmRef + (C11.*Q11.^2 + 3.*C11.*Q12.^2 + C12.*Q11.^2 + 5.*C12.*Q12.^2 + 2.*C44.*Q44.^2 + 2.*C11.*Q11.*Q12 + 6.*C12.*Q11.*Q12).*P1_FilmRef.^3 + (C11.*Q11.^2 + 3.*C11.*Q12.^2 + C12.*Q11.^2 + 5.*C12.*Q12.^2 + 2.*C44.*Q44.^2 + 2.*C11.*Q11.*Q12 + 6.*C12.*Q11.*Q12).*P1_FilmRef.*P2_FilmRef.^2 + (2.*2.^(1/2).*C11.*Q11.^2 + 2.*2.^(1/2).*C11.*Q12.^2 - 2.*2.^(1/2).*C12.*Q11.^2 - 2.*2.^(1/2).*C12.*Q12.^2 - 4.*2.^(1/2).*C44.*Q44.^2 - 4.*2.^(1/2).*C11.*Q11.*Q12 + 4.*2.^(1/2).*C12.*Q11.*Q12).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef + (2.*C11.*Q11.^2 + 4.*C11.*Q12.^2 + 4.*C12.*Q12.^2 + 8.*C12.*Q11.*Q12).*P1_FilmRef.*P3_FilmRef.^2; + f2_elastic = ((2.*C44.*Q44)/3 - (5.*C11.*Q12)/3 - (5.*C12.*Q11)/3 - (7.*C12.*Q12)/3 - (C11.*Q11)/3).*TotalStrain_FilmRef_11.*P2_FilmRef + ((2.^(1/2).*C11.*Q12)/3 - (2.^(1/2).*C11.*Q11)/3 + (2.^(1/2).*C12.*Q11)/3 - (2.^(1/2).*C12.*Q12)/3 + (2.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_11.*P3_FilmRef + (- C11.*Q11 - C11.*Q12 - C12.*Q11 - 3.*C12.*Q12 - 2.*C44.*Q44).*TotalStrain_FilmRef_22.*P2_FilmRef + ((2.^(1/2).*C11.*Q11)/3 - (2.^(1/2).*C11.*Q12)/3 - (2.^(1/2).*C12.*Q11)/3 + (2.^(1/2).*C12.*Q12)/3 - (2.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_22.*P3_FilmRef + ((4.*C44.*Q44)/3 - (4.*C11.*Q12)/3 - (4.*C12.*Q11)/3 - (8.*C12.*Q12)/3 - (2.*C11.*Q11)/3).*TotalStrain_FilmRef_33.*P2_FilmRef + ((2.*C11.*Q12)/3 - (2.*C11.*Q11)/3 + (2.*C12.*Q11)/3 - (2.*C12.*Q12)/3 - (8.*C44.*Q44)/3).*TotalStrain_FilmRef_12.*P1_FilmRef + ((2.*2.^(1/2).*C11.*Q12)/3 - (2.*2.^(1/2).*C11.*Q11)/3 + (2.*2.^(1/2).*C12.*Q11)/3 - (2.*2.^(1/2).*C12.*Q12)/3 + (4.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_13.*P1_FilmRef + ((2.*2.^(1/2).*C11.*Q11)/3 - (2.*2.^(1/2).*C11.*Q12)/3 - (2.*2.^(1/2).*C12.*Q11)/3 + (2.*2.^(1/2).*C12.*Q12)/3 - (4.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_23.*P2_FilmRef + ((4.*C11.*Q12)/3 - (4.*C11.*Q11)/3 + (4.*C12.*Q11)/3 - (4.*C12.*Q12)/3 - (4.*C44.*Q44)/3).*TotalStrain_FilmRef_23.*P3_FilmRef + (C11.*Q11.^2 + 3.*C11.*Q12.^2 + C12.*Q11.^2 + 5.*C12.*Q12.^2 + 2.*C44.*Q44.^2 + 2.*C11.*Q11.*Q12 + 6.*C12.*Q11.*Q12).*P1_FilmRef.^2.*P2_FilmRef + (2.^(1/2).*C11.*Q11.^2 + 2.^(1/2).*C11.*Q12.^2 - 2.^(1/2).*C12.*Q11.^2 - 2.^(1/2).*C12.*Q12.^2 - 2.*2.^(1/2).*C44.*Q44.^2 - 2.*2.^(1/2).*C11.*Q11.*Q12 + 2.*2.^(1/2).*C12.*Q11.*Q12).*P1_FilmRef.^2.*P3_FilmRef + (C11.*Q11.^2 + 3.*C11.*Q12.^2 + C12.*Q11.^2 + 5.*C12.*Q12.^2 + 2.*C44.*Q44.^2 + 2.*C11.*Q11.*Q12 + 6.*C12.*Q11.*Q12).*P2_FilmRef.^3 + (2.^(1/2).*C12.*Q11.^2 - 2.^(1/2).*C11.*Q12.^2 - 2.^(1/2).*C11.*Q11.^2 + 2.^(1/2).*C12.*Q12.^2 + 2.*2.^(1/2).*C44.*Q44.^2 + 2.*2.^(1/2).*C11.*Q11.*Q12 - 2.*2.^(1/2).*C12.*Q11.*Q12).*P2_FilmRef.^2.*P3_FilmRef + (2.*C11.*Q11.^2 + 4.*C11.*Q12.^2 + 4.*C12.*Q12.^2 + 8.*C12.*Q11.*Q12).*P2_FilmRef.*P3_FilmRef.^2; + f3_elastic = ((2.^(1/2).*C11.*Q12)/3 - (2.^(1/2).*C11.*Q11)/3 + (2.^(1/2).*C12.*Q11)/3 - (2.^(1/2).*C12.*Q12)/3 + (2.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_11.*P2_FilmRef + ((4.*C44.*Q44)/3 - (4.*C11.*Q12)/3 - (4.*C12.*Q11)/3 - (8.*C12.*Q12)/3 - (2.*C11.*Q11)/3).*TotalStrain_FilmRef_11.*P3_FilmRef + ((2.^(1/2).*C11.*Q11)/3 - (2.^(1/2).*C11.*Q12)/3 - (2.^(1/2).*C12.*Q11)/3 + (2.^(1/2).*C12.*Q12)/3 - (2.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_22.*P2_FilmRef + ((4.*C44.*Q44)/3 - (4.*C11.*Q12)/3 - (4.*C12.*Q11)/3 - (8.*C12.*Q12)/3 - (2.*C11.*Q11)/3).*TotalStrain_FilmRef_22.*P3_FilmRef + (- (2.*C11.*Q11)/3 - (4.*C11.*Q12)/3 - (4.*C12.*Q11)/3 - (8.*C12.*Q12)/3 - (8.*C44.*Q44)/3).*TotalStrain_FilmRef_33.*P3_FilmRef + ((2.*2.^(1/2).*C11.*Q12)/3 - (2.*2.^(1/2).*C11.*Q11)/3 + (2.*2.^(1/2).*C12.*Q11)/3 - (2.*2.^(1/2).*C12.*Q12)/3 + (4.*2.^(1/2).*C44.*Q44)/3).*TotalStrain_FilmRef_12.*P1_FilmRef + ((4.*C11.*Q12)/3 - (4.*C11.*Q11)/3 + (4.*C12.*Q11)/3 - (4.*C12.*Q12)/3 - (4.*C44.*Q44)/3).*TotalStrain_FilmRef_13.*P1_FilmRef + ((4.*C11.*Q12)/3 - (4.*C11.*Q11)/3 + (4.*C12.*Q11)/3 - (4.*C12.*Q12)/3 - (4.*C44.*Q44)/3).*TotalStrain_FilmRef_23.*P2_FilmRef + (2.^(1/2).*C11.*Q11.^2 + 2.^(1/2).*C11.*Q12.^2 - 2.^(1/2).*C12.*Q11.^2 - 2.^(1/2).*C12.*Q12.^2 - 2.*2.^(1/2).*C44.*Q44.^2 - 2.*2.^(1/2).*C11.*Q11.*Q12 + 2.*2.^(1/2).*C12.*Q11.*Q12).*P1_FilmRef.^2.*P2_FilmRef + (2.*C11.*Q11.^2 + 4.*C11.*Q12.^2 + 4.*C12.*Q12.^2 + 8.*C12.*Q11.*Q12).*P1_FilmRef.^2.*P3_FilmRef + ((2.^(1/2).*C12.*Q11.^2)/3 - (2.^(1/2).*C11.*Q12.^2)/3 - (2.^(1/2).*C11.*Q11.^2)/3 + (2.^(1/2).*C12.*Q12.^2)/3 + (2.*2.^(1/2).*C44.*Q44.^2)/3 + (2.*2.^(1/2).*C11.*Q11.*Q12)/3 - (2.*2.^(1/2).*C12.*Q11.*Q12)/3).*P2_FilmRef.^3 + (2.*C11.*Q11.^2 + 4.*C11.*Q12.^2 + 4.*C12.*Q12.^2 + 8.*C12.*Q11.*Q12).*P2_FilmRef.^2.*P3_FilmRef + ((2.*C11.*Q11.^2)/3 + (8.*C11.*Q12.^2)/3 + (4.*C12.*Q11.^2)/3 + (16.*C12.*Q12.^2)/3 + (8.*C44.*Q44.^2)/3 + (8.*C11.*Q11.*Q12)/3 + (16.*C12.*Q11.*Q12)/3).*P3_FilmRef.^3; + + f1_elastic = f1_elastic .* in_film .* Nucleation_Sites; + f2_elastic = f2_elastic .* in_film .* Nucleation_Sites; + f3_elastic = f3_elastic .* in_film .* Nucleation_Sites; + + f1_elastic_2Dk = fft_2d_slices(f1_elastic); + f2_elastic_2Dk = fft_2d_slices(f2_elastic); + f3_elastic_2Dk = fft_2d_slices(f3_elastic); +else + f1_elastic_2Dk = 0; f2_elastic_2Dk = 0; f3_elastic_2Dk = 0; + f1_elastic = 0; f2_elastic = 0; f3_elastic = 0; + TotalStrain_FilmRef_11 = 0; TotalStrain_FilmRef_22 = 0; + TotalStrain_FilmRef_33 = 0; TotalStrain_FilmRef_12 = 0; + TotalStrain_FilmRef_13 = 0; TotalStrain_FilmRef_23 = 0; + u_FilmRef_1 = 0; u_FilmRef_2 = 0; u_FilmRef_3 = 0; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/GreenTensorSetup.m",".m","1233","39","%% Green's Tensor +Green_FilmRef_k = zeros(Nx,Ny,Nz,3,3); + +% For each k vector find Green's Tensor +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny +for k3_ind = 1 : Nz + + K_vec = [kx_grid_3D(k1_ind,k2_ind,k3_ind) ky_grid_3D(k1_ind,k2_ind,k3_ind) kz_grid_3D(k1_ind,k2_ind,k3_ind)]; % Fourier space vector + g_inv = zeros(3,3); + for i_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + for k_ind = 1 : 3 + g_inv(i_ind,j_ind) = g_inv(i_ind,j_ind) + C_FilmRef(i_ind,k_ind,j_ind,l_ind) * K_vec(k_ind) * K_vec(l_ind); + end + end + end + end + + Green_FilmRef_k(k1_ind,k2_ind,k3_ind,:,:) = inv(g_inv); + +end +end +end + +Green_FilmRef_k((kx==0),(ky==0),(kz==0),:,:) = 0; + +Green_FilmRef_k_11 = squeeze(Green_FilmRef_k(:,:,:,1,1)); +Green_FilmRef_k_12 = squeeze(Green_FilmRef_k(:,:,:,1,2)); +Green_FilmRef_k_13 = squeeze(Green_FilmRef_k(:,:,:,1,3)); + +Green_FilmRef_k_21 = squeeze(Green_FilmRef_k(:,:,:,2,1)); +Green_FilmRef_k_22 = squeeze(Green_FilmRef_k(:,:,:,2,2)); +Green_FilmRef_k_23 = squeeze(Green_FilmRef_k(:,:,:,2,3)); + +Green_FilmRef_k_31 = squeeze(Green_FilmRef_k(:,:,:,3,1)); +Green_FilmRef_k_32 = squeeze(Green_FilmRef_k(:,:,:,3,2)); +Green_FilmRef_k_33 = squeeze(Green_FilmRef_k(:,:,:,3,3));","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/CrystalRef_Transform_FilmRef.m",".m","285","3","P1_FilmRef = (2.^(1/2).*P2_CrystalRef)/2 - (2.^(1/2).*P3_CrystalRef)/2; +P2_FilmRef = (6.^(1/2).*P2_CrystalRef)/6 + (6.^(1/2).*P3_CrystalRef)/6 - (2.^(1/2).*3.^(1/2).*P1_CrystalRef)/3; +P3_FilmRef = (3.^(1/2).*P1_CrystalRef)/3 + (3.^(1/2).*P2_CrystalRef)/3 + (3.^(1/2).*P3_CrystalRef)/3;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/EigenstrainInFilm.m",".m","17055","32","%% Eigenstrains +% Transformed eigenstrains, in film reference frame +CalcEigenstrains + +%% Calculate the displacement field via Khachutaryan method +% For each k vector calculate displacement field +u_1_A_k = (- (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i)/2 - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_12.*kx_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_13.*kx_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i)/6 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/6 - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_11.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/2 - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_13.*ky_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_11.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_12.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_13.*kz_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_13.*kx_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_12.*kx_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_13.*ky_grid_3D.*1i)/6 - (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_11.*ky_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_13.*ky_grid_3D.*1i)/6 + (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_12.*kz_grid_3D.*1i)/6 - (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_11.*kz_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_12.*kz_grid_3D.*1i)/6).*C11 + (- (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i)/2 + (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_12.*kx_grid_3D.*1i)/3 + (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_13.*kx_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_11.*kx_grid_3D.*5i)/6 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_11.*kx_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_12.*ky_grid_3D.*5i)/6 + (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_11.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/2 + (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_13.*ky_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_12.*ky_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_13.*kz_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_11.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_13.*kz_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_12.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_13.*kz_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_13.*kx_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_12.*kx_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_13.*ky_grid_3D.*1i)/6 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_11.*ky_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_13.*ky_grid_3D.*1i)/6 - (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_12.*kz_grid_3D.*1i)/6 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_11.*kz_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_12.*kz_grid_3D.*1i)/6).*C12 + (- Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_12.*kx_grid_3D.*4i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_13.*kx_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_11.*kx_grid_3D.*1i)/3 + (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_11.*kx_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_11.*ky_grid_3D.*4i)/3 - Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_12.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_13.*ky_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_12.*ky_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_13.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_11.*kz_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_13.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_12.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_13.*kz_grid_3D.*4i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_13.*kx_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_12.*kx_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_11.*kx_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_13.*ky_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_11.*ky_grid_3D.*2i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_13.*ky_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_12.*ky_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_12.*kz_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_11.*kz_grid_3D.*2i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_12.*kz_grid_3D.*1i)/3).*C44; +u_2_A_k = (- (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i)/2 - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_22.*kx_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_23.*kx_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i)/6 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/6 - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_21.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/2 - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_23.*ky_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_21.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_22.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_23.*kz_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_23.*kx_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_22.*kx_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_23.*ky_grid_3D.*1i)/6 - (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_21.*ky_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_23.*ky_grid_3D.*1i)/6 + (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_22.*kz_grid_3D.*1i)/6 - (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_21.*kz_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_22.*kz_grid_3D.*1i)/6).*C11 + (- (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i)/2 + (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_22.*kx_grid_3D.*1i)/3 + (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_23.*kx_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_21.*kx_grid_3D.*5i)/6 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_21.*kx_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_22.*ky_grid_3D.*5i)/6 + (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_21.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/2 + (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_23.*ky_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_22.*ky_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_23.*kz_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_21.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_23.*kz_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_22.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_23.*kz_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_23.*kx_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_22.*kx_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_23.*ky_grid_3D.*1i)/6 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_21.*ky_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_23.*ky_grid_3D.*1i)/6 - (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_22.*kz_grid_3D.*1i)/6 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_21.*kz_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_22.*kz_grid_3D.*1i)/6).*C12 + (- Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_22.*kx_grid_3D.*4i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_23.*kx_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_21.*kx_grid_3D.*1i)/3 + (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_21.*kx_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_21.*ky_grid_3D.*4i)/3 - Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_22.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_23.*ky_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_22.*ky_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_23.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_21.*kz_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_23.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_22.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_23.*kz_grid_3D.*4i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_23.*kx_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_22.*kx_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_21.*kx_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_23.*ky_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_21.*ky_grid_3D.*2i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_23.*ky_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_22.*ky_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_22.*kz_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_21.*kz_grid_3D.*2i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_22.*kz_grid_3D.*1i)/3).*C44; +u_3_A_k = (- (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i)/2 - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_32.*kx_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_33.*kx_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i)/6 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/6 - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_31.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/2 - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_33.*ky_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_31.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_32.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_33.*kz_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_33.*kx_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_32.*kx_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_33.*ky_grid_3D.*1i)/6 - (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_31.*ky_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_33.*ky_grid_3D.*1i)/6 + (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_32.*kz_grid_3D.*1i)/6 - (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_31.*kz_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_32.*kz_grid_3D.*1i)/6).*C11 + (- (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i)/2 + (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_32.*kx_grid_3D.*1i)/3 + (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_33.*kx_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_31.*kx_grid_3D.*5i)/6 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_31.*kx_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_32.*ky_grid_3D.*5i)/6 + (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_31.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/2 + (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_33.*ky_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_32.*ky_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_33.*kz_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_31.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_33.*kz_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_32.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_33.*kz_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_33.*kx_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_32.*kx_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_33.*ky_grid_3D.*1i)/6 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_31.*ky_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_33.*ky_grid_3D.*1i)/6 - (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_32.*kz_grid_3D.*1i)/6 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_31.*kz_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_32.*kz_grid_3D.*1i)/6).*C12 + (- Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_32.*kx_grid_3D.*4i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_33.*kx_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_31.*kx_grid_3D.*1i)/3 + (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_31.*kx_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i)/3 - (Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_31.*ky_grid_3D.*4i)/3 - Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_32.*ky_grid_3D.*1i - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_33.*ky_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_32.*ky_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_33.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_31.*kz_grid_3D.*2i)/3 + (Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_33.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_32.*kz_grid_3D.*2i)/3 - (Eigenstrain_FilmRef_33_k.*Green_FilmRef_k_33.*kz_grid_3D.*4i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_33.*kx_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_32.*kx_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_31.*kx_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_33.*ky_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_13_k.*Green_FilmRef_k_31.*ky_grid_3D.*2i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_33.*ky_grid_3D.*1i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_23_k.*Green_FilmRef_k_32.*ky_grid_3D.*2i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_11_k.*Green_FilmRef_k_32.*kz_grid_3D.*1i)/3 + (2.^(1/2).*Eigenstrain_FilmRef_12_k.*Green_FilmRef_k_31.*kz_grid_3D.*2i)/3 - (2.^(1/2).*Eigenstrain_FilmRef_22_k.*Green_FilmRef_k_32.*kz_grid_3D.*1i)/3).*C44; + +% DC component = zero by def. +u_1_A_k((kx==0),(ky==0),(kz==0)) = 0; +u_2_A_k((kx==0),(ky==0),(kz==0)) = 0; +u_3_A_k((kx==0),(ky==0),(kz==0)) = 0; + +u_1_A = real( ifftn( u_1_A_k ) ); +u_2_A = real( ifftn( u_2_A_k ) ); +u_3_A = real( ifftn( u_3_A_k ) ); + +e_11_A_k = 1i .* kx_grid_3D .* u_1_A_k; +e_22_A_k = 1i .* ky_grid_3D .* u_2_A_k; +e_33_A_k = 1i .* kz_grid_3D .* u_3_A_k; +e_12_A_k = 0.5 * ( 1i .* kx_grid_3D .* u_2_A_k + 1i .* ky_grid_3D .* u_1_A_k ); +e_13_A_k = 0.5 * ( 1i .* kx_grid_3D .* u_3_A_k + 1i .* kz_grid_3D .* u_1_A_k ); +e_23_A_k = 0.5 * ( 1i .* kz_grid_3D .* u_2_A_k + 1i .* ky_grid_3D .* u_3_A_k ); + +e_11_A = real(ifftn(e_11_A_k)); +e_22_A = real(ifftn(e_22_A_k)); +e_33_A = real(ifftn(e_33_A_k)); +e_12_A = real(ifftn(e_12_A_k)); +e_13_A = real(ifftn(e_13_A_k)); +e_23_A = real(ifftn(e_23_A_k));","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/unfreezeColors.m",".m","3611","107","function unfreezeColors(h) +% unfreezeColors Restore colors of a plot to original indexed color. (v2.3) +% +% Useful if you want to apply a new colormap to plots whose +% colors were previously frozen with freezeColors. +% +% Usage: +% unfreezeColors unfreezes all objects in current axis, +% unfreezeColors(axh) same, but works on axis axh. axh can be vector. +% unfreezeColors(figh) same, but for all objects in figure figh. +% +% Has no effect on objects on which freezeColors was not already called. +% (Note: if colorbars were frozen using cbfreeze, use cbfreeze('off') to +% unfreeze them. See freezeColors for information on cbfreeze.) +% +% +% See also freezeColors, freezeColors_pub.html, cbfreeze. +% +% +% John Iversen (iversen@nsi.edu) 3/23/05 +% + +% Changes: +% JRI 9/1/06 now restores any object with frozen CData; +% can unfreeze an entire figure at once. +% JRI 4/7/10 Change documentation for colorbars + +% Free for all uses, but please retain the following: +% +% Original Author: +% John Iversen, 2005-10 +% john_iversen@post.harvard.edu + +error(nargchk(0,1,nargin,'struct')) + +appdatacode = 'JRI__freezeColorsData'; + +%default: operate on gca +if nargin < 1, + h = gca; +end + +if ~ishandle(h), + error('JRI:unfreezeColors:invalidHandle',... + 'The argument must be a valid graphics handle to a figure or axis') +end + +%if h is a figure, loop on its axes +if strcmp(get(h,'type'),'figure'), + h = get(h,'children'); +end + +for h1 = h', %loop on axes + + %process all children, acting only on those with saved CData + % ( in appdata JRI__freezeColorsData) + ch = findobj(h1); + + for hh = ch', + + %some object handles may be invalidated when their parent changes + % (e.g. restoring colors of a scattergroup unfortunately changes + % the handles of all its children). So, first check to make sure + % it's a valid handle + if ishandle(hh) + if isappdata(hh,appdatacode), + ad = getappdata(hh,appdatacode); + %get oroginal cdata + %patches have to be handled separately (see note in freezeColors) + if ~strcmp(get(hh,'type'),'patch'), + cdata = get(hh,'CData'); + else + cdata = get(hh,'faceVertexCData'); + cdata = permute(cdata,[1 3 2]); + end + indexed = ad{1}; + scalemode = ad{2}; + + %size consistency check + if all(size(indexed) == size(cdata(:,:,1))), + %ok, restore indexed cdata + if ~strcmp(get(hh,'type'),'patch'), + set(hh,'CData',indexed); + else + set(hh,'faceVertexCData',indexed); + end + %restore cdatamapping, if needed + g = get(hh); + if isfield(g,'CDataMapping'), + set(hh,'CDataMapping',scalemode); + end + %clear appdata + rmappdata(hh,appdatacode) + else + warning('JRI:unfreezeColors:internalCdataInconsistency',... + ['Could not restore indexed data: it is the wrong size. ' ... + 'Were the axis contents changed since the call to freezeColors?']) + end + + end %test if has our appdata + end %test ishandle + + end %loop on children + +end %loop on axes + +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/convert.m",".m","1116","42","function color = convert( P1, P2, P3, P1_min,P1_max,P2_min,P2_max,P3_min,P3_max ) +% convert P into a color + +% num = 1024; +% Area = hsv(num); +% Area_axis = linspace(-pi,pi,num); +% Phi = parula(num); +% Phi_axis = linspace(-pi/2,pi/2,num); +% +% +% % find where in the Area P is +% polar_angle = atan2(P2, P1); +% polar_angle = repmat(polar_angle,1,num); +% Area_axis = repmat(Area_axis,numel(P1),1); +% [~, ind] = min(abs(polar_angle - Area_axis),[],2); +% Area_val = Area(ind,:); +% +% % find where in the height P is +% Phi_axis = repmat(Phi_axis,numel(P1),1); +% phi_angle = acos( P3 ./ sqrt( P1.^2 + P2.^2 ) ); phi_angle = repmat(phi_angle,1,num); +% [~, ind] = min(abs(phi_angle - Phi_axis),[],2); +% Height_val = Phi(ind,:); +% +% color = cat(3,Area_val,Height_val); + + % normalize P + R = sqrt(P1.^2 + P2.^2 + P3.^2); + + P1 = P1 ./ R; + P2 = P2 ./ R; + P3 = P3 ./ R; + + R = (P3+1)/2; + G = (P1+1)/2; + B = (P2+1)/2; + + Area_val = [R,G,B]; + Height_val = [R,G,B]; + + color = cat(3,Area_val,Height_val); + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/SurfaceDepolEnergy.m",".m","142","6","%% Surface depolarization field +if( ELECTRIC == 1 && SURFACE_DEPOL == 1 ) + f3_surface_depol_2Dk = 0; +else + f3_surface_depol_2Dk = 0; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/CalcP_CrystalRef.m",".m","336","10","% Calculate P within the film +P1_film = P1_CrystalRef(:,:,interface_index:film_index); +P2_film = P2_CrystalRef(:,:,interface_index:film_index); +P3_film = P3_CrystalRef(:,:,interface_index:film_index); + +P1_val = vol_avg(abs(P1_film)) +P2_val = vol_avg(abs(P2_film)) +P3_val = vol_avg(abs(P3_film)) + +P_val = sqrt(P1_val^2+P2_val^2+P3_val^2)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/EnergyDensities.m",".m","5493","76","% Landau Energy +f_landau = a1 .* ( P1_CrystalRef.^2 + P2_CrystalRef.^2 + P3_CrystalRef.^2 ) + a11 .* ( P1_CrystalRef.^4 + P2_CrystalRef.^4 + P3_CrystalRef.^4 ) + ... + a12 .* ( P1_CrystalRef.^2 .* P2_CrystalRef.^2 + P1_CrystalRef.^2 .* P3_CrystalRef.^2 + P2_CrystalRef.^2 .* P3_CrystalRef.^2 ) + ... + a111 .* ( P1_CrystalRef.^6 + P2_CrystalRef.^6 + P3_CrystalRef.^6 ) + a112 .* ( P1_CrystalRef.^4 .* (P2_CrystalRef.^2 + P3_CrystalRef.^2) + P2_CrystalRef.^4 .* (P3_CrystalRef.^2 + P1_CrystalRef.^2) + P3_CrystalRef.^4 .* (P1_CrystalRef.^2 + P2_CrystalRef.^2) ) + ... + a123 .* ( P1_CrystalRef.^2 .* P2_CrystalRef.^2 .* P3_CrystalRef.^2 ) + ... + a1111 .* ( P1_CrystalRef.^8 + P2_CrystalRef.^8 + P3_CrystalRef.^8 ) + ... + a1112 .* ( P1_CrystalRef.^4 .* P2_CrystalRef.^4 + P2_CrystalRef.^4 .* P3_CrystalRef.^4 + P1_CrystalRef.^4 .* P3_CrystalRef.^4 ) + ... + a1123 .* ( P1_CrystalRef.^4 .* P2_CrystalRef.^2 .* P3_CrystalRef.^2 + P2_CrystalRef.^4 .* P3_CrystalRef.^2 .* P1_CrystalRef.^2 + P3_CrystalRef.^4 .* P1_CrystalRef.^2 .* P2_CrystalRef.^2 ); + +Eigenstrain_11 = Q11 * P1_CrystalRef.^2 + Q12 .* (P2_CrystalRef.^2 + P3_CrystalRef.^2); +Eigenstrain_22 = Q11 * P2_CrystalRef.^2 + Q12 .* (P1_CrystalRef.^2 + P3_CrystalRef.^2); +Eigenstrain_33 = Q11 * P3_CrystalRef.^2 + Q12 .* (P1_CrystalRef.^2 + P2_CrystalRef.^2); +Eigenstrain_23 = Q44 * P2_CrystalRef .* P3_CrystalRef; +Eigenstrain_13 = Q44 * P1_CrystalRef .* P3_CrystalRef; +Eigenstrain_12 = Q44 * P1_CrystalRef .* P2_CrystalRef; + +ElasticStrain_11 = e_11 + e_11_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_11; +ElasticStrain_22 = e_22 + e_22_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_22; +ElasticStrain_33 = e_33 + e_33_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_33; +ElasticStrain_12 = e_12 + e_12_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_12; +ElasticStrain_23 = e_23 + e_23_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_23; +ElasticStrain_13 = e_13 + e_13_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ) - Eigenstrain_13; + +f_elastic = (C11/2) .* ( ElasticStrain_11.^2 + ElasticStrain_22.^2 + ElasticStrain_33.^2 ) + ... + (C12) .* ( ElasticStrain_11 .* ElasticStrain_22 + ElasticStrain_22 .* ElasticStrain_33 + ElasticStrain_11 .* ElasticStrain_33 ) + ... + (2*C44) .* ( ElasticStrain_12.^2 + ElasticStrain_23.^2 + ElasticStrain_13.^2 ); + +% e11_tot = e_11 + e_11_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e22_tot = e_22 + e_22_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e33_tot = e_33 + e_33_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e12_tot = e_12 + e_12_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e23_tot = e_23 + e_23_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% e13_tot = e_13 + e_13_homo( P1_CrystalRef, P2_CrystalRef, P3_CrystalRef ); +% +% f_elastic_2 = b11 .* ( P1_CrystalRef.^4 + P2_CrystalRef.^4 + P3_CrystalRef.^4 ) + b12 .* ( P1_CrystalRef.^2 .* P2_CrystalRef.^2 + P1_CrystalRef.^2 .* P3_CrystalRef.^2 + P2_CrystalRef.^2 .* P3_CrystalRef.^2 ) + ... +% (C11/2) .* ( e11_tot.^2 + e22_tot.^2 + e33_tot.^2 ) + ... +% (C12) .* ( e11_tot .* e22_tot + e22_tot .* e33_tot + e11_tot .* e33_tot ) + ... +% (2*C44) .* ( e12_tot.^2 + e23_tot.^2 + e13_tot.^2 ) + ... +% -( q11 .* e11_tot + q12 .* e22_tot + q12 .* e33_tot ) .* P1_CrystalRef.^2 + ... +% -( q11 .* e22_tot + q12 .* e11_tot + q12 .* e33_tot ) .* P2_CrystalRef.^2 + ... +% -( q11 .* e33_tot + q12 .* e11_tot + q12 .* e22_tot ) .* P3_CrystalRef.^2 + ... +% -(2*q44) .* ( e12_tot .* P1_CrystalRef .* P2_CrystalRef + e23_tot .* P2_CrystalRef .* P3_CrystalRef + e13_tot .* P1_CrystalRef .* P3_CrystalRef ); + +P1_CrystalRef_2Dk = fft_2d_slices(P1_CrystalRef); P2_CrystalRef_2Dk = fft_2d_slices(P2_CrystalRef); P3_CrystalRef_2Dk = fft_2d_slices(P3_CrystalRef); + +P1_CrystalRef_1 = ifft_2d_slices(P1_CrystalRef_2Dk .* kx_grid_3D); +P1_CrystalRef_2 = ifft_2d_slices(P1_CrystalRef_2Dk .* ky_grid_3D); +P1_CrystalRef_3 = finite_diff_x3_first_der(P1_CrystalRef,dz); + +P2_CrystalRef_1 = ifft_2d_slices(P2_CrystalRef_2Dk .* kx_grid_3D); +P2_CrystalRef_2 = ifft_2d_slices(P2_CrystalRef_2Dk .* ky_grid_3D); +P2_CrystalRef_3 = finite_diff_x3_first_der(P2_CrystalRef,dz); + +P3_CrystalRef_1 = ifft_2d_slices(P3_CrystalRef_2Dk .* kx_grid_3D); +P3_CrystalRef_2 = ifft_2d_slices(P3_CrystalRef_2Dk .* ky_grid_3D); +P3_CrystalRef_3 = finite_diff_x3_first_der(P3_CrystalRef,dz); + +G12 = 0; H44 = 0.6 * G110; H14 = 0; +E_1_applied = 0; E_2_applied = 0; E_3_applied = 0; + +f_grad = (G11/2) * ( P1_CrystalRef_1.^2 + P2_CrystalRef_2.^2 + P3_CrystalRef_3.^2 ) + ... + G12 .* ( P1_CrystalRef_1 .* P2_CrystalRef_2 + P2_CrystalRef_2 .* P3_CrystalRef_3 + P3_CrystalRef_3 .* P1_CrystalRef_1 ) + ... + (H44/2) .* ( P1_CrystalRef_2.^2 + P2_CrystalRef_1.^2 + P2_CrystalRef_3.^2 + P3_CrystalRef_2.^2 + P1_CrystalRef_3.^2 + P3_CrystalRef_1.^2 ) + ... + (H14 - G12) .* ( P1_CrystalRef_2 .* P2_CrystalRef_1 + P1_CrystalRef_3 .* P3_CrystalRef_1 + P2_CrystalRef_3 .* P3_CrystalRef_2 ); + +f_elec = (-1/2) .* ( E_1_depol .* P1_CrystalRef + E_2_depol .* P2_CrystalRef + E_3_depol .* P3_CrystalRef ); + +f_elec_ext = -( E_1_applied .* P1_CrystalRef + E_2_applied .* P2_CrystalRef + E_3_applied .* P3_CrystalRef ); + +F_landau = sum(sum(sum(f_landau))); +F_elastic = sum(sum(sum(f_elastic))); +F_grad = sum(sum(sum(f_grad))); +F_elec = sum(sum(sum(f_elec))); +F_elec_ext = sum(sum(sum(f_elec_ext))); + +[F_landau, F_elastic,F_grad,F_elec]","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Render3D_CrystalRef.m",".m","124","1","Visualize_3D(P1_CrystalRef,P2_CrystalRef,P3_CrystalRef,x_grid*1e9,y_grid*1e9,z_grid*1e9,interface_index,film_index,Nx,Ny,Nz)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Visualize_3D.m",".m","5720","136","function out = Visualize_3D(P1,P2,P3,x_grid,y_grid,z_grid,interface_index,film_index,Nx,Ny,Nz_film) + P1_film = P1(:,:,interface_index:film_index); + P2_film = P2(:,:,interface_index:film_index); + P3_film = P3(:,:,interface_index:film_index); + + x_grid_film = x_grid(:,:,interface_index:film_index); + y_grid_film = y_grid(:,:,interface_index:film_index); + z_grid_film = z_grid(:,:,interface_index:film_index); + + P1_max = max(max(max(P1_film))); + P1_min = min(min(min(P1_film))); + + P2_max = max(max(max(P2_film))); + P2_min = min(min(min(P2_film))); + + P3_max = max(max(max(P3_film))); + P3_min = min(min(min(P3_film))); + + Nz_film = film_index - interface_index + 1; + + %% Get the sides of the cube... + yz_1_x = x_grid_film(1,:,:); yz_1_x = reshape(yz_1_x,Ny,Nz_film); + yz_1_y = y_grid_film(1,:,:); yz_1_y = reshape(yz_1_y,Ny,Nz_film); + yz_1_z = z_grid_film(1,:,:); yz_1_z = reshape(yz_1_z,Ny,Nz_film); + + yz_1_P1 = P1_film(1,:,:); yz_1_P1 = reshape(yz_1_P1,Ny*Nz_film,1); + yz_1_P2 = P2_film(1,:,:); yz_1_P2 = reshape(yz_1_P2,Ny*Nz_film,1); + yz_1_P3 = P3_film(1,:,:); yz_1_P3 = reshape(yz_1_P3,Ny*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(yz_1_P1,yz_1_P2,yz_1_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Ny,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Ny,Nz_film,3); + yz_1_color = (Area+Height)/2; + + surf(yz_1_x,yz_1_y,yz_1_z,yz_1_color); + hold on; + + %% Get the sides of the cube... + yz_2_x = x_grid_film(end,:,:); yz_2_x = reshape(yz_2_x,Ny,Nz_film); + yz_2_y = y_grid_film(end,:,:); yz_2_y = reshape(yz_2_y,Ny,Nz_film); + yz_2_z = z_grid_film(end,:,:); yz_2_z = reshape(yz_2_z,Ny,Nz_film); + + yz_2_P1 = P1_film(end,:,:); yz_2_P1 = reshape(yz_2_P1,Ny*Nz_film,1); + yz_2_P2 = P2_film(end,:,:); yz_2_P2 = reshape(yz_2_P2,Ny*Nz_film,1); + yz_2_P3 = P3_film(end,:,:); yz_2_P3 = reshape(yz_2_P3,Ny*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(yz_2_P1,yz_2_P2,yz_2_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Ny,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Ny,Nz_film,3); + yz_2_color = (Area+Height)/2; + + surf(yz_2_x,yz_2_y,yz_2_z,yz_2_color); + + + %% Get the sides of the cube... + xz_1_x = x_grid_film(:,1,:); xz_1_x = reshape(xz_1_x,Nx,Nz_film); + xz_1_y = y_grid_film(:,1,:); xz_1_y = reshape(xz_1_y,Nx,Nz_film); + xz_1_z = z_grid_film(:,1,:); xz_1_z = reshape(xz_1_z,Nx,Nz_film); + + xz_1_P1 = P1_film(:,1,:); xz_1_P1 = reshape(xz_1_P1,Nx*Nz_film,1); + xz_1_P2 = P2_film(:,1,:); xz_1_P2 = reshape(xz_1_P2,Nx*Nz_film,1); + xz_1_P3 = P3_film(:,1,:); xz_1_P3 = reshape(xz_1_P3,Nx*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xz_1_P1,xz_1_P2,xz_1_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Nz_film,3); + xz_1_color = (Area+Height)/2; + + surf(xz_1_x,xz_1_y,xz_1_z,xz_1_color); + + %% Get the sides of the cube... + xz_2_x = x_grid_film(:,end,:); xz_2_x = reshape(xz_2_x,Nx,Nz_film); + xz_2_y = y_grid_film(:,end,:); xz_2_y = reshape(xz_2_y,Nx,Nz_film); + xz_2_z = z_grid_film(:,end,:); xz_2_z = reshape(xz_2_z,Nx,Nz_film); + + xz_2_P1 = P1_film(:,end,:); xz_2_P1 = reshape(xz_2_P1,Nx*Nz_film,1); + xz_2_P2 = P2_film(:,end,:); xz_2_P2 = reshape(xz_2_P2,Nx*Nz_film,1); + xz_2_P3 = P3_film(:,end,:); xz_2_P3 = reshape(xz_2_P3,Nx*Nz_film,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xz_2_P1,xz_2_P2,xz_2_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Nz_film,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Nz_film,3); + xz_2_color = (Area+Height)/2; + + surf(xz_2_x,xz_2_y,xz_2_z,xz_2_color); + + %% Get the sides of the cube... + xy_1_x = x_grid_film(:,:,1); xy_1_x = reshape(xy_1_x,Nx,Ny); + xy_1_y = y_grid_film(:,:,1); xy_1_y = reshape(xy_1_y,Nx,Ny); + xy_1_z = z_grid_film(:,:,1); xy_1_z = reshape(xy_1_z,Nx,Ny); + + xy_1_P1 = P1_film(:,:,1); xy_1_P1 = reshape(xy_1_P1,Nx*Ny,1); + xy_1_P2 = P2_film(:,:,1); xy_1_P2 = reshape(xy_1_P2,Nx*Ny,1); + xy_1_P3 = P3_film(:,:,1); xy_1_P3 = reshape(xy_1_P3,Nx*Ny,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xy_1_P1,xy_1_P2,xy_1_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Ny,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Ny,3); + xy_1_color = (Area+Height)/2; + + surf(xy_1_x,xy_1_y,xy_1_z,xy_1_color); + + %% Get the sides of the cube... + xy_2_x = x_grid_film(:,:,end); xy_2_x = reshape(xy_2_x,Nx,Ny); + xy_2_y = y_grid_film(:,:,end); xy_2_y = reshape(xy_2_y,Nx,Ny); + xy_2_z = z_grid_film(:,:,end); xy_2_z = reshape(xy_2_z,Nx,Ny); + + xy_2_P1 = P1_film(:,:,end); xy_2_P1 = reshape(xy_2_P1,Nx*Ny,1); + xy_2_P2 = P2_film(:,:,end); xy_2_P2 = reshape(xy_2_P2,Nx*Ny,1); + xy_2_P3 = P3_film(:,:,end); xy_2_P3 = reshape(xy_2_P3,Nx*Ny,1); + + % Switch P1,P2,P3 into a color now... + + C = convert(xy_2_P1,xy_2_P2,xy_2_P3,P1_min,P1_max,P2_min,P2_max,P3_min,P3_max); + Area = squeeze(C(:,:,1)); Area = reshape(Area,Nx,Ny,3); + Height = squeeze(C(:,:,1)); Height = reshape(Height,Nx,Ny,3); + xy_2_color = (Area+Height)/2; + + surf(xy_2_x,xy_2_y,xy_2_z,xy_2_color); + + %% + axis([min(min(min(x_grid_film))) max(max(max(x_grid_film))) ... + min(min(min(y_grid_film))) max(max(max(y_grid_film))) ... + min(min(min(z_grid_film))) max(max(max(z_grid_film)))] ) + shading flat +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/CalcElecEnergy.m",".m","3453","93","if( ELECTRIC ) + + %% Solve particular solution within the entire sample... + P1_FilmRef_3Dk = fftn(P1_FilmRef); + P2_FilmRef_3Dk = fftn(P2_FilmRef); + P3_FilmRef_3Dk = fftn(P3_FilmRef); + + %%%%%%%% + %%%%%%%% + %% + %% Isotropic relative background permittivity constant --> Nothing changes!! + %% + %%%%%%%% + %%%%%%%% + potential_A_k = -1i .* (kx_grid_3D .* P1_FilmRef_3Dk + ky_grid_3D .* P2_FilmRef_3Dk + kz_grid_3D .* P3_FilmRef_3Dk) ./ ... + ( permittivity_0 .* (k_electric_11 .* kx_grid_3D.^2 + k_electric_22 .* ky_grid_3D.^2 + k_electric_33 .* kz_grid_3D.^2) ); + potential_A_k(k_mag_3D == 0) = 0; + potential_A = real(ifftn(potential_A_k)); + + E_A_1_k = -1i .* kx_grid_3D .* potential_A_k; + E_A_2_k = -1i .* ky_grid_3D .* potential_A_k; + E_A_3_k = -1i .* kz_grid_3D .* potential_A_k; + + E_A_1 = real(ifftn(E_A_1_k)); + E_A_2 = real(ifftn(E_A_2_k)); + E_A_3 = real(ifftn(E_A_3_k)); + + %% Homogenous solution boundary condition application, 2D FT solution + C_mat = zeros(Nx,Ny,2); + potential_bc_interface = squeeze(potential_A(:,:,interface_index)); + potential_bc_film = squeeze(potential_A(:,:,film_index)); + potential_bc_interface_2Dk = -fft2(potential_bc_interface); + potential_bc_film_2Dk = -fft2(potential_bc_film); + potential_bc_given_mat = cat(3,potential_bc_interface_2Dk,potential_bc_film_2Dk); + + potential_B_2Dk = zeros(Nx,Ny,Nz); + potential_B_2Dk_d3 = zeros(Nx,Ny,Nz); + + for k1_ind = 1 : Nx + for k2_ind = 1 : Ny + + C_mat(k1_ind,k2_ind,:) = squeeze(electric_bc_mats_inv(k1_ind,k2_ind,:,:)) * squeeze(potential_bc_given_mat(k1_ind,k2_ind,:)); + + end + end + + C1 = squeeze(C_mat(:,:,1)); C2 = squeeze(C_mat(:,:,2)); + p = sqrt((k_electric_11*kx_grid_2D.^2 + k_electric_22*ky_grid_2D.^2)/k_electric_33); + for z_loop = 1 : numel(z_axis) + potential_B_2Dk(:,:,z_loop) = C1 .* exp(z_axis(z_loop) .* p) + C2 .* exp(-z_axis(z_loop) .* p); + potential_B_2Dk_d3(:,:,z_loop) = p .* C1 .* exp(z_axis(z_loop) .* p) - p .* C2 .* exp(-z_axis(z_loop) .* p); + end + + % Fourier space origin + C_origin = electric_bc_mats_inv_korigin * squeeze(potential_bc_given_mat(1,1,:)); + C1 = C_origin(1); C2 = C_origin(2); + potential_B_2Dk(1,1,:) = C1 * z_axis + C2; + potential_B_2Dk_d3(1,1,:) = C1; + + %% Total Potential + potential_B = ifft_2d_slices(potential_B_2Dk); + potential_FilmRef = potential_A + potential_B; + + % E field + E_B_2Dk_1 = -1i .* kx_grid_3D .* potential_B_2Dk; + E_B_2Dk_2 = -1i .* ky_grid_3D .* potential_B_2Dk; + E_B_2Dk_3 = -potential_B_2Dk_d3; + + E_B_1 = ifft_2d_slices(E_B_2Dk_1); + E_B_2 = ifft_2d_slices(E_B_2Dk_2); + E_B_3 = ifft_2d_slices(E_B_2Dk_3); + + % Depolarization field, not including surface charge effect + E_FilmRef_1_depol = E_A_1 + E_B_1; + E_FilmRef_2_depol = E_A_2 + E_B_2; + E_FilmRef_3_depol = E_A_3 + E_B_3; + + %% Electrical energy define + f1_elec = -0.5 * E_FilmRef_1_depol .* in_film .* Nucleation_Sites; + f2_elec = -0.5 * E_FilmRef_2_depol .* in_film .* Nucleation_Sites; + f3_elec = -0.5 * E_FilmRef_3_depol .* in_film .* Nucleation_Sites; + + f1_elec_2Dk = fft_2d_slices(f1_elec); + f2_elec_2Dk = fft_2d_slices(f2_elec); + f3_elec_2Dk = fft_2d_slices(f3_elec); + +else + + f1_elec_2Dk = 0; f2_elec_2Dk = 0; f3_elec_2Dk = 0; + E_FilmRef_1_depol = 0; E_FilmRef_2_depol = 0; E_FilmRef_3_depol = 0; + potential_FilmRef = 0; + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/ElectrostaticSetup.m",".m","614","19","electric_bc_mats_inv = zeros(Nx,Ny,2,2); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if(k1_ind ~= 1 || k2_ind ~= 1) + eta_1 = kx_grid_2D(k1_ind,k2_ind); + eta_2 = ky_grid_2D(k1_ind,k2_ind); + p = sqrt((k_electric_11*eta_1^2 + k_electric_22*eta_2^2)/k_electric_33); + + potential_sol_mat = [ exp(h_int*p), exp(-h_int*p); ... + exp(h_film*p), exp(-h_film*p)]; + + electric_bc_mats_inv(k1_ind,k2_ind,:,:) = inv(potential_sol_mat); + end +end +end + +electric_bc_mats_inv_korigin = inv( [h_int, 1;... + h_film, 1] );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Setup_BST.m",".m","4981","165","% Run inputs +LOAD = 0; % 1 = Load initial conditions from file called init.mat, 0 = random P initial conditions +E_1_applied_FilmRef = 0; E_2_applied_FilmRef = 0; E_3_applied_FilmRef = 0; % in V/m, 1e5 V/m = 1 kV/cm +T = 17; % in C +Us_11 = 0.5068e-2; % unitless misfit strain +Us_22 = Us_11; % anisotropic misfit strain +% BST composition +BTO_pct = 0.8; STO_pct = 1 - BTO_pct; + + + + + +%% ---- Nothing needed to modify below ---- %% + +%% Convergence +epsilon = 1e-2; % convergence criterion +saves = [0 : 1000 : 20000]; % save after this many iterations + +%% Grid Size +Nx = 64; Ny = Nx; Nz = 36; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 32; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 1 && ELASTIC; % automatically 0 if no elastic energy +% no heterogenous elastic relaxation if no elastic energy + +ELECTRIC = 1; +SURFACE_DEPOL = 0; % depolarization energy due to uncompensated surface charges + +NUCLEATE = 0; % nucleation sites, places that don't change during temporal evolution, 1 -> during hysteresis calcs + +ThermConst = 0; % No thermal energy + +%% BTO = http://www.ems.psu.edu/~chen/publications/YL2005APL.pdf +C11_BTO = 1.78 * 1e11; +C12_BTO = 0.964 * 1e11; +C44_BTO = 1.22 * 1e11; + +Q11_BTO = 0.10; +Q12_BTO = -0.034; +Q44_BTO = 0.029; + +a1_BTO = @(T) 4.124 * ( T - 115 ) * 1e5; +a11_BTO = -2.097 * 1e8; +a12_BTO = 7.974 * 1e8; +a111_BTO = 1.294 * 1e9; +a112_BTO = -1.950 * 1e9; +a123_BTO = -2.5 * 1e9; +a1111_BTO = 3.863 * 1e10; +a1112_BTO = 2.529 * 1e10; +a1122_BTO = 1.637 * 1e10; +a1123_BTO = 1.367 * 1e10; + +%% STO, Table VII, Table I last column +% http://www.wolframalpha.com/input/?i=1+dyn%2Fcm%5E2 +% 1 dyn/cm^2 = 0.1 Pa +C11_STO = 3.36 * 1e11; +C12_STO = 1.07 * 1e11; +C44_STO = 1.27 * 1e11; + +% STO Yu Luan Li PRB 184112, Table II +% 1 cm^4 / esu^2 = 8.988 * 1e10 m^4 / C^2 +% http://www.wolframalpha.com/input/?i=(1+cm)%5E4%2F(3.3356e-10+coulomb)%5E2 +Q11_STO = 4.57 * 1e-2; +Q12_STO = -1.348 * 1e-2; +Q44_STO = 0.957 * 1e-2; + +% STO Yu Luan Li PRB 184112, Table III a1 (1st, from ref 6, 16, 22), Table +% VII a11, a12, a1 +% Shirokov, Yuzyu, PRB 144118, Table I STO in parantheses + +% 1 cm^2 * dyn / esu^2 = 8.9876 * 1e9 J * m^2 / C +a1_STO = @(T) 4.05 * 1e7 * ( coth( 54 / (T+273) ) - coth(54/30) ); + +% 1 cm^6 * dyn / esu^4 = 8.0776 * 1e20 J * m^5 / C^4 +a11_STO = 17 * 1e8; +a12_STO = 13.7 * 1e8; + +a111_STO = 0; +a112_STO = 0; +a123_STO = 0; +a1111_STO = 0; +a1112_STO = 0; +a1122_STO = 0; +a1123_STO = 0; + +%% Elastic Tensor +C11 = C11_BTO * BTO_pct + C11_STO * STO_pct; +C12 = C12_BTO * BTO_pct + C12_STO * STO_pct; +C44 = C44_BTO * BTO_pct + C44_STO * STO_pct; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + +%% Electrostriction +q11_BTO = C11_BTO * Q11_BTO + 2 * C12_BTO * Q12_BTO; +q12_BTO = C11_BTO * Q12_BTO + C12_BTO * (Q11_BTO + Q12_BTO); +q44_BTO = 2 * C44_BTO * Q44_BTO; + +q11_STO = C11_STO * Q11_STO + 2 * C12_STO * Q12_STO; +q12_STO = C11_STO * Q12_STO + C12_STO * (Q11_STO + Q12_STO); +q44_STO = 2 * C44_STO * Q44_STO; + +q11 = q11_BTO * BTO_pct + q11_STO * STO_pct; +q12 = q12_BTO * BTO_pct + q12_STO * STO_pct; +q44 = q44_BTO * BTO_pct + q44_STO * STO_pct; + +q11_h = q11 + 2 * q12; +q22_h = q11 - q12; +C11_h = C11 + 2 * C12; +C22_h = C11 - C12; + +Q11 = (1/3) * ( (q11_h/C11_h) + (2 * q22_h/C22_h) ); +Q12 = (1/3) * ( (q11_h/C11_h) - (q22_h/C22_h) ); +Q44 = q44 / (2 * C44); + +%% LGD Constants, stress free BTO +a1_T = @(T) a1_BTO(T) * BTO_pct + a1_STO(T) * STO_pct; +a1 = a1_T(T); +a11 = a11_BTO * BTO_pct + a11_STO * STO_pct; +a12 = a12_BTO * BTO_pct + a12_STO * STO_pct; +a111 = a111_BTO * BTO_pct + a111_STO * STO_pct; +a112 = a112_BTO * BTO_pct + a112_STO * STO_pct; +a123 = a123_BTO * BTO_pct + a123_STO * STO_pct; +a1111 = a1111_BTO * BTO_pct + a1111_STO * STO_pct; +a1112 = a1112_BTO * BTO_pct + a1112_STO * STO_pct; +a1122 = a1122_BTO * BTO_pct + a1122_STO * STO_pct; +a1123 = a1123_BTO * BTO_pct + a1123_STO * STO_pct; + +%% Simulation Size +l_0 = 1e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = 0.5*l_0*(Nz-1); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = l_0^2 * a0; +G11 = 0.6 * G110; +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = 0.6 * G110; % H44 = G44 + G44' + +%% Run time setup +t_0 = 1/a0; +dt = 0.0125/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% Electrical +permittivity_0 = 8.85418782*1e-12; +k11 = 1000; k22 = k11; k33 = k11;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/HomoStrainSetup.m",".m","1587","20","TotalStrain_FilmRef_homo_11 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) Us_11; + +TotalStrain_FilmRef_homo_22 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) Us_22; + +TotalStrain_FilmRef_homo_12 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) Us_12; + +TotalStrain_FilmRef_homo_33 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) -(C11*TotalStrain_FilmRef_homo_11(P1_FilmRef, P2_FilmRef, P3_FilmRef) ... + + 2*C12*TotalStrain_FilmRef_homo_11(P1_FilmRef, P2_FilmRef, P3_FilmRef) ... + + C11*TotalStrain_FilmRef_homo_22(P1_FilmRef, P2_FilmRef, P3_FilmRef) + 2*C12*TotalStrain_FilmRef_homo_22(P1_FilmRef, P2_FilmRef, P3_FilmRef) ... + - 2*C44*TotalStrain_FilmRef_homo_11(P1_FilmRef, P2_FilmRef, P3_FilmRef) - 2*C44*TotalStrain_FilmRef_homo_22(P1_FilmRef, P2_FilmRef, P3_FilmRef))/(C11 + 2*C12 + 4*C44); + +TotalStrain_FilmRef_homo_23 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) -(2^(1/2)*C11*TotalStrain_FilmRef_homo_11(P1_FilmRef, P2_FilmRef, P3_FilmRef)... + - 2^(1/2)*C12*TotalStrain_FilmRef_homo_11(P1_FilmRef, P2_FilmRef, P3_FilmRef) ... + - 2^(1/2)*C11*TotalStrain_FilmRef_homo_22(P1_FilmRef, P2_FilmRef, P3_FilmRef) ... + + 2^(1/2)*C12*TotalStrain_FilmRef_homo_22(P1_FilmRef, P2_FilmRef, P3_FilmRef) ... + - 2*2^(1/2)*C44*TotalStrain_FilmRef_homo_11(P1_FilmRef, P2_FilmRef, P3_FilmRef) ... + + 2*2^(1/2)*C44*TotalStrain_FilmRef_homo_22(P1_FilmRef, P2_FilmRef, P3_FilmRef))/(4*(C11 - C12 + C44)); + +TotalStrain_FilmRef_homo_13 = @(P1_FilmRef, P2_FilmRef, P3_FilmRef) (TotalStrain_FilmRef_homo_12(P1_FilmRef, P2_FilmRef, P3_FilmRef) ... + * (2^(1/2)*C12 - 2^(1/2)*C11 + 2*2^(1/2)*C44))/(2*(C11 - C12 + C44));","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Main.m",".m","831","44","clc; +rng(1) + +%% Setup stuff +FundamentalConstants; +Setup; +AxesSetup; +Nucleate; +TransformElasticTensor; +GreenTensorSetup; +HomoStrainSetup; + +%% Setup energy stuff +if(VPA_ELASTIC_ON) + InfinitePlateSetup_vpa; +else + InfinitePlateSetup; +end + +if(VPA_ELECTRIC_ON) + ElectrostaticSetup_vpa; +else + ElectrostaticSetup; +end + +%% Initial conditions +InitP; + +%% Energies +CalcElasticEnergy +CalcElecEnergy +ThermalNoise +LandauEnergy +SurfaceDepolEnergy +ExternalEFieldEnergy + +f1_2Dk = f1_landau_2Dk + f1_elec_2Dk + f1_elastic_2Dk + f1_ext_E_2Dk + Thermal_Noise_1_2Dk; +f2_2Dk = f2_landau_2Dk + f2_elec_2Dk + f2_elastic_2Dk + f2_ext_E_2Dk + Thermal_Noise_2_2Dk; +f3_2Dk = f3_landau_2Dk + f3_elec_2Dk + f3_elastic_2Dk + f3_ext_E_2Dk + Thermal_Noise_3_2Dk + f3_surface_depol_2Dk; +c = 0; % Flag for do while loop +error = inf; + +%% Main loop +MainLoop","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/ElectrostaticSetup_vpa.m",".m","694","22","% Use vpa to get more accurate inverted matrices + +electric_bc_mats_inv = zeros(Nx,Ny,2,2); + +for k1 = 1 : Nx +for k2 = 1 : Ny + if(k1 ~= 1 || k2 ~= 1) + eta_1 = kx_grid_2D(k1,k2); + eta_2 = ky_grid_2D(k1,k2); + p = sqrt((k_electric_11*eta_1^2 + k_electric_22*eta_2^2)/k_electric_33); + + potential_sol_mat = [ exp(h_int*p), exp(-h_int*p); ... + exp(h_film*p), exp(-h_film*p)]; + + vpa_mat = vpa(potential_sol_mat); + electric_bc_mats_inv(k1,k2,:,:) = double(inv(vpa_mat)); + end +end +end + +electric_bc_mats_inv_korigin = double ( inv( vpa([h_int, 1;... + h_film, 1]) ) );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/FilmRef_Transform_CrystalRef.m",".m","316","4","% Transform back from film ref to crystal ref +P1_CrystalRef = (3.^(1/2).*P3_FilmRef)/3 - (2.^(1/2).*3.^(1/2).*P2_FilmRef)/3; +P2_CrystalRef = (2.^(1/2).*P1_FilmRef)/2 + (3.^(1/2).*P3_FilmRef)/3 + (6.^(1/2).*P2_FilmRef)/6; +P3_CrystalRef = (3.^(1/2).*P3_FilmRef)/3 - (2.^(1/2).*P1_FilmRef)/2 + (6.^(1/2).*P2_FilmRef)/6;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/R_Phases.m",".m","1102","19","r1_plus = ( P1_CrystalRef > 0.3 ) & ( P2_CrystalRef > 0.3 ) & ( P3_CrystalRef > 0.3 ); +r2_plus = ( P1_CrystalRef < -0.3 ) & ( P2_CrystalRef > 0.3 ) & ( P3_CrystalRef > 0.3 ); +r3_plus = ( P1_CrystalRef < -0.3 ) & ( P2_CrystalRef < -0.3 ) & ( P3_CrystalRef > 0.3 ); +r4_plus = ( P1_CrystalRef > 0.3 ) & ( P2_CrystalRef < -0.3 ) & ( P3_CrystalRef > 0.3 ); + +r1_minus = ( P1_CrystalRef < -0.3 ) & ( P2_CrystalRef < -0.3 ) & ( P3_CrystalRef < -0.3 ); +r2_minus = ( P1_CrystalRef > 0.3 ) & ( P2_CrystalRef < -0.3 ) & ( P3_CrystalRef < -0.3 ); +r3_minus = ( P1_CrystalRef > 0.3 ) & ( P2_CrystalRef > 0.3 ) & ( P3_CrystalRef < -0.3 ); +r4_minus = ( P1_CrystalRef < -0.3 ) & ( P2_CrystalRef > 0.3 ) & ( P3_CrystalRef < -0.3 ); + +sum(sum(sum(r1_plus))) / sum(sum(sum(in_film))) +sum(sum(sum(r2_plus))) / sum(sum(sum(in_film))) +sum(sum(sum(r3_plus))) / sum(sum(sum(in_film))) +sum(sum(sum(r4_plus))) / sum(sum(sum(in_film))) + +sum(sum(sum(r1_minus))) / sum(sum(sum(in_film))) +sum(sum(sum(r2_minus))) / sum(sum(sum(in_film))) +sum(sum(sum(r3_minus))) / sum(sum(sum(in_film))) +sum(sum(sum(r4_minus))) / sum(sum(sum(in_film)))","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/vol_avg.m",".m","64","5","function out = vol_avg( f ) + + out = mean(mean(mean(f))); + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/GradEnergy.m",".m","631","13","%% Gradient Free Energy +% Treat the z term not in FFT... +P1_FilmRef_d3_d3 = finite_diff_x3_second_der(P1_FilmRef_prev_2Dk,dz); +P2_FilmRef_d3_d3 = finite_diff_x3_second_der(P2_FilmRef_prev_2Dk,dz); +P3_FilmRef_d3_d3 = finite_diff_x3_second_der(P3_FilmRef_prev_2Dk,dz); + +G1_no_d3 = G11 * kx_grid_3D.^2 + H44 * ky_grid_3D.^2; +G2_no_d3 = G11 * ky_grid_3D.^2 + H44 * kx_grid_3D.^2; +G3_no_d3 = H44 * (kx_grid_3D.^2 + ky_grid_3D.^2); + +G1_d3_part = H44 * P1_FilmRef_d3_d3 .* in_film .* Nucleation_Sites; +G2_d3_part = H44 * P2_FilmRef_d3_d3 .* in_film .* Nucleation_Sites; +G3_d3_part = G11 * P3_FilmRef_d3_d3 .* in_film .* Nucleation_Sites; ","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/SaveData.m",".m","1595","35","save(sprintf('%sfinal__%g Us11__%g Us22__%gC__%gkV-cm__%s.mat',PATH,Us_11*1e2,Us_22*1e2,Temperature,E_1_applied_FilmRef/1e5,STRING),... + 'P1_FilmRef','P2_FilmRef','P3_FilmRef',... + 'P1_FilmRef_prev','P2_FilmRef_prev','P3_FilmRef_prev',... + ... + 'a1','a1_T','a11','a111','a1111','a1112','a112','a1122','a1123','a12','a123',... + ... + 'C11','C12','C44','C_CrystalRef',... + 'TotalStrain_FilmRef_11','TotalStrain_FilmRef_22','TotalStrain_FilmRef_33','TotalStrain_FilmRef_12','TotalStrain_FilmRef_13','TotalStrain_FilmRef_23',... + 'u_FilmRef_1','u_FilmRef_2','u_FilmRef_3',... + 'TotalStrain_FilmRef_homo_11','TotalStrain_FilmRef_homo_22','TotalStrain_FilmRef_homo_33','TotalStrain_FilmRef_homo_12','TotalStrain_FilmRef_homo_13','TotalStrain_FilmRef_homo_23',... + ... + 'q11','q12','q44',... + 'Q11','Q12','Q44',... + ... + 'E_1_applied_FilmRef','E_2_applied_FilmRef','E_3_applied_FilmRef',... + 'E_FilmRef_1_depol','E_FilmRef_2_depol','E_FilmRef_3_depol',... + 'k_electric_11','k_electric_22','k_electric_33',... + 'potential_FilmRef',... + ... + 'G11','G12','H14','H44','G110',... + 'dt',... + 'l_0',... + 'h_film','h_int','h_sub',... + 'interface_index','film_index',... + 'x_axis','y_axis','z_axis',... + 'x_grid','y_grid','z_grid',... + 'Nx','Ny','Nz',... + ... + 'VPA_ELECTRIC_ON','VPA_ELASTIC_ON','ELASTIC','HET_ELASTIC_RELAX',... + 'ELECTRIC','SURFACE_DEPOL','NUCLEATE','ThermConst','LOAD',... + ... + 'Temperature','Us_11','Us_22','Us_12',... + ... + 'Transform_Matrix','in_film','Nucleation_Sites','errors'... + );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/MainLoop.m",".m","2073","63","if( 7 ~= exist(PATH,'dir')) + mkdir(PATH); +end + +errors = zeros(saves(end),1); + +while (c == 0 || error > epsilon) && c < saves(end) + + % saving + if( sum(c == saves) == 1 ) + save(sprintf('%s%g t__%g Us11__%g Us22__%gC__%gkV-cm__%s.mat',PATH,c,Us_11*1e2,Us_22*1e2,Temperature,E_1_applied_FilmRef/1e5,STRING),'P1_FilmRef','P2_FilmRef','P3_FilmRef'); + end + + % Previous iteration + P1_FilmRef_prev_2Dk = P1_FilmRef_2Dk; + f1_prev_2Dk = f1_2Dk; + + P2_FilmRef_prev_2Dk = P2_FilmRef_2Dk; + f2_prev_2Dk = f2_2Dk; + + P3_FilmRef_prev_2Dk = P3_FilmRef_2Dk; + f3_prev_2Dk = f3_2Dk; + + P1_FilmRef_prev = P1_FilmRef; + P2_FilmRef_prev = P2_FilmRef; + P3_FilmRef_prev = P3_FilmRef; + + % Next iteration + GradEnergy % d3_part uses previous P's + P1_FilmRef_2Dk = (( P1_FilmRef_prev_2Dk + dt .* -f1_prev_2Dk + dt .* G1_d3_part ) ./ ( 1 + dt .* G1_no_d3 )); + P2_FilmRef_2Dk = (( P2_FilmRef_prev_2Dk + dt .* -f2_prev_2Dk + dt .* G2_d3_part ) ./ ( 1 + dt .* G2_no_d3 )); + P3_FilmRef_2Dk = (( P3_FilmRef_prev_2Dk + dt .* -f3_prev_2Dk + dt .* G3_d3_part ) ./ ( 1 + dt .* G3_no_d3 )); + + P1_FilmRef = ifft_2d_slices(P1_FilmRef_2Dk); + P2_FilmRef = ifft_2d_slices(P2_FilmRef_2Dk); + P3_FilmRef = ifft_2d_slices(P3_FilmRef_2Dk); + + CalcElasticEnergy + CalcElecEnergy + ThermalNoise; + LandauEnergy + SurfaceDepolEnergy + ExternalEFieldEnergy + + f1_2Dk = f1_landau_2Dk + f1_elec_2Dk + f1_elastic_2Dk + f1_ext_E_2Dk + Thermal_Noise_1_2Dk; + f2_2Dk = f2_landau_2Dk + f2_elec_2Dk + f2_elastic_2Dk + f2_ext_E_2Dk + Thermal_Noise_2_2Dk; + f3_2Dk = f3_landau_2Dk + f3_elec_2Dk + f3_elastic_2Dk + f3_ext_E_2Dk + Thermal_Noise_3_2Dk + f3_surface_depol_2Dk; + + c = c + 1; + + % Progress + error = max( [sum(sum(sum(abs(P1_FilmRef-P1_FilmRef_prev)))); sum(sum(sum(abs(P2_FilmRef-P2_FilmRef_prev)))); sum(sum(sum(abs(P3_FilmRef-P3_FilmRef_prev))))] ); + errors(c) = error; + % print error + if( mod(c, 50) == 0 ) + Visualize + drawnow + error + end + +end + +SaveData","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Pretty.m",".m","334","8","Render3D_CrystalRef +dx = x_axis(2) - x_axis(1); +dy = y_axis(2) - y_axis(1); +dz = z_axis(2) - z_axis(1); + +axis([min(x_axis)*1e9, max(x_axis)*1e9, min(y_axis)*1e9, max(y_axis)*1e9,... + min(z_axis)*1e9, (min(z_axis)+(max(x_axis)-min(x_axis)))*1e9]); +set(gca,'xtick',[]);set(gca,'ytick',[]);set(gca,'ztick',[]);set(gca,'Visible','off')","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/freezeColors.m",".m","9815","276","function freezeColors(varargin) +% freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3) +% +% Problem: There is only one colormap per figure. This function provides +% an easy solution when plots using different colomaps are desired +% in the same figure. +% +% freezeColors freezes the colors of graphics objects in the current axis so +% that subsequent changes to the colormap (or caxis) will not change the +% colors of these objects. freezeColors works on any graphics object +% with CData in indexed-color mode: surfaces, images, scattergroups, +% bargroups, patches, etc. It works by converting CData to true-color rgb +% based on the colormap active at the time freezeColors is called. +% +% The original indexed color data is saved, and can be restored using +% unfreezeColors, making the plot once again subject to the colormap and +% caxis. +% +% +% Usage: +% freezeColors applies to all objects in current axis (gca), +% freezeColors(axh) same, but works on axis axh. +% +% Example: +% subplot(2,1,1); imagesc(X); colormap hot; freezeColors +% subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc... +% +% Note: colorbars must also be frozen. Due to Matlab 'improvements' this can +% no longer be done with freezeColors. Instead, please +% use the function CBFREEZE by Carlos Adrian Vargas Aguilera +% that can be downloaded from the MATLAB File Exchange +% (http://www.mathworks.com/matlabcentral/fileexchange/24371) +% +% h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar) +% +% For additional examples, see test/test_main.m +% +% Side effect on render mode: freezeColors does not work with the painters +% renderer, because Matlab doesn't support rgb color data in +% painters mode. If the current renderer is painters, freezeColors +% changes it to zbuffer. This may have unexpected effects on other aspects +% of your plots. +% +% See also unfreezeColors, freezeColors_pub.html, cbfreeze. +% +% +% John Iversen (iversen@nsi.edu) 3/23/05 +% + +% Changes: +% JRI (iversen@nsi.edu) 4/19/06 Correctly handles scaled integer cdata +% JRI 9/1/06 should now handle all objects with cdata: images, surfaces, +% scatterplots. (v 2.1) +% JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded) +% JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3) +% JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it. +% JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf) +% JRI 4/7/10 Change documentation for colorbars + +% Hidden option for NaN colors: +% Missing data are often represented by NaN in the indexed color +% data, which renders transparently. This transparency will be preserved +% when freezing colors. If instead you wish such gaps to be filled with +% a real color, add 'nancolor',[r g b] to the end of the arguments. E.g. +% freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]), +% where [r g b] is a color vector. This works on images & pcolor, but not on +% surfaces. +% Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes +% attributed in the code. + +% Free for all uses, but please retain the following: +% Original Author: +% John Iversen, 2005-10 +% john_iversen@post.harvard.edu + +appdatacode = 'JRI__freezeColorsData'; + +[h, nancolor] = checkArgs(varargin); + +%gather all children with scaled or indexed CData +cdatah = getCDataHandles(h); + +%current colormap +cmap = colormap; +nColors = size(cmap,1); +cax = caxis; + +% convert object color indexes into colormap to true-color data using +% current colormap +for hh = cdatah', + g = get(hh); + + %preserve parent axis clim + parentAx = getParentAxes(hh); + originalClim = get(parentAx, 'clim'); + + % Note: Special handling of patches: For some reason, setting + % cdata on patches created by bar() yields an error, + % so instead we'll set facevertexcdata instead for patches. + if ~strcmp(g.Type,'patch'), + cdata = g.CData; + else + cdata = g.FaceVertexCData; + end + + %get cdata mapping (most objects (except scattergroup) have it) + if isfield(g,'CDataMapping'), + scalemode = g.CDataMapping; + else + scalemode = 'scaled'; + end + + %save original indexed data for use with unfreezeColors + siz = size(cdata); + setappdata(hh, appdatacode, {cdata scalemode}); + + %convert cdata to indexes into colormap + if strcmp(scalemode,'scaled'), + %4/19/06 JRI, Accommodate scaled display of integer cdata: + % in MATLAB, uint * double = uint, so must coerce cdata to double + % Thanks to O Yamashita for pointing this need out + idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors); + else %direct mapping + idx = cdata; + %10/8/09 in case direct data is non-int (e.g. image;freezeColors) + % (Floor mimics how matlab converts data into colormap index.) + % Thanks to D Armyr for the catch + idx = floor(idx); + end + + %clamp to [1, nColors] + idx(idx<1) = 1; + idx(idx>nColors) = nColors; + + %handle nans in idx + nanmask = isnan(idx); + idx(nanmask)=1; %temporarily replace w/ a valid colormap index + + %make true-color data--using current colormap + realcolor = zeros(siz); + for i = 1:3, + c = cmap(idx,i); + c = reshape(c,siz); + c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified) + realcolor(:,:,i) = c; + end + + %apply new true-color color data + + %true-color is not supported in painters renderer, so switch out of that + if strcmp(get(gcf,'renderer'), 'painters'), + set(gcf,'renderer','zbuffer'); + end + + %replace original CData with true-color data + if ~strcmp(g.Type,'patch'), + set(hh,'CData',realcolor); + else + set(hh,'faceVertexCData',permute(realcolor,[1 3 2])) + end + + %restore clim (so colorbar will show correct limits) + if ~isempty(parentAx), + set(parentAx,'clim',originalClim) + end + +end %loop on indexed-color objects + + +% ============================================================================ % +% Local functions + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% getCDataHandles -- get handles of all descendents with indexed CData +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function hout = getCDataHandles(h) +% getCDataHandles Find all objects with indexed CData + +%recursively descend object tree, finding objects with indexed CData +% An exception: don't include children of objects that themselves have CData: +% for example, scattergroups are non-standard hggroups, with CData. Changing +% such a group's CData automatically changes the CData of its children, +% (as well as the children's handles), so there's no need to act on them. + +error(nargchk(1,1,nargin,'struct')) + +hout = []; +if isempty(h),return;end + +ch = get(h,'children'); +for hh = ch' + g = get(hh); + if isfield(g,'CData'), %does object have CData? + %is it indexed/scaled? + if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1, + hout = [hout; hh]; %#ok %yes, add to list + end + else %no CData, see if object has any interesting children + hout = [hout; getCDataHandles(hh)]; %#ok + end +end + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% getParentAxes -- return handle of axes object to which a given object belongs +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +function hAx = getParentAxes(h) +% getParentAxes Return enclosing axes of a given object (could be self) + +error(nargchk(1,1,nargin,'struct')) +%object itself may be an axis +if strcmp(get(h,'type'),'axes'), + hAx = h; + return +end + +parent = get(h,'parent'); +if (strcmp(get(parent,'type'), 'axes')), + hAx = parent; +else + hAx = getParentAxes(parent); +end + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% checkArgs -- Validate input arguments +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function [h, nancolor] = checkArgs(args) +% checkArgs Validate input arguments to freezeColors + +nargs = length(args); +error(nargchk(0,3,nargs,'struct')) + +%grab handle from first argument if we have an odd number of arguments +if mod(nargs,2), + h = args{1}; + if ~ishandle(h), + error('JRI:freezeColors:checkArgs:invalidHandle',... + 'The first argument must be a valid graphics handle (to an axis)') + end + % 4/2010 check if object to be frozen is a colorbar + if strcmp(get(h,'Tag'),'Colorbar'), + if ~exist('cbfreeze.m'), + warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',... + ['You seem to be attempting to freeze a colorbar. This no longer'... + 'works. Please read the help for freezeColors for the solution.']) + else + cbfreeze(h); + return + end + end + args{1} = []; + nargs = nargs-1; +else + h = gca; +end + +%set nancolor if that option was specified +nancolor = [nan nan nan]; +if nargs == 2, + if strcmpi(args{end-1},'nancolor'), + nancolor = args{end}; + if ~all(size(nancolor)==[1 3]), + error('JRI:freezeColors:checkArgs:badColorArgument',... + 'nancolor must be [r g b] vector'); + end + nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0; + else + error('JRI:freezeColors:checkArgs:unrecognizedOption',... + 'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1}) + end +end + + +","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/CalcEigenstrains.m",".m","2956","19","Eigenstrain_FilmRef_11 = (P1_FilmRef.^2/2 + P2_FilmRef.^2/6 + (2.^(1/2).*P2_FilmRef.*P3_FilmRef)/3 + P3_FilmRef.^2/3).*Q11 + (P1_FilmRef.^2/2 + (5.*P2_FilmRef.^2)/6 - (2.^(1/2).*P2_FilmRef.*P3_FilmRef)/3 + (2.*P3_FilmRef.^2)/3).*Q12 + (P1_FilmRef.^2/2 - P2_FilmRef.^2/6 - (2.^(1/2).*P2_FilmRef.*P3_FilmRef)/3 - P3_FilmRef.^2/3).*Q44; +Eigenstrain_FilmRef_12 = ((P1_FilmRef.*(6.*P2_FilmRef + 6.*2.^(1/2).*P3_FilmRef))/18).*Q11 + (-(P1_FilmRef.*(6.*P2_FilmRef + 6.*2.^(1/2).*P3_FilmRef))/18).*Q12 + ((P1_FilmRef.*(12.*P2_FilmRef - 6.*2.^(1/2).*P3_FilmRef))/18).*Q44; +Eigenstrain_FilmRef_13 = ((P1_FilmRef.*(12.*P3_FilmRef + 6.*2.^(1/2).*P2_FilmRef))/18).*Q11 + (-(P1_FilmRef.*(12.*P3_FilmRef + 6.*2.^(1/2).*P2_FilmRef))/18).*Q12 + ((P1_FilmRef.*(6.*P3_FilmRef - 6.*2.^(1/2).*P2_FilmRef))/18).*Q44; +Eigenstrain_FilmRef_21 = ((P1_FilmRef.*(6.*P2_FilmRef + 6.*2.^(1/2).*P3_FilmRef))/18).*Q11 + (-(P1_FilmRef.*(6.*P2_FilmRef + 6.*2.^(1/2).*P3_FilmRef))/18).*Q12 + ((P1_FilmRef.*(12.*P2_FilmRef - 6.*2.^(1/2).*P3_FilmRef))/18).*Q44; +Eigenstrain_FilmRef_22 = (P1_FilmRef.^2/6 + P2_FilmRef.^2/2 - (2.^(1/2).*P2_FilmRef.*P3_FilmRef)/3 + P3_FilmRef.^2/3).*Q11 + ((5.*P1_FilmRef.^2)/6 + P2_FilmRef.^2/2 + (2.^(1/2).*P2_FilmRef.*P3_FilmRef)/3 + (2.*P3_FilmRef.^2)/3).*Q12 + (P2_FilmRef.^2/2 - P1_FilmRef.^2/6 + (2.^(1/2).*P2_FilmRef.*P3_FilmRef)/3 - P3_FilmRef.^2/3).*Q44; +Eigenstrain_FilmRef_23 = ((2.^(1/2).*P1_FilmRef.^2)/6 - (2.^(1/2).*P2_FilmRef.^2)/6 + (2.*P3_FilmRef.*P2_FilmRef)/3).*Q11 + ((2.^(1/2).*P2_FilmRef.^2)/6 - (2.^(1/2).*P1_FilmRef.^2)/6 - (2.*P3_FilmRef.*P2_FilmRef)/3).*Q12 + ((2.^(1/2).*P2_FilmRef.^2)/6 - (2.^(1/2).*P1_FilmRef.^2)/6 + (P3_FilmRef.*P2_FilmRef)/3).*Q44; +Eigenstrain_FilmRef_31 = ((P1_FilmRef.*(12.*P3_FilmRef + 6.*2.^(1/2).*P2_FilmRef))/18).*Q11 + (-(P1_FilmRef.*(12.*P3_FilmRef + 6.*2.^(1/2).*P2_FilmRef))/18).*Q12 + ((P1_FilmRef.*(6.*P3_FilmRef - 6.*2.^(1/2).*P2_FilmRef))/18).*Q44; +Eigenstrain_FilmRef_32 = ((2.^(1/2).*P1_FilmRef.^2)/6 - (2.^(1/2).*P2_FilmRef.^2)/6 + (2.*P3_FilmRef.*P2_FilmRef)/3).*Q11 + ((2.^(1/2).*P2_FilmRef.^2)/6 - (2.^(1/2).*P1_FilmRef.^2)/6 - (2.*P3_FilmRef.*P2_FilmRef)/3).*Q12 + ((2.^(1/2).*P2_FilmRef.^2)/6 - (2.^(1/2).*P1_FilmRef.^2)/6 + (P3_FilmRef.*P2_FilmRef)/3).*Q44; +Eigenstrain_FilmRef_33 = (P1_FilmRef.^2/3 + P2_FilmRef.^2/3 + P3_FilmRef.^2/3).*Q11 + ((2.*P1_FilmRef.^2)/3 + (2.*P2_FilmRef.^2)/3 + (2.*P3_FilmRef.^2)/3).*Q12 + ((2.*P3_FilmRef.^2)/3 - P2_FilmRef.^2/3 - P1_FilmRef.^2/3).*Q44; + +Eigenstrain_FilmRef_11_k = fftn(Eigenstrain_FilmRef_11); +Eigenstrain_FilmRef_22_k = fftn(Eigenstrain_FilmRef_22); +Eigenstrain_FilmRef_33_k = fftn(Eigenstrain_FilmRef_33); +Eigenstrain_FilmRef_23_k = fftn(Eigenstrain_FilmRef_23); +Eigenstrain_FilmRef_13_k = fftn(Eigenstrain_FilmRef_13); +Eigenstrain_FilmRef_12_k = fftn(Eigenstrain_FilmRef_12); +Eigenstrain_FilmRef_21_k = Eigenstrain_FilmRef_12_k; +Eigenstrain_FilmRef_31_k = Eigenstrain_FilmRef_13_k; +Eigenstrain_FilmRef_32_k = Eigenstrain_FilmRef_23_k;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/LandauEnergy.m",".m","27980","12","%% Landau Free Energy +f1_landau = 2.*P1_FilmRef.*a1 + a1112.*((32.*P1_FilmRef.*P2_FilmRef.^6)/27 + (40.*P1_FilmRef.*P3_FilmRef.^6)/27 + P1_FilmRef.^7 + (25.*P1_FilmRef.^3.*P2_FilmRef.^4)/9 + 2.*P1_FilmRef.^5.*P2_FilmRef.^2 + (10.*P1_FilmRef.^3.*P3_FilmRef.^4)/9 + (5.*P1_FilmRef.^5.*P3_FilmRef.^2)/2 + 10.*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^4 + (25.*P1_FilmRef.*P2_FilmRef.^4.*P3_FilmRef.^2)/2 + (5.*P1_FilmRef.^3.*P2_FilmRef.^2.*P3_FilmRef.^2)/3 - (8.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^5)/3 - (7.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.^5.*P3_FilmRef)/3 - 2.^(1/2).*P1_FilmRef.^5.*P2_FilmRef.*P3_FilmRef - (260.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef.^3)/27 - (20.*2.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef.^3)/3 - (10.*2.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.^3.*P3_FilmRef)/3 + (28.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^5)/27 + (22.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^5.*P3_FilmRef)/27 + (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^5.*P2_FilmRef.*P3_FilmRef)/3 + (190.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef.^3)/81 - (10.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef.^3)/27 + (40.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.^3.*P3_FilmRef)/27 - (40.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^4)/27 - (20.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^4.*P3_FilmRef.^2)/27 - (20.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.^2.*P3_FilmRef.^2)/9) + a112.*((13.*P1_FilmRef.*P2_FilmRef.^4)/6 + (4.*P1_FilmRef.*P3_FilmRef.^4)/3 + (3.*P1_FilmRef.^5)/2 + P1_FilmRef.^3.*P2_FilmRef.^2 + (16.*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^2)/3 - (32.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^3)/9 - (28.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef)/9 - (4.*2.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef)/3 + (8.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^3)/27 + (22.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef)/27 - (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef)/9 - (8.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^2)/9) + a1122.*((47.*P1_FilmRef.*P2_FilmRef.^6)/54 + (8.*P1_FilmRef.*P3_FilmRef.^6)/27 + P1_FilmRef.^7/2 + (19.*P1_FilmRef.^3.*P2_FilmRef.^4)/18 - (P1_FilmRef.^5.*P2_FilmRef.^2)/2 + (8.*P1_FilmRef.^3.*P3_FilmRef.^4)/9 - P1_FilmRef.^5.*P3_FilmRef.^2 + (40.*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^4)/9 + (35.*P1_FilmRef.*P2_FilmRef.^4.*P3_FilmRef.^2)/9 + (14.*P1_FilmRef.^3.*P2_FilmRef.^2.*P3_FilmRef.^2)/3 - (16.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^5)/9 - (16.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.^5.*P3_FilmRef)/9 - (40.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef.^3)/9 - (8.*2.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef.^3)/9 - (16.*2.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.^3.*P3_FilmRef)/9 + (5.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^5.*P3_FilmRef)/9 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^5.*P2_FilmRef.*P3_FilmRef)/3 + (124.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef.^3)/81 + (4.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef.^3)/9 + (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.^3.*P3_FilmRef)/9 - (16.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^4)/27 - (32.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^4.*P3_FilmRef.^2)/27) - a1123.*((5.*P1_FilmRef.*P2_FilmRef.^6)/27 + (4.*P1_FilmRef.*P3_FilmRef.^6)/27 - (2.*P1_FilmRef.^3.*P2_FilmRef.^4)/9 - P1_FilmRef.^5.*P2_FilmRef.^2 + (P1_FilmRef.^3.*P3_FilmRef.^4)/9 - (P1_FilmRef.^5.*P3_FilmRef.^2)/2 + (35.*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^4)/27 + (65.*P1_FilmRef.*P2_FilmRef.^4.*P3_FilmRef.^2)/54 - (7.*P1_FilmRef.^3.*P2_FilmRef.^2.*P3_FilmRef.^2)/9 - (4.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^5)/9 - (2.^(1/2).*P1_FilmRef.*P2_FilmRef.^5.*P3_FilmRef)/3 + 2.^(1/2).*P1_FilmRef.^5.*P2_FilmRef.*P3_FilmRef - (32.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef.^3)/27 + (2.*2.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.^3.*P3_FilmRef)/3 + (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^5)/27 + (4.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^5.*P3_FilmRef)/27 + (34.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef.^3)/81 + (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef.^3)/27 + (4.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.^3.*P3_FilmRef)/27 - (16.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^4)/81 - (20.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^4.*P3_FilmRef.^2)/81 - (4.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.^2.*P3_FilmRef.^2)/27) - a123.*((2.*P1_FilmRef.*P2_FilmRef.^4)/9 + (2.*P1_FilmRef.*P3_FilmRef.^4)/9 - (2.*P1_FilmRef.^3.*P2_FilmRef.^2)/3 - (P1_FilmRef.^3.*P3_FilmRef.^2)/3 + (5.*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^2)/9 - (4.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^3)/9 - (2.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef)/9 + (2.*2.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef)/3 + (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^3)/27 + (4.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef)/27 - (4.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^2)/27) + a111.*((3.*P1_FilmRef.^5)/2 + 5.*P1_FilmRef.^3.*P2_FilmRef.^2 + (10.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef)/3 + 10.*P1_FilmRef.^3.*P3_FilmRef.^2 + (5.*P1_FilmRef.*P2_FilmRef.^4)/6 + (10.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef)/9 + 10.*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^2 + (20.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^3)/9 + (10.*P1_FilmRef.*P3_FilmRef.^4)/3) + a1111.*(P1_FilmRef.^7 + 7.*P1_FilmRef.^5.*P2_FilmRef.^2 + (14.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^5.*P2_FilmRef.*P3_FilmRef)/3 + 14.*P1_FilmRef.^5.*P3_FilmRef.^2 + (35.*P1_FilmRef.^3.*P2_FilmRef.^4)/9 + (140.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.^3.*P3_FilmRef)/27 + (140.*P1_FilmRef.^3.*P2_FilmRef.^2.*P3_FilmRef.^2)/3 + (280.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^3.*P2_FilmRef.*P3_FilmRef.^3)/27 + (140.*P1_FilmRef.^3.*P3_FilmRef.^4)/9 + (7.*P1_FilmRef.*P2_FilmRef.^6)/27 + (14.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^5.*P3_FilmRef)/27 + (70.*P1_FilmRef.*P2_FilmRef.^4.*P3_FilmRef.^2)/9 + (280.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.^3.*P3_FilmRef.^3)/81 + (140.*P1_FilmRef.*P2_FilmRef.^2.*P3_FilmRef.^4)/9 + (56.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef.^5)/27 + (56.*P1_FilmRef.*P3_FilmRef.^6)/27) + a12.*(P1_FilmRef.*P2_FilmRef.^2 + P1_FilmRef.^3 - (4.*2.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef)/3 - (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef)/9) + a11.*(2.*P1_FilmRef.^3 + 2.*P1_FilmRef.*P2_FilmRef.^2 + (4.*3.^(1/2).*6.^(1/2).*P1_FilmRef.*P2_FilmRef.*P3_FilmRef)/3 + 4.*P1_FilmRef.*P3_FilmRef.^2); +f2_landau = a1123.*((P1_FilmRef.^6.*P2_FilmRef)/3 + (68.*P2_FilmRef.*P3_FilmRef.^6)/81 - (8.*2.^(1/2).*P3_FilmRef.^7)/81 + (4.*P2_FilmRef.^7)/27 - (5.*P1_FilmRef.^2.*P2_FilmRef.^5)/9 + (2.*P1_FilmRef.^4.*P2_FilmRef.^3)/9 + (311.*P2_FilmRef.^3.*P3_FilmRef.^4)/81 + (121.*P2_FilmRef.^5.*P3_FilmRef.^2)/54 - (35.*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/27 + (7.*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/18 + (2.*2.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^5)/9 - (50.*2.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/27 - (200.*2.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/81 - (65.*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/27 - (2.^(1/2).*P1_FilmRef.^6.*P3_FilmRef)/6 - (35.*2.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/162 + (8.*3.^(1/2).*6.^(1/2).*P3_FilmRef.^7)/243 + (49.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/243 + (5.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/6 - (2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/2 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^5)/27 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P3_FilmRef.^3)/54 + (47.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/81 + (415.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/486 + (16.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/9 - (17.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/27 - (40.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/243 - (10.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/27 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/9 - (160.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/243 - (22.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/81 + (16.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/81 + (2.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/27 + (40.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/81) + a11.*(2.*P1_FilmRef.^2.*P2_FilmRef + 4.*P2_FilmRef.*P3_FilmRef.^2 - (4.*2.^(1/2).*P3_FilmRef.^3)/9 + 2.*P2_FilmRef.^3 - (8.*2.^(1/2).*P2_FilmRef.^2.*P3_FilmRef)/3 + (4.*3.^(1/2).*6.^(1/2).*P3_FilmRef.^3)/27 + (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P3_FilmRef)/3 + (2.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef)/9) + a123.*((P1_FilmRef.^4.*P2_FilmRef)/3 + (10.*P2_FilmRef.*P3_FilmRef.^4)/27 - (2.*2.^(1/2).*P3_FilmRef.^5)/27 + P2_FilmRef.^5/9 - (4.*P1_FilmRef.^2.*P2_FilmRef.^3)/9 + (25.*P2_FilmRef.^3.*P3_FilmRef.^2)/27 - (5.*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2)/9 + (2.*2.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^3)/9 - (2.*2.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^3)/3 - (2.^(1/2).*P1_FilmRef.^4.*P3_FilmRef)/6 - (5.*2.^(1/2).*P2_FilmRef.^4.*P3_FilmRef)/54 + (2.*3.^(1/2).*6.^(1/2).*P3_FilmRef.^5)/81 + (10.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef)/81 + (2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef)/3 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^3)/27 + (5.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^3)/27 - (8.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^4)/81 - (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef)/9 - (8.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^2)/81 + (4.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2)/27) + a1.*(2.*P2_FilmRef - (2.*2.^(1/2).*P3_FilmRef)/3 + (2.*3.^(1/2).*6.^(1/2).*P3_FilmRef)/9) + a1112.*((2.*P1_FilmRef.^6.*P2_FilmRef)/3 + (8.*P2_FilmRef.*P3_FilmRef.^6)/3 - (16.*2.^(1/2).*P3_FilmRef.^7)/81 + (23.*P2_FilmRef.^7)/27 + (32.*P1_FilmRef.^2.*P2_FilmRef.^5)/9 + (25.*P1_FilmRef.^4.*P2_FilmRef.^3)/9 + (890.*P2_FilmRef.^3.*P3_FilmRef.^4)/81 + (131.*P2_FilmRef.^5.*P3_FilmRef.^2)/18 + 10.*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4 + (5.*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/6 - (4.*2.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^5)/3 - (5.*2.^(1/2).*P1_FilmRef.^4.*P3_FilmRef.^3)/3 - (116.*2.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/27 - (515.*2.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/81 + 25.*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2 - (2.^(1/2).*P1_FilmRef.^6.*P3_FilmRef)/6 - (343.*2.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/162 + (16.*3.^(1/2).*6.^(1/2).*P3_FilmRef.^7)/243 + (3.^(1/2).*6.^(1/2).*P1_FilmRef.^6.*P3_FilmRef)/9 + (140.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/243 - (35.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/6 - (5.*2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/2 + (14.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^5)/27 - (5.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P3_FilmRef.^3)/54 + (110.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/81 + (1555.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/486 - (130.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/9 + (95.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/27 - (16.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/81 + (55.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/27 + (10.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/9 - (400.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/243 - (34.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/27 - (40.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/27 - (10.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/9 - (40.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/27) + a112.*((P1_FilmRef.^4.*P2_FilmRef)/2 + (100.*P2_FilmRef.*P3_FilmRef.^4)/27 - (4.*2.^(1/2).*P3_FilmRef.^5)/9 + (7.*P2_FilmRef.^5)/6 + (13.*P1_FilmRef.^2.*P2_FilmRef.^3)/3 + (160.*P2_FilmRef.^3.*P3_FilmRef.^2)/27 + (16.*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2)/3 - (16.*2.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^3)/9 - (32.*2.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^3)/9 - (2.^(1/2).*P1_FilmRef.^4.*P3_FilmRef)/3 - (5.*2.^(1/2).*P2_FilmRef.^4.*P3_FilmRef)/3 + (4.*3.^(1/2).*6.^(1/2).*P3_FilmRef.^5)/27 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P3_FilmRef)/18 + (5.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef)/6 - (14.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef)/3 + (4.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^3)/27 + (44.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^3)/27 - (32.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^4)/81 + (11.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef)/9 - (80.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^2)/81 - (8.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2)/9) + a111.*((5.*P1_FilmRef.^4.*P2_FilmRef)/2 + (10.*P2_FilmRef.*P3_FilmRef.^4)/3 - (2.*2.^(1/2).*P3_FilmRef.^5)/9 + (11.*P2_FilmRef.^5)/6 + (5.*P1_FilmRef.^2.*P2_FilmRef.^3)/3 + 10.*P2_FilmRef.^3.*P3_FilmRef.^2 + 10.*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2 - (40.*2.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^3)/9 - (40.*2.^(1/2).*P2_FilmRef.^4.*P3_FilmRef)/9 + (2.*3.^(1/2).*6.^(1/2).*P3_FilmRef.^5)/27 + (5.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P3_FilmRef)/6 + (5.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef)/54 + (10.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^3)/9 + (10.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^3)/27 + (5.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef)/3) + a1111.*((7.*P1_FilmRef.^6.*P2_FilmRef)/3 + (56.*P2_FilmRef.*P3_FilmRef.^6)/27 - (8.*2.^(1/2).*P3_FilmRef.^7)/81 + (43.*P2_FilmRef.^7)/27 + (7.*P1_FilmRef.^2.*P2_FilmRef.^5)/9 + (35.*P1_FilmRef.^4.*P2_FilmRef.^3)/9 + (140.*P2_FilmRef.^3.*P3_FilmRef.^4)/9 + (154.*P2_FilmRef.^5.*P3_FilmRef.^2)/9 + (140.*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/9 + (70.*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/3 - (112.*2.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/27 - (1120.*2.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/81 + (140.*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/9 - (448.*2.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/81 + (8.*3.^(1/2).*6.^(1/2).*P3_FilmRef.^7)/243 + (7.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^6.*P3_FilmRef)/9 + (7.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/243 + (28.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^5)/27 + (70.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P3_FilmRef.^3)/27 + (28.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/81 + (70.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/243 + (140.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/27 + (35.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/27 + (35.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/9) + a1122.*((88.*P2_FilmRef.*P3_FilmRef.^6)/81 - (P1_FilmRef.^6.*P2_FilmRef)/6 - (8.*2.^(1/2).*P3_FilmRef.^7)/81 + (11.*P2_FilmRef.^7)/54 + (47.*P1_FilmRef.^2.*P2_FilmRef.^5)/18 + (19.*P1_FilmRef.^4.*P2_FilmRef.^3)/18 + (392.*P2_FilmRef.^3.*P3_FilmRef.^4)/81 + (67.*P2_FilmRef.^5.*P3_FilmRef.^2)/27 + (40.*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/9 + (7.*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/3 - (8.*2.^(1/2).*P1_FilmRef.^2.*P3_FilmRef.^5)/9 - (2.*2.^(1/2).*P1_FilmRef.^4.*P3_FilmRef.^3)/9 - (40.*2.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/27 - (250.*2.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/81 + (70.*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/9 - (28.*2.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/81 + (8.*3.^(1/2).*6.^(1/2).*P3_FilmRef.^7)/243 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^6.*P3_FilmRef)/18 + (119.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/486 - (40.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/9 - (4.*2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/3 + (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P3_FilmRef.^3)/9 + (64.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/81 + (235.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/243 - (20.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/3 + (62.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/27 - (32.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/243 + (25.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/18 + (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/6 - (160.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/243 - (32.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/81 - (16.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/27 - (64.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/27) + a12.*(P1_FilmRef.^2.*P2_FilmRef + (16.*P2_FilmRef.*P3_FilmRef.^2)/9 - (4.*2.^(1/2).*P3_FilmRef.^3)/9 + P2_FilmRef.^3 - (2.*2.^(1/2).*P1_FilmRef.^2.*P3_FilmRef)/3 - (2.*2.^(1/2).*P2_FilmRef.^2.*P3_FilmRef)/3 + (4.*3.^(1/2).*6.^(1/2).*P3_FilmRef.^3)/27 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P3_FilmRef)/9 + (5.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef)/9 - (8.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^2)/27); +f3_landau = a112.*((80.*P2_FilmRef.^4.*P3_FilmRef)/27 - (2.^(1/2).*P2_FilmRef.^5)/3 + (4.*P3_FilmRef.^5)/3 + (8.*P1_FilmRef.^2.*P3_FilmRef.^3)/3 + (200.*P2_FilmRef.^2.*P3_FilmRef.^3)/27 + (16.*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef)/3 - (14.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3)/9 - (32.*2.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^2)/9 - (2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef)/3 - (20.*2.^(1/2).*P2_FilmRef.*P3_FilmRef.^4)/9 + (3.^(1/2).*6.^(1/2).*P2_FilmRef.^5)/6 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef)/18 + (20.*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^4)/27 - (16.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2)/3 + (11.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3)/27 + (44.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^2)/27 - (40.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef)/81 + (4.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2)/9 - (64.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^3)/81 - (8.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef)/9) + a11.*(4.*P1_FilmRef.^2.*P3_FilmRef + 4.*P2_FilmRef.^2.*P3_FilmRef - (8.*2.^(1/2).*P2_FilmRef.^3)/9 + (4.*P3_FilmRef.^3)/3 - (4.*2.^(1/2).*P2_FilmRef.*P3_FilmRef.^2)/3 + (2.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3)/27 + (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef)/3 + (4.*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^2)/9) + a123.*((P1_FilmRef.^4.*P3_FilmRef)/6 + (25.*P2_FilmRef.^4.*P3_FilmRef)/54 - (2.^(1/2).*P2_FilmRef.^5)/54 + (2.*P3_FilmRef.^5)/9 - (4.*P1_FilmRef.^2.*P3_FilmRef.^3)/9 + (20.*P2_FilmRef.^2.*P3_FilmRef.^3)/27 - (5.*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef)/9 + (2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3)/9 - (2.*2.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^2)/3 - (2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef)/6 - (10.*2.^(1/2).*P2_FilmRef.*P3_FilmRef.^4)/27 + (2.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^5)/81 + (10.*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^4)/81 + (2.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2)/3 - (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3)/27 + (5.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^2)/27 - (4.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef)/81 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2)/9 - (16.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^3)/81 + (4.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef)/27) + a1.*(2.*P3_FilmRef - (2.*2.^(1/2).*P2_FilmRef)/3 + (2.*3.^(1/2).*6.^(1/2).*P2_FilmRef)/9) + a1112.*((5.*P1_FilmRef.^6.*P3_FilmRef)/6 + (131.*P2_FilmRef.^6.*P3_FilmRef)/54 - (49.*2.^(1/2).*P2_FilmRef.^7)/162 + (16.*P3_FilmRef.^7)/27 + (40.*P1_FilmRef.^2.*P3_FilmRef.^5)/9 + (10.*P1_FilmRef.^4.*P3_FilmRef.^3)/9 + 8.*P2_FilmRef.^2.*P3_FilmRef.^5 + (890.*P2_FilmRef.^4.*P3_FilmRef.^3)/81 + (25.*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/2 + (5.*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/6 - (7.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^5)/6 - (5.*2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^3)/6 - (580.*2.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/81 - (103.*2.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/27 + 20.*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3 - (2.^(1/2).*P1_FilmRef.^6.*P2_FilmRef)/6 - (112.*2.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/81 + (20.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^7)/243 + (3.^(1/2).*6.^(1/2).*P1_FilmRef.^6.*P2_FilmRef)/9 + (112.*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/243 - (20.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/3 - 5.*2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2 + (11.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^5)/27 + (10.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^3)/27 + (550.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/243 + (311.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/162 - (130.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/9 + (95.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/27 - (34.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/81 + (70.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/27 - (5.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/18 - (16.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/27 - (400.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/243 - (20.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/27 - (10.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/9 - (80.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/27) + a111.*(5.*P1_FilmRef.^4.*P3_FilmRef + 5.*P2_FilmRef.^4.*P3_FilmRef - (8.*2.^(1/2).*P2_FilmRef.^5)/9 + (2.*P3_FilmRef.^5)/3 + (20.*P1_FilmRef.^2.*P3_FilmRef.^3)/3 + (20.*P2_FilmRef.^2.*P3_FilmRef.^3)/3 + 10.*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef - (40.*2.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^2)/9 - (10.*2.^(1/2).*P2_FilmRef.*P3_FilmRef.^4)/9 + (3.^(1/2).*6.^(1/2).*P2_FilmRef.^5)/54 + (5.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef)/6 + (10.*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^4)/27 + (5.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3)/9 + (10.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^2)/27 + (10.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^2)/3) + a1111.*((14.*P1_FilmRef.^6.*P3_FilmRef)/3 + (154.*P2_FilmRef.^6.*P3_FilmRef)/27 - (64.*2.^(1/2).*P2_FilmRef.^7)/81 + (8.*P3_FilmRef.^7)/27 + (56.*P1_FilmRef.^2.*P3_FilmRef.^5)/9 + (140.*P1_FilmRef.^4.*P3_FilmRef.^3)/9 + (56.*P2_FilmRef.^2.*P3_FilmRef.^5)/9 + (140.*P2_FilmRef.^4.*P3_FilmRef.^3)/9 + (70.*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/9 + (70.*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/3 - (560.*2.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/81 - (224.*2.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/27 + (280.*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/9 - (56.*2.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/81 + (3.^(1/2).*6.^(1/2).*P2_FilmRef.^7)/243 + (7.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^6.*P2_FilmRef)/9 + (56.*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/243 + (7.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^5)/27 + (35.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^3)/27 + (140.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/243 + (14.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/81 + (140.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/27 + (140.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/27 + (70.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/9) + a1122.*((67.*P2_FilmRef.^6.*P3_FilmRef)/81 - (P1_FilmRef.^6.*P3_FilmRef)/3 - (4.*2.^(1/2).*P2_FilmRef.^7)/81 + (8.*P3_FilmRef.^7)/27 + (8.*P1_FilmRef.^2.*P3_FilmRef.^5)/9 + (8.*P1_FilmRef.^4.*P3_FilmRef.^3)/9 + (88.*P2_FilmRef.^2.*P3_FilmRef.^5)/27 + (392.*P2_FilmRef.^4.*P3_FilmRef.^3)/81 + (35.*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/9 + (7.*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/3 - (8.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^5)/9 - (4.*2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^3)/9 - (200.*2.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/81 - (50.*2.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/27 + (80.*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/9 - (56.*2.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/81 + (17.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^7)/486 - (3.^(1/2).*6.^(1/2).*P1_FilmRef.^6.*P2_FilmRef)/18 + (56.*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/243 - (40.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/9 - (2.*2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/3 + (5.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^5)/18 + (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^3)/18 + (320.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/243 + (47.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/81 - (20.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/3 + (62.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/27 - (32.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/243 + (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/3 - (32.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/81 - (160.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/243 - (32.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/27 - (32.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/27) - a1123.*((5.*2.^(1/2).*P2_FilmRef.^7)/162 - (121.*P2_FilmRef.^6.*P3_FilmRef)/162 - (P1_FilmRef.^6.*P3_FilmRef)/6 - (8.*P3_FilmRef.^7)/27 + (4.*P1_FilmRef.^2.*P3_FilmRef.^5)/9 + (P1_FilmRef.^4.*P3_FilmRef.^3)/9 - (68.*P2_FilmRef.^2.*P3_FilmRef.^5)/27 - (311.*P2_FilmRef.^4.*P3_FilmRef.^3)/81 + (65.*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/54 - (7.*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/18 - (2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^5)/6 + (2.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^3)/6 + (250.*2.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/81 + (40.*2.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/27 + (70.*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/27 + (2.^(1/2).*P1_FilmRef.^6.*P2_FilmRef)/6 + (56.*2.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/81 - (7.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^7)/243 - (56.*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^6)/243 - (10.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/9 + (2.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^5)/27 + (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^3)/27 - (235.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3.*P3_FilmRef.^4)/243 - (83.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^5.*P3_FilmRef.^2)/162 - (16.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/9 + (17.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^3.*P3_FilmRef.^2)/27 + (22.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^6.*P3_FilmRef)/243 + (5.*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.*P3_FilmRef.^4)/27 + (3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.*P3_FilmRef.^2)/18 + (40.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef.^5)/81 + (160.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^4.*P3_FilmRef.^3)/243 - (20.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^4.*P3_FilmRef)/81 - (2.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^4.*P2_FilmRef.^2.*P3_FilmRef)/27 - (32.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef.^2.*P3_FilmRef.^3)/81) - a12.*((2.*2.^(1/2).*P2_FilmRef.^3)/9 - (16.*P2_FilmRef.^2.*P3_FilmRef)/9 - (4.*P3_FilmRef.^3)/3 + (2.*2.^(1/2).*P1_FilmRef.^2.*P2_FilmRef)/3 + (4.*2.^(1/2).*P2_FilmRef.*P3_FilmRef.^2)/3 - (5.*3.^(1/2).*6.^(1/2).*P2_FilmRef.^3)/27 + (3.^(1/2).*6.^(1/2).*P1_FilmRef.^2.*P2_FilmRef)/9 - (4.*3.^(1/2).*6.^(1/2).*P2_FilmRef.*P3_FilmRef.^2)/9 + (8.*2.^(1/2).*3.^(1/2).*6.^(1/2).*P2_FilmRef.^2.*P3_FilmRef)/27); + +f1_landau = f1_landau .* in_film .* Nucleation_Sites; +f2_landau = f2_landau .* in_film .* Nucleation_Sites; +f3_landau = f3_landau .* in_film .* Nucleation_Sites; + +f1_landau_2Dk = fft_2d_slices(f1_landau); +f2_landau_2Dk = fft_2d_slices(f2_landau); +f3_landau_2Dk = fft_2d_slices(f3_landau);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/CalculateStrain.m",".m","1783","58","if(HET_ELASTIC_RELAX) + EigenstrainInFilm; + InfinitePlate; +else % Don't do heterogenous strain relaxation + u_1_A = 0; + u_2_A = 0; + u_3_A = 0; + + u_1_B = 0; + u_2_B = 0; + u_3_B = 0; + + e_11_A = 0; + e_22_A = 0; + e_33_A = 0; + e_12_A = 0; + e_13_A = 0; + e_23_A = 0; + + e_11_B = 0; + e_22_B = 0; + e_33_B = 0; + e_12_B = 0; + e_13_B = 0; + e_23_B = 0; +end + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% +%% +% A + B = het strains +% A + B + homo = total strain +%% +%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% e_FilmRef_het_11 = e_11_A + e_11_B; +% e_FilmRef_het_22 = e_22_A + e_22_B; +% e_FilmRef_het_33 = e_33_A + e_33_B; +% e_FilmRef_het_12 = e_12_A + e_12_B; +% e_FilmRef_het_13 = e_13_A + e_13_B; +% e_FilmRef_het_23 = e_23_A + e_23_B; +% e_FilmRef_het_21 = e_12_FilmRef_het; +% e_FilmRef_het_31 = e_13_FilmRef_het; +% e_FilmRef_het_32 = e_23_FilmRef_het; + +u_FilmRef_1 = u_1_A + u_1_B; +u_FilmRef_2 = u_2_A + u_2_B; +u_FilmRef_3 = u_3_A + u_3_B; + +TotalStrain_FilmRef_11 = e_11_A + e_11_B + TotalStrain_FilmRef_homo_11(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_12 = e_12_A + e_12_B + TotalStrain_FilmRef_homo_12(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_13 = e_13_A + e_13_B + TotalStrain_FilmRef_homo_13(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_22 = e_22_A + e_22_B + TotalStrain_FilmRef_homo_22(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_23 = e_23_A + e_23_B + TotalStrain_FilmRef_homo_23(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_33 = e_33_A + e_33_B + TotalStrain_FilmRef_homo_33(P1_FilmRef,P2_FilmRef,P3_FilmRef); +TotalStrain_FilmRef_32 = TotalStrain_FilmRef_23; +TotalStrain_FilmRef_21 = TotalStrain_FilmRef_12; +TotalStrain_FilmRef_31 = TotalStrain_FilmRef_13;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Hysteresis.m",".m","2771","115","%% Nucleation sites, have 0 free energy change... +Setup +% Nucleation_Sites = +(rand(Nx,Ny,Nz) < (1-0.01)) .* in_film; +L = 5; +Nucleation_Sites = ones(Nx,Ny,Nz); +xy_edges = 8; +z_edges = 2; +for i = 1 : 7 + Nucleation_Sites(randi([xy_edges,Nx-L+1-xy_edges])+(0:L-1),randi([xy_edges,Ny-L+1-xy_edges])+(0:L-1),randi([z_edges,Nz-L+1-z_edges])+(0:L-1)) = 0; +end + +% Percent of nucleation sites +Nucleation_pct = abs(sum(sum(sum(Nucleation_Sites-1)))/(Nx*Ny*(film_index-interface_index+1))); + +%% Hysteresis Loops + +% Run 0 kV/cm + +% +Load = 1; +E_fields_tot = [0, 1e2, 1e3, 1e4, 1e5, 5e5, 1e6, 2e6, 3e6, 4e6, 5e6, 6e6, 7e6, 8e6, 9e6, 1e7]; +E_vectors = []; +P_vectors = []; + +%% +E_fields = E_fields_tot(2:end); + +for E_1_applied_FilmRef = E_fields + + folder = sprintf('%gkV-cm',E_1_applied_FilmRef/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied_FilmRef]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied_FilmRef/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +%% +E_fields = E_fields_tot(1:end-1); +E_fields = fliplr(E_fields); + +for E_1_applied_FilmRef = E_fields + + folder = sprintf('%g_2kV-cm',E_1_applied_FilmRef/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied_FilmRef]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied_FilmRef/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +%% +E_fields = -E_fields_tot(2:end); + +for E_1_applied_FilmRef = E_fields + + folder = sprintf('%gkV-cm',E_1_applied_FilmRef/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied_FilmRef]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied_FilmRef/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +%% +E_fields = -E_fields_tot(1:end-1); +E_fields = fliplr(E_fields); + +for E_1_applied_FilmRef = E_fields + + folder = sprintf('%g_2kV-cm',E_1_applied_FilmRef/1e5); + mkdir(folder); + cd(folder); + movefile('../init.mat','./init.mat'); + + addpath('../') + Main + + P_vectors = [P_vectors, mean(mean(mean(P1)))]; + E_vectors = [E_vectors, E_1_applied_FilmRef]; + + final = sprintf('./final_%g_%gC_%gkV-cm.mat',Us*1e2,T,E_1_applied_FilmRef/1e5); + copyfile(final,'../init.mat','f'); + cd('../'); + +end + +save('PE','P_vectors','E_vectors');","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Nucleate.m",".m","566","16","%% Nucleation sites, have 0 free energy change... +% Nucleation_Sites = +(rand(Nx,Ny,Nz) < (1-0.01)) .* in_film; +if( NUCLEATE ) + L = 5; + Nucleation_Sites = ones(Nx,Ny,Nz); + xy_edges = 8; + z_edges = 2; + for i_ind = 1 : 7 + Nucleation_Sites(randi([xy_edges,Nx-L+1-xy_edges])+(0:L-1),randi([xy_edges,Ny-L+1-xy_edges])+(0:L-1),randi([z_edges,Nz-L+1-z_edges])+(0:L-1)) = 0; + end + + % Percent of nucleation sites + Nucleation_pct = abs(sum(sum(sum(Nucleation_Sites-1)))/(Nx*Ny*(film_index-interface_index+1))); +else + Nucleation_Sites = 1; +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/InfinitePlateSetup_vpa.m",".m","3887","93","U = zeros(3,3); +m = [0, 0, 1]; +for i_ind = 1 : 3 +for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + U(i_ind,k_ind) = U(i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * m(j_ind) * m(l_ind); + end + end +end +end + +R = zeros(Nx,Ny,3,3); W = zeros(numel(kx),numel(ky),3,3); +eigenvec_mat = zeros(Nx,Ny,6,6); % the eigenvalues and eigenvectors found at each k vector pt +eigenval_mat = zeros(Nx,Ny,6); % the eigenvalues and eigenvectors found at each k vector pt +mat_mat = zeros(numel(kx),numel(ky),6,6); + +for k1_ind = 1 : numel(kx) +for k2_ind = 1 : numel(ky) + + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Origin, different solution, be mindful of dividing by k vector as well! + + n = [ kx_grid_2D(k1_ind,k2_ind), ky_grid_2D(k1_ind,k2_ind), 0 ] ./ sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ) ; + + for i_ind = 1 : 3 + for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + R(k1_ind,k2_ind,i_ind,k_ind) = R(k1_ind,k2_ind,i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * m(l_ind); + W(k1_ind,k2_ind,i_ind,k_ind) = W(k1_ind,k2_ind,i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * n(l_ind); + end + end + end + end + + R_mat = squeeze(R(k1_ind,k2_ind,:,:)); + W_mat = squeeze(W(k1_ind,k2_ind,:,:)); + + + N1 = -inv(U)*R_mat'; N2 = inv(U); N3 = R_mat*inv(U)*R_mat'-W_mat; + mat = [N1, N2; N3, N1']; + vpa_mat = vpa(mat); + + [eigenvec, eigenval] = eig(vpa_mat); + eigenvec = double(eigenvec); + eigenval = diag(double(eigenval)); + + mat_mat(k1_ind,k2_ind,:,:) = mat; + eigenvec_mat(k1_ind,k2_ind,:,:) = eigenvec; + eigenval_mat(k1_ind,k2_ind,:) = eigenval; + + end +end +end + +%% BC matrix solutions +bc_mats = zeros(Nx,Ny,6,6); +strain_bc_mats_inv = zeros(Nx,Ny,6,6); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Because we divide by K^2 to make matrices better + K = sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ); + bc_mat = zeros(6,6); + % [ d1 * eigenvec(1,1) + d2 * eigenvec(1,2) + + % d1 * eigenvec(2,1) + d2 * eigenvec(2,2) + + % d1 * eigenvec(3,1) + d2 * eigenvec(3,2) + + % d1 * eigenvec(4,1) + d2 * eigenvec(4,2) + + for m = 1 : 6 % the eigenvalue -> column of eigenvec_mat ~ eigenvector + for k_ind = 1 : 3 % eigenvector a, scale by K + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_sub*1i*K); + end + % rescale by K^-1 to avoid conditioning errors... need to rescale + % the given value as well! + for k_ind = 4 : 6 % eigenvector b + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_film*1i*K) * 1i * K / K^2; + end + end + bc_mats(k1_ind,k2_ind,:,:) = bc_mat; + + vpa_mat = vpa(bc_mat); + strain_bc_mats_inv(k1_ind,k2_ind,:,:) = double(inv(vpa_mat)); + end +end +end + +strain_bc_mat_inv_korigin = inv( vpa([ h_sub 1 0 0 0 0 ; ... + 0 0 h_sub 1 0 0 ; ... + 0 0 0 0 h_sub 1 ; ... + C_FilmRef(1,3,1,3) 0 C_FilmRef(1,3,2,3) 0 C_FilmRef(1,3,3,3) 0 ; ... + C_FilmRef(2,3,1,3) 0 C_FilmRef(2,3,2,3) 0 C_FilmRef(2,3,3,3) 0 ; ... + C_FilmRef(3,3,1,3) 0 C_FilmRef(3,3,2,3) 0 C_FilmRef(3,3,3,3) 0 ]) ); +strain_bc_mat_inv_korigin = double(strain_bc_mat_inv_korigin);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/FundamentalConstants.m",".m","34","1","permittivity_0 = 8.85418782*1e-12;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/InfinitePlateSetup.m",".m","3695","88","U = zeros(3,3); +m = [0, 0, 1]; +for i_ind = 1 : 3 +for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + U(i_ind,k_ind) = U(i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * m(j_ind) * m(l_ind); + end + end +end +end + +R = zeros(Nx,Ny,3,3); W = zeros(numel(kx),numel(ky),3,3); +eigenvec_mat = zeros(Nx,Ny,6,6); % the eigenvalues and eigenvectors found at each k vector pt +eigenval_mat = zeros(Nx,Ny,6); % the eigenvalues and eigenvectors found at each k vector pt +mat_mat = zeros(numel(kx),numel(ky),6,6); + +for k1_ind = 1 : numel(kx) +for k2_ind = 1 : numel(ky) + + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Origin, different solution, be mindful of dividing by k vector as well! + + n = [ kx_grid_2D(k1_ind,k2_ind), ky_grid_2D(k1_ind,k2_ind), 0 ] ./ sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ) ; + + for i_ind = 1 : 3 + for k_ind = 1 : 3 + for j_ind = 1 : 3 + for l_ind = 1 : 3 + R(k1_ind,k2_ind,i_ind,k_ind) = R(k1_ind,k2_ind,i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * m(l_ind); + W(k1_ind,k2_ind,i_ind,k_ind) = W(k1_ind,k2_ind,i_ind,k_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind) * n(j_ind) * n(l_ind); + end + end + end + end + + R_mat = squeeze(R(k1_ind,k2_ind,:,:)); + W_mat = squeeze(W(k1_ind,k2_ind,:,:)); + + + N1 = -inv(U)*R_mat'; N2 = inv(U); N3 = R_mat*inv(U)*R_mat'-W_mat; + mat = [N1, N2; N3, N1']; + + [eigenvec, eigenval] = eig(mat,'vector'); + + mat_mat(k1_ind,k2_ind,:,:) = mat; + eigenvec_mat(k1_ind,k2_ind,:,:) = eigenvec; + eigenval_mat(k1_ind,k2_ind,:) = eigenval; + + end +end +end + +%% BC matrix solutions +bc_mats = zeros(Nx,Ny,6,6); +strain_bc_mats_inv = zeros(Nx,Ny,6,6); + +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + if( k1_ind ~= 1 || k2_ind ~= 1 ) % Because we divide by K^2 to make matrices better + K = sqrt( kx_grid_2D(k1_ind,k2_ind)^2 + ky_grid_2D(k1_ind,k2_ind)^2 ); + bc_mat = zeros(6,6); + % [ d1 * eigenvec(1,1) + d2 * eigenvec(1,2) + + % d1 * eigenvec(2,1) + d2 * eigenvec(2,2) + + % d1 * eigenvec(3,1) + d2 * eigenvec(3,2) + + % d1 * eigenvec(4,1) + d2 * eigenvec(4,2) + + for m = 1 : 6 % the eigenvalue -> column of eigenvec_mat ~ eigenvector + for k_ind = 1 : 3 % eigenvector a, scale by K + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_sub*1i*K); + end + % rescale by K^-1 to avoid conditioning errors... need to rescale + % the given value as well! + for k_ind = 4 : 6 % eigenvector b + bc_mat(k_ind,m) = eigenvec_mat(k1_ind,k2_ind,k_ind,m) * exp(eigenval_mat(k1_ind,k2_ind,m)*h_film*1i*K) * 1i * K / K^2; + end + end + bc_mats(k1_ind,k2_ind,:,:) = bc_mat; + strain_bc_mats_inv(k1_ind,k2_ind,:,:) = inv(bc_mat); + end +end +end + +strain_bc_mat_inv_korigin = inv([ h_sub 1 0 0 0 0 ; ... + 0 0 h_sub 1 0 0 ; ... + 0 0 0 0 h_sub 1 ; ... + C_FilmRef(1,3,1,3) 0 C_FilmRef(1,3,2,3) 0 C_FilmRef(1,3,3,3) 0 ; ... + C_FilmRef(2,3,1,3) 0 C_FilmRef(2,3,2,3) 0 C_FilmRef(2,3,3,3) 0 ; ... + C_FilmRef(3,3,1,3) 0 C_FilmRef(3,3,2,3) 0 C_FilmRef(3,3,3,3) 0 ]); +strain_bc_mat_inv_korigin = double(strain_bc_mat_inv_korigin);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/finite_diff_x3_second_der.m",".m","528","16","function out = finite_diff_x3_second_der( mat, dz ) + + [~,~,Nz] = size(mat); + out = mat; + + for i = 2 : Nz - 1 + out(:,:,i) = (1/dz^2) * (mat(:,:,i+1) - 2*mat(:,:,i) + mat(:,:,i-1)); + end + + out(:,:,1) = (mat(:,:,2) - mat(:,:,1)) / dz; % approx d/dx3 ~ forward difference + out(:,:,1) = (out(:,:,2) - out(:,:,1)) / dz; % approx d^2/dx3^2 ~ using another forward difference + + out(:,:,end) = (mat(:,:,end) - mat(:,:,end-1)) / dz; + out(:,:,end) = (out(:,:,end) - out(:,:,end-1)) / dz; + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/TransformElasticTensor.m",".m","509","24","% Transform +C_FilmRef = zeros(3,3,3,3); + +for i_ind = 1 : 3 +for j_ind = 1 : 3 +for k_ind = 1 : 3 +for l_ind = 1 : 3 + + for m_ind = 1 : 3 + for n_ind = 1 : 3 + for o_ind = 1 : 3 + for p_ind = 1 : 3 + + C_FilmRef(i_ind,j_ind,k_ind,l_ind) = Transform_Matrix(i_ind,m_ind) * Transform_Matrix(j_ind,n_ind) * Transform_Matrix(k_ind,o_ind) * Transform_Matrix(l_ind,p_ind) * C_CrystalRef(m_ind,n_ind,o_ind,p_ind) + C_FilmRef(i_ind,j_ind,k_ind,l_ind); + + end + end + end + end + +end +end +end +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Visualize.m",".m","1105","25","% subplot(2,3,1); +% surf(z_axis,y_axis,squeeze(P3(:,16,:))); shading interp; view(0,90); axis([min(z_axis) max(z_axis) min(y_axis) max(y_axis)]); colormap parula; +% xlabel('Y (m)'); ylabel('Z (m)'); colorbar +% freezeColors + +subplot(2,2,1); +surf(x_axis*1e9,y_axis*1e9,P3_FilmRef(:,:,film_index)); shading interp; view(0,90); +axis([min(x_axis)*1e9 max(x_axis)*1e9 min(y_axis)*1e9 max(y_axis)*1e9]); colormap parula; +% xlabel('X (m)'); ylabel('Y (m)'); +freezeColors + +subplot(2,2,2); +angle = atan2(P2_FilmRef,P1_FilmRef); surf(x_axis*1e9,y_axis*1e9,angle(:,:,film_index)); view(0,90); colormap hsv; shading interp; +axis([min(x_axis)*1e9 max(x_axis)*1e9 min(y_axis)*1e9 max(y_axis)*1e9]); +caxis([-pi pi]); +% xlabel('X (m)'); ylabel('Y (m)'); +freezeColors + +subplot(2,2,3); +semilogy(errors(1:c)); + +subplot(2,2,4); +% Visualize_3D(P1_FilmRef,P2_FilmRef,P3_FilmRef,x_grid*1e9,y_grid*1e9,z_grid*1e9,interface_index,film_index,Nx,Ny,Nz) +surf(z_axis*1e9,y_axis*1e9,squeeze(P1_FilmRef(:,1,:))); colormap parula; shading interp; view(0,90); +axis([min(z_axis)*1e9 max(z_axis)*1e9 min(y_axis)*1e9 max(y_axis)*1e9]); ","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Setup_BFO_2.m",".m","3106","103","% Run inputs +LOAD = 1; % 1 = Load initial conditions from file called init.mat, 0 = random P initial conditions +E_1_applied_FilmRef = 0; E_2_applied_FilmRef = 0; E_3_applied_FilmRef = 0; % in V/m, 1e5 V/m = 1 kV/cm +T = 27; % in C +Us_11 = 0; % unitless misfit strain +Us_22 = Us_11; % anisotropic misfit strain +STRING = 'BFO small Q44'; % Material Name +VPA_ELECTRIC_ON = 1; % numerical errors when doing electric energy, so we need to use vpa +VPA_ELASTIC_ON = 0; + +%% ---- Nothing needed to modify below ---- %% +% BFO Constants http://www.mmm.psu.edu/JXZhang2008_JAP_Computersimulation.pdf + +%% Convergence +epsilon = 1e-10; % convergence criterion +saves = [0 : 500 : 100000]; % save after this many iterations + +%% Grid Size +Nx = 32; Ny = Nx; Nz = 32; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 28; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 1 && ELASTIC; % automatically 0 if no elastic energy +% no heterogenous elastic relaxation if no elastic energy + +ELECTRIC = 1; +SURFACE_DEPOL = 0; % depolarization energy due to uncompensated surface charges + +NUCLEATE = 0; % nucleation sites, places that don't change during temporal evolution, 1 -> during hysteresis calcs + +ThermConst = 0; % No thermal energy + +%% Elastic Tensor +Poisson_Ratio = 0.35; +Shear_Mod = 0.69 * 1e11; + +C11 = 2 * Shear_Mod * ( 1 - Poisson_Ratio ) / ( 1 - 2 * Poisson_Ratio ); +C12 = 2 * Shear_Mod * Poisson_Ratio / ( 1 - 2 * Poisson_Ratio ); +C44 = Shear_Mod; + +C12 = 1.62 * 1e11; + +C = zeros(3,3,3,3); +C(1,1,1,1) = C11; C(2,2,2,2) = C11; C(3,3,3,3) = C11; +C(1,1,2,2) = C12; C(1,1,3,3) = C12; C(2,2,1,1) = C12; +C(2,2,3,3) = C12; C(3,3,1,1) = C12; C(3,3,2,2) = C12; +C(1,2,1,2) = C44; C(2,1,2,1) = C44; C(1,3,1,3) = C44; +C(3,1,3,1) = C44; C(2,3,2,3) = C44; C(3,2,3,2) = C44; +C(1,2,2,1) = C44; C(2,1,1,2) = C44; C(1,3,3,1) = C44; +C(3,1,1,3) = C44; C(2,3,3,2) = C44; C(3,2,2,3) = C44; + + +%% Electrostriction +Q11 = 0.032; % Q1111 = Q11 +Q12 = -0.016; % Q1122 = Q12 +Q44 = 0.01 * 2; % 2 * Q1212 = Q44 + +q11 = C11 * Q11 + 2 * C12 * Q12; +q12 = C11 * Q12 + C12 * ( Q11 + Q12 ); +q44 = 2 * C44 * Q44; + +%% LGD Constants, stress free BTO +a1_T = @(T) 4.9 * ((T+273)-1103) * 1e5; % T in C +a1 = a1_T(T); +a11 = 5.42 * 1e8; +a12 = 1.54 * 1e8; +a111 = 0; +a112 = 0; +a123 = 0; +a1111 = 0; +a1112 = 0; +a1122 = 0; +a1123 = 0; + +%% Simulation Size +l_0 = 0.5e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = l_0*(Nz-1); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = l_0^2 * a0; +G11 = 0.6 * G110; + +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = G11; % H44 = G44 + G44' + +%% Run time setup +t_0 = 1/a0; +dt = 0.0125/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% Electrical +k_electric_11 = 500; k_electric_22 = k_electric_11; k_electric_33 = k_electric_11;","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/InitP.m",".m","492","14","% Initial Conditions +if( LOAD ) + load('init.mat','P1_FilmRef','P2_FilmRef','P3_FilmRef'); +else + RandomP; +end + +% Thin film simulation +P1_FilmRef(:,:,1:sub_index) = 0; P2_FilmRef(:,:,1:sub_index) = 0; P3_FilmRef(:,:,1:sub_index) = 0; +P1_FilmRef(:,:,film_index+1:end) = 0; P2_FilmRef(:,:,film_index+1:end) = 0; P3_FilmRef(:,:,film_index+1:end) = 0; + +P1_FilmRef_2Dk = fft_2d_slices( P1_FilmRef ); +P2_FilmRef_2Dk = fft_2d_slices( P2_FilmRef ); +P3_FilmRef_2Dk = fft_2d_slices( P3_FilmRef );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/fft_2d_slices.m",".m","160","12","function out = fft_2d_slices( mat ) + + out = mat; + [~, ~, z] = size(mat); + + for i = 1 : z + + out(:,:,i) = fft2(squeeze(mat(:,:,i))); + + end + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Setup.m",".m","3724","111","% Run inputs +LOAD = 1; % 1 = Load initial conditions from file called init.mat, 0 = random P initial conditions +E_1_applied_FilmRef = 0; E_2_applied_FilmRef = 0; E_3_applied_FilmRef = 0; % in V/m, 1e5 V/m = 1 kV/cm +Temperature = 27; % in C +Us_11 = -0.5*1e-2; % unitless misfit strain +Us_22 = Us_11; % anisotropic misfit strain +Us_12 = 0; +STRING = 'BFO_compress'; % Material Name +PATH = './BFO_compress/'; +VPA_ELECTRIC_ON = 1; % numerical errors when doing electric energy, so we need to use vpa +VPA_ELASTIC_ON = 0; +dt_factor = 0.06; + +%% ---- Nothing needed to modify below ---- %% +% BFO Constants http://www.mmm.psu.edu/JXZhang2008_JAP_Computersimulation.pdf + +%% Convergence +epsilon = 1e-5; % convergence criterion +saves = [0 : 1000 : 100000]; % save after this many iterations + +%% Grid Size +Nx = 64; Ny = Nx; Nz = 32; % Grid Points +sub_index = 12; % where substrate starts, >= 1, at and below this index P = 0, substrate thickness +% sub_index = 0 to get no substrate part +interface_index = sub_index + 1; +film_index = 28; % where film ends, <= Nz, above this index, P = 0 +Nz_film = film_index - sub_index; % film lies in the area between sub_index + 1 and film_index, film thickness +Nz_film_sub = film_index; + +%% Energies, 0 = off, 1 = on +ELASTIC = 1; +HET_ELASTIC_RELAX = 1 && ELASTIC; % automatically 0 if no elastic energy +% no heterogenous elastic relaxation if no elastic energy + +ELECTRIC = 1; +SURFACE_DEPOL = 0; % depolarization energy due to uncompensated surface charges + +NUCLEATE = 0; % nucleation sites, places that don't change during temporal evolution, 1 -> during hysteresis calcs + +ThermConst = 0; % No thermal energy + +%% Elastic Tensor +Poisson_Ratio = 0.35; +Shear_Mod = 0.69 * 1e11; + +C11 = 2 * Shear_Mod * ( 1 - Poisson_Ratio ) / ( 1 - 2 * Poisson_Ratio ); +C12 = 2 * Shear_Mod * Poisson_Ratio / ( 1 - 2 * Poisson_Ratio ); +C44 = Shear_Mod; + +C12 = 1.62 * 1e11; + +C_CrystalRef = zeros(3,3,3,3); +C_CrystalRef(1,1,1,1) = C11; C_CrystalRef(2,2,2,2) = C11; C_CrystalRef(3,3,3,3) = C11; +C_CrystalRef(1,1,2,2) = C12; C_CrystalRef(1,1,3,3) = C12; C_CrystalRef(2,2,1,1) = C12; +C_CrystalRef(2,2,3,3) = C12; C_CrystalRef(3,3,1,1) = C12; C_CrystalRef(3,3,2,2) = C12; +C_CrystalRef(1,2,1,2) = C44; C_CrystalRef(2,1,2,1) = C44; C_CrystalRef(1,3,1,3) = C44; +C_CrystalRef(3,1,3,1) = C44; C_CrystalRef(2,3,2,3) = C44; C_CrystalRef(3,2,3,2) = C44; +C_CrystalRef(1,2,2,1) = C44; C_CrystalRef(2,1,1,2) = C44; C_CrystalRef(1,3,3,1) = C44; +C_CrystalRef(3,1,1,3) = C44; C_CrystalRef(2,3,3,2) = C44; C_CrystalRef(3,2,2,3) = C44; + + +%% Electrostriction +Q11 = 0.032; % Q1111 = Q11 +Q12 = -0.016; % Q1122 = Q12 +Q44 = 0.01 * 2; % 2 * Q1212 = Q44 + +q11 = C11 * Q11 + 2 * C12 * Q12; +q12 = C11 * Q12 + C12 * ( Q11 + Q12 ); +q44 = 2 * C44 * Q44; + +%% LGD Constants, stress free BTO +a1_T = @(T) 4.9 * ((T+273)-1103) * 1e5; % T in C +a1 = a1_T(Temperature); +a11 = 5.42 * 1e8; +a12 = 1.54 * 1e8; +a111 = 0; +a112 = 0; +a123 = 0; +a1111 = 0; +a1112 = 0; +a1122 = 0; +a1123 = 0; + +%% Simulation Size +l_0 = 0.5e-9; +Lx = l_0*(Nx-1); Ly = l_0*(Ny-1); Lz = l_0*(Nz-1); + +%% Gradient Free Energy +a0 = abs(a1_T(25)); +G110 = l_0^2 * a0; +G11 = 0.6 * G110; + +G12 = 0; % anisotropic part + +% G44 = G44' +H14 = 0; % H14 = G12 + G44 - G44' +H44 = G11; % H44 = G44 + G44' + +%% Run time setup +t_0 = 1/a0; +dt = dt_factor/(a0); +RUN_TIME = 1; % time, not iterations +MAX_ITERATIONS = RUN_TIME / dt; + +%% Electrical +k_electric_11 = 100; k_electric_22 = k_electric_11; k_electric_33 = k_electric_11; + +%% Transformation from crystal to global +Transform_Matrix = [ 0 1/sqrt(2) -1/sqrt(2); ... + -2/sqrt(6) 1/sqrt(6) 1/sqrt(6); ... + 1/sqrt(3) 1/sqrt(3) 1/sqrt(3) ];","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/Render3D_FilmRef.m",".m","115","1","Visualize_3D(P1_FilmRef,P2_FilmRef,P3_FilmRef,x_grid*1e9,y_grid*1e9,z_grid*1e9,interface_index,film_index,Nx,Ny,Nz)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/ExternalEFieldEnergy.m",".m","330","8","%% External field +f1_ext_E = -E_1_applied_FilmRef .* in_film .* Nucleation_Sites; +f2_ext_E = -E_2_applied_FilmRef .* in_film .* Nucleation_Sites; +f3_ext_E = -E_3_applied_FilmRef .* in_film .* Nucleation_Sites; + +f1_ext_E_2Dk = fft_2d_slices(f1_ext_E); +f2_ext_E_2Dk = fft_2d_slices(f2_ext_E); +f3_ext_E_2Dk = fft_2d_slices(f3_ext_E);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/CalcP_FilmRef.m",".m","327","10","% Calculate P within the film +P1_film = P1_FilmRef(:,:,interface_index:film_index); +P2_film = P2_FilmRef(:,:,interface_index:film_index); +P3_film = P3_FilmRef(:,:,interface_index:film_index); + +P1_val = vol_avg(abs(P1_film)) +P2_val = vol_avg(abs(P2_film)) +P3_val = vol_avg(abs(P3_film)) + +P_val = sqrt(P1_val^2+P2_val^2+P3_val^2)","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/ifft_2d_slices.m",".m","168","12","function out = ifft_2d_slices( mat ) + + out = mat; + [~, ~, z] = size(mat); + + for i = 1 : z + + out(:,:,i) = real(ifft2(squeeze(mat(:,:,i)))); + + end + +end","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/InfinitePlate.m",".m","6139","131","%% Application of Boundary Conditions +% bc in real space + +% 3D fft diff.. +bc_film_1_3Dk = (Eigenstrain_FilmRef_13_k - kx_grid_3D.*u_3_A_k.*1i).*(C11/3 - C12/3 + C44/3) + (Eigenstrain_FilmRef_13_k - kz_grid_3D.*u_1_A_k.*1i).*(C11/3 - C12/3 + C44/3) - (Eigenstrain_FilmRef_12_k - kx_grid_3D.*u_2_A_k.*1i).*((2.^(1/2).*C12)/6 - (2.^(1/2).*C11)/6 + (2.^(1/2).*C44)/3) - (Eigenstrain_FilmRef_12_k - ky_grid_3D.*u_1_A_k.*1i).*((2.^(1/2).*C12)/6 - (2.^(1/2).*C11)/6 + (2.^(1/2).*C44)/3); +bc_film_2_3Dk = (Eigenstrain_FilmRef_23_k - ky_grid_3D.*u_3_A_k.*1i).*(C11/3 - C12/3 + C44/3) + (Eigenstrain_FilmRef_23_k - kz_grid_3D.*u_2_A_k.*1i).*(C11/3 - C12/3 + C44/3) - (Eigenstrain_FilmRef_11_k - kx_grid_3D.*u_1_A_k.*1i).*((2.^(1/2).*C12)/6 - (2.^(1/2).*C11)/6 + (2.^(1/2).*C44)/3) + (Eigenstrain_FilmRef_22_k - ky_grid_3D.*u_2_A_k.*1i).*((2.^(1/2).*C12)/6 - (2.^(1/2).*C11)/6 + (2.^(1/2).*C44)/3); +bc_film_3_3Dk = (Eigenstrain_FilmRef_11_k - kx_grid_3D.*u_1_A_k.*1i).*(C11/3 + (2.*C12)/3 - (2.*C44)/3) + (Eigenstrain_FilmRef_22_k - ky_grid_3D.*u_2_A_k.*1i).*(C11/3 + (2.*C12)/3 - (2.*C44)/3) + (Eigenstrain_FilmRef_33_k - kz_grid_3D.*u_3_A_k.*1i).*(C11/3 + (2.*C12)/3 + (4.*C44)/3); + +% real space bc +% bc applied on the top surface in real space +bc_film_1 = real(ifftn(squeeze(bc_film_1_3Dk))); +bc_film_2 = real(ifftn(squeeze(bc_film_2_3Dk))); +bc_film_3 = real(ifftn(squeeze(bc_film_3_3Dk))); + +bc_film_1 = squeeze(bc_film_1(:,:,film_index)); +bc_film_2 = squeeze(bc_film_2(:,:,film_index)); +bc_film_3 = squeeze(bc_film_3(:,:,film_index)); + +% Strain free substrate +bc_sub_1 = -squeeze(u_1_A(:,:,1)); +bc_sub_2 = -squeeze(u_2_A(:,:,1)); +bc_sub_3 = -squeeze(u_3_A(:,:,1)); + +%% fft2 the bc +bc_film_1_2Dk = fft2(bc_film_1); +bc_film_2_2Dk = fft2(bc_film_2); +bc_film_3_2Dk = fft2(bc_film_3); + +% Orders of magnitude larger... so let's make the matrix better to work with +rescaling_mat = sqrt( kx_grid_2D.^2 + ky_grid_2D.^2 ).^2; +rescaling_mat(1,1) = 1; +bc_film_1_2Dk = bc_film_1_2Dk ./ rescaling_mat; +bc_film_2_2Dk = bc_film_2_2Dk ./ rescaling_mat; +bc_film_3_2Dk = bc_film_3_2Dk ./ rescaling_mat; + +bc_sub_1_2Dk = fft2(bc_sub_1); +bc_sub_2_2Dk = fft2(bc_sub_2); +bc_sub_3_2Dk = fft2(bc_sub_3); + +bc_given_k_space = cat(4,bc_sub_1_2Dk,bc_sub_2_2Dk,bc_sub_3_2Dk,bc_film_1_2Dk,bc_film_2_2Dk,bc_film_3_2Dk); +d_sols = zeros(numel(kx),numel(ky),6); + +%% Apply the boundary conditions to get the solution to the diff. eq. +for k1_ind = 1 : Nx +for k2_ind = 1 : Ny + % Solve the matrix problem + d_sols(k1_ind,k2_ind,:) = squeeze(strain_bc_mats_inv(k1_ind,k2_ind,:,:)) * squeeze(bc_given_k_space(k1_ind,k2_ind,:)); +end +end + +%% Construct the solution in the 2D k-space, kx,ky,z +u_B_2Dk_mat = zeros(Nx,Ny,Nz,3); +u_B_2Dk_d3_mat = zeros(Nx,Ny,Nz,3); + +q_1 = squeeze(d_sols(:,:,1)); +q_2 = squeeze(d_sols(:,:,2)); +q_3 = squeeze(d_sols(:,:,3)); +q_4 = squeeze(d_sols(:,:,4)); +q_5 = squeeze(d_sols(:,:,5)); +q_6 = squeeze(d_sols(:,:,6)); + +p_1 = squeeze(eigenval_mat(:,:,1)); +p_2 = squeeze(eigenval_mat(:,:,2)); +p_3 = squeeze(eigenval_mat(:,:,3)); +p_4 = squeeze(eigenval_mat(:,:,4)); +p_5 = squeeze(eigenval_mat(:,:,5)); +p_6 = squeeze(eigenval_mat(:,:,6)); + +for l_ind = 1 : 3 + for z_loop = 1 : numel(z_axis); + K = sqrt( kx_grid_2D.^2 + ky_grid_2D.^2 ); + + a_vec_1 = squeeze(eigenvec_mat(:,:,l_ind,1)); + a_vec_2 = squeeze(eigenvec_mat(:,:,l_ind,2)); + a_vec_3 = squeeze(eigenvec_mat(:,:,l_ind,3)); + a_vec_4 = squeeze(eigenvec_mat(:,:,l_ind,4)); + a_vec_5 = squeeze(eigenvec_mat(:,:,l_ind,5)); + a_vec_6 = squeeze(eigenvec_mat(:,:,l_ind,6)); + + u_B_2Dk_mat(:,:,z_loop,l_ind) = q_1 .* a_vec_1 .* exp(p_1.*z_axis(z_loop).*1i.*K) + ... + q_2 .* a_vec_2 .* exp(p_2.*z_axis(z_loop).*1i.*K) + ... + q_3 .* a_vec_3 .* exp(p_3.*z_axis(z_loop).*1i.*K) + ... + q_4 .* a_vec_4 .* exp(p_4.*z_axis(z_loop).*1i.*K) + ... + q_5 .* a_vec_5 .* exp(p_5.*z_axis(z_loop).*1i.*K) + ... + q_6 .* a_vec_6 .* exp(p_6.*z_axis(z_loop).*1i.*K); + u_B_2Dk_d3_mat(:,:,z_loop,l_ind) = ( q_1 .* a_vec_1 .* exp(p_1.*z_axis(z_loop).*1i.*K) .* p_1 + ... + q_2 .* a_vec_2 .* exp(p_2.*z_axis(z_loop).*1i.*K) .* p_2 + ... + q_3 .* a_vec_3 .* exp(p_3.*z_axis(z_loop).*1i.*K) .* p_3 + ... + q_4 .* a_vec_4 .* exp(p_4.*z_axis(z_loop).*1i.*K) .* p_4 + ... + q_5 .* a_vec_5 .* exp(p_5.*z_axis(z_loop).*1i.*K) .* p_5 + ... + q_6 .* a_vec_6 .* exp(p_6.*z_axis(z_loop).*1i.*K) .* p_6 ) .* 1i .* K; + end +end + +% 2D origin point... +d_sols(1,1,:) = strain_bc_mat_inv_korigin * squeeze(bc_given_k_space(1,1,:)); + +q = squeeze(d_sols(1,1,:)); +u_B_2Dk_mat(1,1,:,1) = q(1) * z_axis + q(2); +u_B_2Dk_mat(1,1,:,2) = q(3) * z_axis + q(4); +u_B_2Dk_mat(1,1,:,3) = q(5) * z_axis + q(6); +u_B_2Dk_d3_mat(1,1,:,1) = q(1); +u_B_2Dk_d3_mat(1,1,:,2) = q(3); +u_B_2Dk_d3_mat(1,1,:,3) = q(5); + +u_1_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,1)); +u_2_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,2)); +u_3_B_2Dk = squeeze(u_B_2Dk_mat(:,:,:,3)); +u_1_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,1)); +u_2_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,2)); +u_3_B_2Dk_d3 = squeeze(u_B_2Dk_d3_mat(:,:,:,3)); + +%% Calculate the strains, e_ij = 0.5 * (u_i,j + u_j,i) +e_11_B_2Dk = u_1_B_2Dk .* 1i .* kx_grid_3D; +e_22_B_2Dk = u_2_B_2Dk .* 1i .* ky_grid_3D; +e_33_B_2Dk = u_3_B_2Dk_d3; +e_23_B_2Dk = 0.5 * (u_2_B_2Dk_d3 + 1i .* ky_grid_3D .* u_3_B_2Dk); +e_13_B_2Dk = 0.5 * (u_1_B_2Dk_d3 + 1i .* kx_grid_3D .* u_3_B_2Dk); +e_12_B_2Dk = 0.5 * (1i .* ky_grid_3D .* u_1_B_2Dk + 1i .* kx_grid_3D .* u_2_B_2Dk); + +%% Final outputs +u_1_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,1))); +u_2_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,2))); +u_3_B = ifft_2d_slices(squeeze(u_B_2Dk_mat(:,:,:,3))); + +e_11_B = ifft_2d_slices(e_11_B_2Dk); +e_22_B = ifft_2d_slices(e_22_B_2Dk); +e_33_B = ifft_2d_slices(e_33_B_2Dk); +e_23_B = ifft_2d_slices(e_23_B_2Dk); +e_13_B = ifft_2d_slices(e_13_B_2Dk); +e_12_B = ifft_2d_slices(e_12_B_2Dk);","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/NonRandomInit.m",".m","1031","27","%% +RandomP; + +% Remember changing first variable is y axis!! +% P(y,x,z); + +P1_FilmRef(1:12,:,:) = P1_FilmRef(1:12,:,:) - 0.003; +P2_FilmRef(1:12,:,:) = P2_FilmRef(1:12,:,:) - 0.003; +P3_FilmRef(1:12,:,:) = P3_FilmRef(1:12,:,:) - 0.003; + +P1_FilmRef(13:24,:,:) = P1_FilmRef(13:24,:,:) + 0.0015; +P2_FilmRef(13:24,:,:) = P2_FilmRef(13:24,:,:) - 0.003; +P3_FilmRef(13:24,:,:) = P3_FilmRef(13:24,:,:) - 0.003; +P1_FilmRef(13:24,:,end-20:end) = P1_FilmRef(13:24,:,end-20:end) + 0.0015; +P1_FilmRef(13:24,:,end-15:end) = P1_FilmRef(13:24,:,end-15:end) + 0.0015; +P1_FilmRef(13:24,:,end-10:end) = P1_FilmRef(13:24,:,end-10:end) + 0.0015; +P1_FilmRef(13:24,:,end-5:end) = P1_FilmRef(13:24,:,end-5:end) + 0.0015; + +P1_FilmRef(25:end,:,:) = P1_FilmRef(25:end,:,:) - 0.003; +P2_FilmRef(25:end,:,:) = P2_FilmRef(25:end,:,:) - 0.003; +P3_FilmRef(25:end,:,:) = P3_FilmRef(25:end,:,:) - 0.003; + +P1_FilmRef = P1_FilmRef .* in_film; +P2_FilmRef = P2_FilmRef .* in_film; +P3_FilmRef = P3_FilmRef .* in_film; + +save('init.mat','P1_FilmRef','P2_FilmRef','P3_FilmRef');","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/DomainPctCalc.m",".m","3650","74","%% For P1_CrystalRef ~ P2 ~ P3 within the domain +% Polar Angle +R = sqrt( P1_CrystalRef.^2 + P2_CrystalRef.^2 + P3_CrystalRef.^2 ); +Theta = acos( P3_CrystalRef ./ R ); % -> [0,pi] +Phi = atan2( P2_CrystalRef, P1_CrystalRef ); % -> [-pi,pi] + +threshold_P1_CrystalRef = 5e-2; % P1_CrystalRef ~ 0 +threshold_P2_CrystalRef = 5e-2; % P2_CrystalRef ~ 0 +threshold_P3_CrystalRef = 5e-2; % P3_CrystalRef ~ 0 + +total_el = sum(sum(sum( P1_CrystalRef ~= 0))); + +%% Tetragonal +a1 = ( abs(P1_CrystalRef) > threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) < threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) < threshold_P3_CrystalRef ); +a2 = ( abs(P1_CrystalRef) < threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) > threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) < threshold_P3_CrystalRef ); +c = ( abs(P1_CrystalRef) < threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) < threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) > threshold_P3_CrystalRef ); + + +%% Orthorhombic +O12 = ( abs(P1_CrystalRef) > threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) > threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) < threshold_P3_CrystalRef ); +O13 = ( abs(P1_CrystalRef) > threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) < threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) > threshold_P3_CrystalRef ); +O23 = ( abs(P1_CrystalRef) < threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) > threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) > threshold_P3_CrystalRef ); + + +%% Rhombohedral +r = ( abs(P1_CrystalRef) > threshold_P1_CrystalRef ) & ( abs(P2_CrystalRef) > threshold_P2_CrystalRef ) & ( abs(P3_CrystalRef) > threshold_P3_CrystalRef ); + +%% Calc +a1_calc = sum(sum(sum(a1))) /total_el; +a2_calc = sum(sum(sum(a2))) /total_el; +c_calc = sum(sum(sum(c))) / total_el; + +O12_calc = sum(sum(sum(O12))) / total_el; +O13_calc = sum(sum(sum(O13))) / total_el; +O23_calc = sum(sum(sum(O23))) / total_el; + +r_calc = sum(sum(sum(r))) / total_el; + +Names = {'a1','a2','c','O12','O13','O23','r'} +Pcts = [a1_calc,a2_calc,c_calc,O12_calc,O13_calc,O23_calc,r_calc] +Avg_val = [ mean(mean(mean(abs(P1_CrystalRef)))); mean(mean(mean(abs(P2_CrystalRef)))); mean(mean(mean(abs(P3_CrystalRef))))]' + + + +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Trash +% %% Tetragonal +% % a1/a2 domain, Theta ~pi/2 ; Phi ~ 0, pi/2, pi, -pi, -pi/2 +% a1_a2 = ( abs(Theta - (pi/2)) < threshold_angle ) & ... +% ( abs(abs(Phi) - pi) < threshold_angle | abs(abs(Phi) - (pi/2)) < threshold_angle ) ; +% +% % c domain, Theta ~0,pi ; Phi ~0 +% c = ( Theta < threshold_angle | abs(Theta - pi) < threshold_angle ) & ... +% ( abs(P1_CrystalRef) < threshold_mag & abs(P2_CrystalRef) < threshold_mag ); +% +% %% Orthorhombic +% % aa1/aa2 domain, Theta ~pi/2, Phi ~ pi/4, 3*pi/4, -pi/4, -3*pi/4 +% aa1_aa2 = ( abs(Theta - (pi/2)) < threshold_angle ) & ... +% ( abs(abs(Phi) - (pi/4)) < threshold_angle | abs(abs(Phi) - (3*pi/4)) < threshold_angle ) ; +% +% % P1_CrystalRef ~ P3_CrystalRef, P2_CrystalRef ~ 0 +% % Theta ~ pi/4, 3pi/4 ; Phi ~ 0, pi +% a1_c = ( abs(Theta - (pi/4)) < threshold_angle | abs(Theta - (3*pi/4)) < threshold_angle ) & ... +% ( abs(Phi) < threshold_angle | abs(abs(Phi) - pi) < threshold_angle ); +% +% % P1_CrystalRef ~ 0, P2_CrystalRef ~ P3_CrystalRef +% % Theta ~ pi/4, 3pi/4 ; Phi ~ pi/2, 3pi/2 +% a2_c = ( abs(Theta - (pi/4)) < threshold_angle | abs(Theta - (3*pi/4)) < threshold_angle ) & ... +% ( abs(abs(Phi) - (pi/2)) < threshold_angle | abs(abs(Phi) - (3*pi/2)) < threshold_angle ); +% +% +% %% Rhombohedral +% r = ( abs(Theta - (pi/6)) < threshold_angle | abs(Theta - (5*pi/6)) < threshold_angle ) & ... +% ( abs(abs(Phi) - (pi/4)) < threshold_angle | abs(abs(Phi) - (3*pi/4)) + threshold_angle );","MATLAB" +"Substrate","geoffxiao/Phase-Field-Modeling","(111)/finite_diff_x3_first_der.m",".m","389","14","function out = finite_diff_x3_first_der( mat, dz ) + + [~,~,Nz] = size(mat); + out = mat; + + for i = 2 : Nz - 1 + out(:,:,i) = (1/dz) * ( (-1/2) * mat(:,:,i-1) + (1/2) * mat(:,:,i+1) ); + end + + % approximate endpoints using forward difference + out(:,:,1) = ( mat(:,:,2) - mat(:,:,1) ) / dz; + out(:,:,end) = ( mat(:,:,end) - mat(:,:,end-1) ) / dz; + +end","MATLAB" +"Substrate","tnecio/supercell-core","setup.py",".py","1096","42","import setuptools + +with open(""README.md"", ""r"") as fh: + long_description = fh.read() + + +def readme(): + with open('README.rst') as f: + return f.read() + + +setuptools.setup( + name='supercell_core', + version='0.1.6', + packages=setuptools.find_packages(), + url='https://github.com/tnecio/supercell-core', + license='GPLv3', + author='Tomasz Necio', + author_email='Tomasz.Necio@fuw.edu.pl', + description='Package for investigation of 2D van der Waals heterostructures\' lattices', + long_description=long_description, + long_description_content_type=""text/markdown"", + classifiers=[ + ""Programming Language :: Python :: 3"", + ""Operating System :: OS Independent"", + ""Intended Audience :: Science/Research"", + ""License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)"", + ""Topic :: Scientific/Engineering :: Physics"" + ], + include_package_data=True, + install_requires=[ + 'numpy', + 'matplotlib' + ], + # TODO: doc + extras_require={ + 'log' : [ + 'pandas' + ] + } +) +","Python" +"Substrate","tnecio/supercell-core","supercell_core/calc.py",".py","3263","136",""""""" +Small utilities to help with various numeric calculations, +especially with operations on arrays of matrices +"""""" + +from typing import List +import numpy as np + +ABS_EPSILON = 1e-6 + + +def rotate(a: np.ndarray, theta: float) -> np.ndarray: + """""" + Rotates vectors stored in 2D matrices columns in array `a` by angle `theta` + counterclockwise + + Parameters + ---------- + a : np.ndarray + theta : float + + Returns + ------- + np.ndarray + """""" + return np.array(((np.cos(theta), -np.sin(theta)), + (np.sin(theta), np.cos(theta)))) @ a + + +def matvecmul(m: np.ndarray, v: np.ndarray) -> np.ndarray: + """""" + Acts with 2D matrix m on 2D vectors stored in array `v` + + Parameters + ---------- + m : np.ndarray, shape (..., 2, 2) + v : np.ndarray, shape (..., 2) + + Returns + ------- + np.ndarray, shape = v.shape + """""" + res = np.empty(v.shape) + res[..., 0] = m[..., 0, 0] * v[..., 0] + m[..., 0, 1] * v[..., 1] + res[..., 1] = m[..., 1, 0] * v[..., 0] + m[..., 1, 1] * v[..., 1] + return res + + +def matmul(m1: np.ndarray, m2: np.ndarray) -> np.ndarray: + """""" + Calculates matrix multiplication of 2D matrices stored in arrays `m1` and `m2` + + Parameters + ---------- + m1 : np.ndarray, shape(..., 2, 2) + m2 : np.ndarray, shape(..., 2, 2) + + Returns + ------- + np.ndarray, shape(..., 2, 2) + """""" + return m1 @ m2 + + +def inv(m: np.ndarray) -> np.ndarray: + """""" + Inverts 2x2 matrices. Why not use np.linalg.inv? To avoid LinAlgError when + just one of the matrices is singular, and fill it with nans instead + These are all 2x2 matrices so no harm in inverting them + + Parameters + ---------- + m : np.ndarray, shape (..., 2, 2) + Array of matrices + + Returns + ------- + np.ndarray + """""" + det_m = np.linalg.det(m) + res = np.moveaxis( + (1.0 / det_m) * np.array(((m[..., 1, 1], -m[..., 0, 1]), + (-m[..., 1, 0], m[..., 0, 0]))), + (0, 1), + (-2, -1)) + res[np.abs(det_m) < 1e-8] = np.nan + return res + + +def matnorm(m: np.ndarray, p: float, q: float) -> np.ndarray: + """""" + Calculates L_{p, q} matrix norm for every 2D matrix in array `m`. + This norm is defined as :math:`(\sum_j (\sum_i |m_{ij}|^p)^{q/p})^{1/q}` [1] + + Parameters + ---------- + m : np.ndarray, shape (..., 2, 2) + p : float >= 1 + q : float >= 1 + + Returns + ------- + np.ndarray + + Notes + ----- + + Useful norms for strain calculations: + Frobenius norm: ord_p = ord_q = 2 + Absolute sum of elements: ord_p = ord_q = 1 + + References + ---------- + [1] https://en.wikipedia.org/wiki/Matrix_norm#L2,1_and_Lp,q_norms + """""" + return ((np.abs(m[..., 0, 0]) ** p + np.abs(m[..., 0, 1]) ** p) ** (q / p) + + (np.abs(m[..., 1, 0]) ** p + np.abs(m[..., 1, 1]) ** p) ** (q / p)) \ + ** (1 / q) + + +def vecnorm(v: np.ndarray, q: float) -> np.ndarray: + """""" + Calculates norm of every 2D vector in `v` + + Parameters + ---------- + m : np.ndarray, shape (..., 2) + q : float >= 1 + + Returns + ------- + np.ndarray + """""" + # NOTE: No ` ** (1 / q)` because we only use these values for comparison + return np.abs(v[..., 0]) ** q + np.abs(v[..., 1]) ** q +","Python" +"Substrate","tnecio/supercell-core","supercell_core/errors.py",".py","1593","52",""""""" +Contains custom Exceptions, Warnings, and their descriptions +"""""" + +# warn is used by other files importing * from errors +import warnings +from enum import Enum + + +class LinearDependenceError(Exception): + """""" + An exception thrown when a set of linearly independent vectors is expected, + but supplied values have a pair of linearly dependent vectors in them. + """""" + pass + + +class BadUnitError(Exception): + """""" + An exception thrown when specified unit can not be used in a given context + """""" + pass + + +class UndefinedBehaviourError(Exception): + """""" + An exception thrown when it's not clear what the user's intention was + """""" + pass + + +class ParseError(Exception): + """""" + An exception thrown when incorrect data are passed to parsing or reading + functions + """""" + pass + + +class WarningText(Enum): + """""" + Enumeration that contains warning messages text + + Warnings are logged when some function in the package was used in a way + that suggests something is incorrect, but it's not clear, and calculation + can be done anyway + """""" + ZComponentWhenNoZVector = ""A z-component of a vector was specified, but only 2 vectors were given, causing the 3rd one to be set to default value"" + ReassigningPartOfVector = ""You reassign only a part of a vector, other elements of which were previously set to non-default values; Values of those other elements will be retained"" + AtomOutsideElementaryCell = ""Atom position specified outside the elementary cell"" + UnknownChemicalElement = ""Chemical element symbol not found in the periodic table"" +","Python" +"Substrate","tnecio/supercell-core","supercell_core/heterostructure_opt.py",".py","16061","430","from typing import List, Iterable, Dict, Any +import itertools +from abc import abstractmethod + +try: + import pandas as pd +except ImportError: + pd = None + +from .physics import * +from .result import * +from .calc import * + + +class OptSolverConfig: + """""" + TODO + + Attributes + ---------- + ord : (int, int) + (p, q) for calculating L_{p, q} norm of the strain tensor + max_el : int + Maximum absolute value of ADt matrix element + log : bool + Whether to save a log or not. Setting to `True` requires `pandas` + """""" + ord: Tuple[int, int] + max_el: int + log: bool # log really ought to be a pandas.DataFrame + + def __init__(self): + # Some default values + self.ord = (1, 1) + self.max_el = 10 + self.log = False + + +class OptSolver: + """""" + + TODO documentation + """""" + + def __init__(self, + XA: Matrix2x2, + XBs: List[Matrix2x2], + thetas: List[np.ndarray], + config: OptSolverConfig): + self.XA = XA + self.XBs = XBs + self.thetas = thetas # List of arrays of floats, corresponding to XBs + self.config = config + if self.config.log: + self.log = {} + columns = [ + *[""theta_{}"".format(i) for i in range(len(thetas))], + ""max_strain"", + ""supercell_size"", + ""M_11"", ""M_12"", ""M_21"", ""M_22"", + *[""N{}_{}{}"".format(n+1, i+1, j+1) for n in range(len(XBs)) for i in range(2) for j in range(2)], + ""supercell_vectors_11"", ""supercell_vectors_12"", + ""supercell_vectors_21"", ""supercell_vectors_22"", + *[""strain_tensor_layer_{}_{}{}"".format(k + 1, i + 1, j + 1) + for k in range(len(thetas)) + for i in range(2) for j in range(2)] + ] + for column in columns: + self.log[column] = [] + if pd is None: + print(""Pandas not installed! Returning a dictionary instead (log)"") # Jezu jak źle + + # Prepare all possible dt vectors (in A basis) + self.dt_As = np.array([]) + self.prepare_dt_As() + + # Dummy start value for classic O(n) find min algorithm, we want to find + # values for which sum of `quality_fun`(strain tensor) is minimal + # (thetas, min_qty, XDt, strain_tensors) + self.res: Tuple[List[Angle], float, Matrix2x2, List[Matrix2x2]] = \ + ([], np.inf, np.identity(2), []) + + def _calculate_strain_tensor(self, ADt: Matrix2x2, XBr: Matrix2x2) -> Matrix2x2: + """""" + Calculate strain tensor. + + See docs of `Heterostructure.calc` for definition of strain tensor. + + Parameters + ---------- + ADt : Matrix 2x2 + XBr : Matrix 2x2 + + Returns + ------- + Matrix 2x2 + """""" + BrDt = inv(XBr) @ self.XA @ ADt + BtrDt = np.round(BrDt) + BtrBr = BtrDt @ inv(BrDt) + return BtrBr - np.identity(2) + + def prepare_dt_As(self) -> None: + """""" + Prepares dt_As for the calculation. + + Returns + ------- + None + """""" + # Let's imagine all possible superlattice vectors (dt vectors). At the + # very least, they need to be able to recreate the substrate lattice. + # We assume substrate lattice to be constant. + # Thus every grid point in substrate basis (A) is a valid dt vector + span_range = np.arange(0, 2 * self.config.max_el + 1) + span_range[(self.config.max_el + 1):] -= 2 * self.config.max_el + 1 + self.dt_As = np.transpose(np.meshgrid(span_range, span_range)) + self.dt_As[0, 0] = [0, 1] # Hack to remove ""[0, 0]"" vector + + def _update_opt_res(self, + thetas: Tuple[Angle, ...], + ADt: np.ndarray, + sts: List[Matrix2x2], + ) -> None: + """""" + Checks if newly calculated result is better than the previous one + (this usually means that the strain measure `qty` is smaller), + and if so updates it accordingly + + Parameters + ---------- + thetas : Collection[float] + ADt : Matrix2x2 + sts : List[Matrix2x2] + + Returns + ------- + None + """""" + min_qty = sum([matnorm(st, *self.config.ord) for st in sts]) + XDt = self.XA @ ADt + + # 0. Update log if necessary (TODO: tests, doc, make a warning if log=True and no pandas) + new_res = (list(thetas), min_qty, XDt, sts) + new_size = np.abs(np.linalg.det(XDt)) + if self.config.log: + for i, theta in enumerate(thetas): + self.log[""theta_{}"".format(i)].append(theta) + self.log[""max_strain""].append(min_qty) + self.log[""supercell_size""].append(new_size) + for i in range(2): + for j in range(2): + self.log[""M_{}{}"".format(i + 1, j + 1)].append(ADt[i, j]) + self.log[""supercell_vectors_{}{}"".format(i + 1, j + 1)].append(XDt[i, j]) + for k, st in enumerate(sts): + self.log[""strain_tensor_layer_{}_{}{}"".format(k + 1, i + 1, j + 1)].append( + sts[k][i, j] + ) + + # 1. Check for smaller supercell quality function + if min_qty - ABS_EPSILON > self.res[1]: + return + + # Here it is most efficient to check whether we aren't at the beginning + # (res[0] is None in that case) + if (min_qty + ABS_EPSILON < self.res[1]) or (self.res[0] is None): + self.res = new_res + + # 2. If qties are almost equal, choose smaller elementary cell + old_size = np.abs(np.linalg.det(self.res[2])) + if new_size < old_size - ABS_EPSILON: + self.res = new_res + elif old_size < new_size - ABS_EPSILON: + return + + # 3. If even the sizes are equal, return the cell more 'square-y' + # here it will mean the cell with smaller |max_lattice_vector_element| + if np.max(np.abs(XDt)) < np.max(np.abs(self.res[2])): + self.res = new_res + + def get_result(self) -> Tuple[List[float], Matrix2x2, Dict[str, Any]]: + """""" + TODO + Returns: + ADt, thetas + """""" + thetas, min_qty, XDt, strain_tensors = self.res + ADt = inv(self.XA) @ XDt + + additional = {} + if self.config.log: + if pd is not None: + self.log = pd.DataFrame(self.log) + additional[""log""] = self.log + return thetas, ADt, additional + + @abstractmethod + def solve(self) -> Tuple[List[float], Matrix2x2, Dict[str, Any]]: + """""" + This routine calculates optimal supercell lattice vectors, layers' + rotation angles and their strain tensors. Here, optimal means + values that result in L_{1, 1} strain tensor norm to be smallest + :math:`L_{11}(\epsilon) = \max_{ij} |\epsilon_{ij}\` [1]. + You can change used norm by setting appropriate value of `ord` + in object passed to `OptSolver.config`. + + Returns + ------- + thetas: List[float] + List of optimal theta values corresponding to the Heterostructure + layers. Length is equal to the number of layers. + ADt: Matrix2x2 + Best ADt matrix found + """""" + pass + + +class StrainOptimisator(OptSolver): + """""" + TODO: copy from supercell_core 0.0.6 + """""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.dt_xs = matvecmul(self.XA, self.dt_As) + span = self.dt_As.shape[0] + self.ADts = np.empty((span, span, span, span, 2, 2)) + self.ADts[..., 0] = self.dt_As[np.newaxis, np.newaxis, ...] + self.ADts[..., 1] = self.dt_As[..., np.newaxis, np.newaxis, :] + + def _get_strain_tensors_opt(self, + theta_comb: Tuple[float]) -> List[np.ndarray]: + """""" + Calculates strain tensor for `solve`. + + Parameters + ---------- + theta_comb : Tuple[float] + Length must correspond to self.XBs + + Returns + ------- + List[np.ndarray with shape (span, span, span, span, 2, 2)] + + Notes + ----- + Definiton of strain tensor here is the same as in documentation + for `calc` + """""" + return [self._calculate_strain_tensor(self.ADts, rotate(XB, theta)) + for XB, theta in zip(self.XBs, theta_comb)] + + def _get_d_xs(self, + XB: np.ndarray, + theta: Angle) -> np.ndarray: + """""" + Returns an array of `d` vectors in Cartesian basis + + Parameters + ---------- + XB : Matrix 2x2 + theta : float + + Returns + ------- + np.ndarray, shape (..., 2) + """""" + XBr = rotate(XB, theta) + BrA = inv(XBr) @ self.XA + dt_Brs = matvecmul(BrA, self.dt_As) + + # Here we use the fact that the supercell must ""stretch"" lattice vectors + # of constituent layers so that they superlattice vectors are linear + # _integer_ combinations of any one layers' lattice vectors. + dt_Btrs = np.round(dt_Brs) + d_Brs = dt_Btrs + return matvecmul(XBr, d_Brs) + + def solve(self) -> Tuple[List[float], Matrix2x2, Dict[str, Any]]: + # embarrasingly parallel, but Python GIL makes this irrelevant + for theta_comb in itertools.product(*self.thetas): + strain_tensors = self._get_strain_tensors_opt(theta_comb) + + # qty – array which contains norms of the strain tensors + qty = sum([matnorm(st, *self.config.ord) for st in strain_tensors]) + + # if qty is NaN it means that we somehow ended up with linear + # dependence; in the limit strain would go to infinity + qty[np.isnan(qty)] = np.inf + + linalg_fix = True # sometimes we get a linearly dependent ADt anyway, TODO: why + while linalg_fix: + argmin_indices = np.unravel_index(qty.argmin(), qty.shape) + min_sts = [st[argmin_indices] for st in strain_tensors] + ADt = np.stack((self.dt_As[argmin_indices[0], argmin_indices[2]], + self.dt_As[argmin_indices[1], argmin_indices[3]])) + if np.isclose(np.linalg.det(ADt), 0): + qty[argmin_indices] = np.inf + else: + linalg_fix = False + + # let's check if the best values for this combination of theta vals + # (theta_lay) are better than those we already have + self._update_opt_res(theta_comb, ADt, min_sts) + + return self.get_result() + + +class MoireFinder(OptSolver): + """""" + TODO + """""" + + def solve(self) -> Tuple[List[float], Matrix2x2, Dict[str, Any]]: + # Precalculate qualities of solutions here, since this problem is independent for + # each layer; the final solution depends on a specific combination of thetas + # but to calculate how much stretched the Br basis will be for each possible dt + # vector will be we only need to know the Br (theta + XB) + # Complexity: O(thetas_len * no. layers * max_el ** 2) + memo = {} + for i, (theta_, XB) in enumerate(zip(self.thetas, self.XBs)): + for theta in theta_: + qtys = self._fast(XB, theta) + memo[float(theta), i] = qtys + + # We need to have this loop over all possible combinations since + # ADt is one for the whole structure and must minimise strains in + # all layers simulatneously + # Complexity: O(thetas_len ** no. layers * max_el ** 2) + # Could probably use a few tricks to get it down to stg like O(thetas_len ** no. layers) + # or at least O(thetas_len ** no. layers * max_el) + for theta_comb in itertools.product(*self.thetas): + qtyss = [memo[float(theta), i] for i, theta in enumerate(theta_comb)] + qtys_total = sum(qtyss) + + ADt = np.zeros((2, 2)) + # This loop is in practice O(1) since the number of vectors giving singular ADt + # is O(max_el) and then, if for one such vector the qty != 0 then it's very + # unprobable that the second one will happen to be parallel + while all(ADt[:, 0] == 0) or all(ADt[:, 1] == 0): + argmax_indices = np.unravel_index(qtys_total.argmax(), qtys_total.shape) + qtys_total[argmax_indices] = -np.inf # removes this vector from ""search pool"" + vec = self.dt_As[argmax_indices] + + if all(ADt[:, 0] == 0): + ADt[:, 0] = vec + else: + ADt[:, 1] = vec + if not self._is_ADt_acceptable(ADt, theta_comb): + # Back off from adding this vec + ADt[:, 1] = 0 + # Note: we always use the best candidate vec and only consider + # the second one (ADt[:. 1]) suspicious because if it is in fact bad + # the it must be almost-parallel or parallel to the first one, so + # it doesn't matter much which one we pick to stay + + # Check if result for this angle combination is better than for the previous one + # Here, we use the exact quality measure, which is sum of norms of strain tensors + XBrs = [rotate(XB, theta) for (XB, theta) in zip(self.XBs, theta_comb)] + sts = [self._calculate_strain_tensor(ADt, XBr) for XBr in XBrs] + # TODO: move to update_opt_res + + self._update_opt_res(theta_comb, ADt, sts) + + return self.get_result() + + def _fast(self, XB: Matrix2x2, theta: float) -> np.ndarray: + """""" + Calculates qualities of each dt vector in dt_As, + where the measure of quality is a heuristic of + how much will the d vector be stretched for given dt + vector; the higher the quality the better. + + Parameters + ---------- + XB : Matrix2D + theta : float + + Returns + ------- + qtys : np.ndarray, shape (span, span) + Quality of corresponding dt vectors + Calculated as ||d - dt||_1 / |d| + """""" + # T = rotation_matrix(theta) in A basis @ AB = AX @ rotation_matrix(theta) @ XA @ AB + # T_inv to solve equation [n1, n2] == T @ [m1, m2], + # where dt_i == n1 a_1 + n2 a_2 == m1 b_1 + m2 b_2 + # this is a 2D matrix, so solving by inv is OK + T_inv = inv(XB) @ np.array([ + [np.cos(theta), np.sin(theta)], + [-np.sin(theta), np.cos(theta)] + ]) @ self.XA + + solution_vecs = matvecmul(T_inv, self.dt_As) # dt_B + qtys = -vecnorm((solution_vecs - np.round(solution_vecs)), 1) / np.sqrt( + vecnorm(solution_vecs, 2)) # TODO: better measure + # TOO self.__calc_strain_tensor_from_ADt(ADt, XBr) + return qtys + + def _is_ADt_acceptable(self, ADt: Matrix2x2, thetas: Iterable[float]) -> bool: + """""" + Checks if given ADt can be a solution + + Parameters + ---------- + ADt : Matrix2D + thetas : List[float] + corresponds to layers of the heterostructure + + Returns + ------- + bool + """""" + # 1. Is det != 0 ? + if np.isclose(np.linalg.det(ADt), 0): + return False + + # 2. Is det in any other basis == 0? + # This can happen when the solution to the equation in `_fast` is bad and gives + # e.g. values close to zero; this translates to impossible stretching of Br + XBrs = [rotate(XB, theta) for XB, theta in zip(self.XBs, thetas)] + BrDts = [inv(XBr) @ self.XA @ ADt for XBr in XBrs] + BtrDts = [np.round(BrDt) for BrDt in BrDts] + zero_dets = [x[0][0] * x[1][1] == x[0][1] * x[1][0] for x in BtrDts] + if any(zero_dets): + ADt[:, 1] = 0 + return False + + return True +","Python" +"Substrate","tnecio/supercell-core","supercell_core/result.py",".py","5440","176","from typing import List +import numpy as np + +from .lattice import Lattice +from .physics import Angle, Matrix2x2 +from .calc import inv, matnorm + + +class Result: + """""" + A class containing results of supercell calculations. + + Notes + ----- + Terminology: + + MN – basis change matrix from N to M + (the order of the letters makes it easy to combine these: + MM' @ M'N == MN) + v_M – vector v (unit vector of basis V) in basis M + v_Ms – an array of vectors v in basis M + stg_lay – list of ""stg"" for each of the layers + (len(stg_lay) == len(self.layers())) + + A, a – basis of lattice vectors of the substrate + B, b – basis of lattice vectors of a given layer + Br, br – basis B rotated by theta angle + Btr, btr – basis of lattice vectors of a given layer when embedded + in the heterostructure (rotated – r, and stretched + due to strain – t) + D, d – basis of vectors composed of integer linear combinations of + the B basis vectors + Dt, dt – basis of vectors composed of the integer linear combinations + of the A basis vectors, represents possible supercell lattice + vectors + X, x – cartesian basis (unit vectors: (1 angstrom, 0), + (0, 1 angstrom)) + + Note that the vector space of all the mentioned objects is R^2 + """""" + __heterostructure: ""Heterostructure"" + __superlattice: Lattice + __thetas: List[Angle] + __strain_tensors: List[Matrix2x2] + __ADt: Matrix2x2 + __ABtrs: List[Matrix2x2] + + def __init__(self, + heterostructure: ""Heterostructure"", + superlattice: Lattice, + thetas: List[Angle], + strain_tensors: List[Matrix2x2], + strain_tensors_wiki: List[Matrix2x2], + ADt: Matrix2x2, + ABtrs: List[Matrix2x2], + atom_count = None): + """""" + + Parameters + ---------- + heterostructure : Heterostructure + superlattice : Lattice + thetas : List[float] + strain_tensors : List[Matrix2x2] + in cartesian basis + strain_tensors_wiki : List[Matrix2x2] + ADt : Matrix2x2 + ABtrs : List[Matrix2x2] + """""" + self.__heterostructure = heterostructure + self.__superlattice = superlattice + self.__thetas = thetas + self.__strain_tensors = strain_tensors + self.__strain_tensors_wiki = strain_tensors_wiki + self.__ADt = ADt + self.__ABtrs = ABtrs + self.__atom_count = len(self.superlattice().atoms()) if atom_count is None else round(atom_count) + + def strain_tensors(self, wiki_definition=False) -> \ + List[Matrix2x2]: + """""" + Returns list of strain tensors for each of the heterostructure's layers. + + Parameters + ---------- + wiki_definition : optional, bool + Default: False. + If True, definition from [1] will be used instead of the default + (see docs of `Heterostructure.calc` for details) + + Returns + ------- + List[Matrix2x2] + + References + ---------- + [1] https://en.wikipedia.org/wiki/Infinitesimal_strain_theory + """""" + if wiki_definition: + return self.__strain_tensors_wiki + return self.__strain_tensors + + def max_strain(self): + """""" + Returns absolute maximum value of sum of strains on all layers. + + Returns + ------- + float + + Notes + ----- + The returned value is minimised in `Heterostructure.opt` calculations. + """""" + # sum instead of np.sum because we want to add matrices in a list, + # not sum all elements of these matrices + return sum([matnorm(st, 1, 1) for st in self.strain_tensors()]) + + def M(self) -> Matrix2x2: + """""" + Returns 2D matrix M: M @ (v in supercell basis) = (v in substrate lattice + basis). In other words, matrix composed of superlattice vectors + in substrate lattice basis. All matrix components are integers. + + Returns + ------- + Matrix2x2 + """""" + return self.__ADt + + def layer_Ms(self) -> List[Matrix2x2]: + """""" + Returns list of matrices Mi: Mi @ (v in supercell basis) = (v in basis + of heterostructure layer no. i when it is stretched due to strain). + In other words, list of matrices composed of superlattice + vectors in stretched layers' lattice basis. + All matrix components are integers. + + Returns + ------- + Matrix2x2 + """""" + return [inv(ABtr) @ self.__ADt for ABtr in self.__ABtrs] + + def atom_count(self) -> int: + """""" + Returns number of atoms in the superlattice elementary cell + + Returns + ------- + int + """""" + return self.__atom_count + + def superlattice(self) -> Lattice: + """""" + Returns a Lattice object representing supercell (elementary cell + of the heterostructure) + + Returns + ------- + Lattice + """""" + return self.__superlattice + + def thetas(self) -> List[Angle]: + """""" + Returns list of theta values corresponding to the layers + in the heterostructure. (in radians) + + Returns + ------- + List[float] + """""" + return self.__thetas +","Python" +"Substrate","tnecio/supercell-core","supercell_core/physics.py",".py","3391","118",""""""" +This file contains names of various physical qties, objects, units etc. +and their mapping to values used in the calculations +"""""" + +from typing import Union, Sequence, List, Tuple +from enum import Enum, auto +import numpy as np + +# Type alias for acceptable numeric values +Number = Union[int, float] + +# Type alias for spatial vectors that can be input of a public function +# No check for the number of items, because support for this in Python +# typing is bad +VectorLike = Sequence[Number] + +# Type aliases for spatial vectors returned from public functions +VectorNumpy = np.ndarray + +# Type alias for an angle +Angle = Number + +# Type aliases for range of angles +AngleRange = Tuple[Angle, Angle, Angle] + +# Type alias for immutable representation of 2x2 matrix +TupleMatrix2x2 = Tuple[Tuple[Number, Number], Tuple[Number, Number]] + +# Type alias for mutable represenation of 2x2 matrix +ListMatrix2x2 = List[List[Number]] + +# Type alias for Numpy 2x2 array (used internally to represent 2D square matrices) +# note: no support on dimensionality and ndarray dtype typing available yet +Matrix2x2 = np.ndarray + +# Type alias for a description of 2D square matrix that can be entered into +# a public method +InMatrix2x2 = Union[TupleMatrix2x2, Matrix2x2, ListMatrix2x2] + +DEGREE = (2 * np.pi) / 360 + +PERIODIC_TABLE = ( + ""H"", ""He"", ""Li"", ""Be"", ""B"", ""C"", ""N"", ""O"", ""F"", ""Ne"", ""Na"", ""Mg"", ""Al"", + ""Si"", ""P"", ""S"", ""Cl"", ""Ar"", ""K"", ""Ca"", ""Sc"", ""Ti"", ""V"", ""Cr"", ""Mn"", ""Fe"", + ""Co"", ""Ni"", ""Cu"", ""Zn"", ""Ga"", ""Ge"", ""As"", ""Se"", ""Br"", ""Kr"", ""Rb"", ""Sr"", ""Y"", + ""Zr"", ""Nb"", ""Mo"", ""Tc"", ""Ru"", ""Rh"", ""Pd"", ""Ag"", ""Cd"", ""In"", ""Sn"", ""Sb"", + ""Te"", ""I"", ""Xe"", ""Cs"", ""Ba"", ""La"", ""Ce"", ""Pr"", ""Nd"", ""Pm"", ""Sm"", ""Eu"", ""Gd"", + ""Tb"", ""Dy"", ""Ho"", ""Er"", ""Tm"", ""Yb"", ""Lu"", ""Hf"", ""Ta"", ""W"", ""Re"", ""Os"", ""Ir"", + ""Pt"", ""Au"", ""Hg"", ""Tl"", ""Pb"", ""Bi"", ""Po"", ""At"", ""Rn"", ""Fr"", ""Ra"", ""Ac"", + ""Th"", ""Pa"", ""U"", ""Np"", ""Pu"", ""Am"", ""Cm"", ""Bk"", ""Cf"", ""Es"", ""Fm"", ""Md"", ""No"", + ""Lr"", ""Rf"", ""Db"", ""Sg"", ""Bh"", ""Hs"", ""Mt"", ""Ds"", ""Rg"", ""Cn"", ""Nh"", ""Fl"", + ""Mc"", ""Lv"", ""Ts"", ""Og"" +) + +# constants that might be useful +Z_SPIN_UP = (0, 0, 1) +Z_SPIN_DOWN = (0, 0, -1) + + +def element_symbol(atomic_no: int) -> str: + """""" + Returns symbol of a chemical element given its atomic number + + Parameters + ---------- + atomic_no : int + atomic number of an element + + Returns + ------- + str + symbol of that element + + Raises + ------ + IndexError or TypeError + If there is no chemical element with such atomic number + """""" + return PERIODIC_TABLE[atomic_no - 1] + + +def atomic_number(element_symbol: str) -> int: + """""" + Inverse function of `element_symbol` + Parameters + ---------- + element_symbol : str + must be a valid symbol of chemical element, can not be its full name + + Returns + ------- + int + atomic number of the element + + Raises + ------ + ValueError or TypeError + If there is no chemical element with such symbol + """""" + return PERIODIC_TABLE.index(element_symbol) + 1 + + +class Unit(Enum): + """""" + Enumeration representing different ways in which lattice vectors + and atomic positions can be specified + + Attributes + ---------- + Angstrom + angstrom (1e-10 m) + Crystal + representation of vector in the base of elementary cell vectors + of a given lattice + """""" + Angstrom = auto() + Crystal = auto()","Python" +"Substrate","tnecio/supercell-core","supercell_core/__init__.py",".py","633","16",""""""" +Top-level exported functions and classes: + +>>> from .input_parsers import read_POSCAR, parse_POSCAR +>>> from .lattice import Atom, lattice, Lattice +>>> from .heterostructure import heterostructure, Heterostructure +>>> from .physics import VectorNumpy, VectorLike, Unit, DEGREE, PERIODIC_TABLE, \\ +>>> element_symbol, Z_SPIN_DOWN, Z_SPIN_UP +"""""" + +from .input_parsers import read_POSCAR, parse_POSCAR +from .lattice import Atom, lattice, Lattice +from .heterostructure import heterostructure, Heterostructure +from .physics import VectorNumpy, VectorLike, Unit, DEGREE, PERIODIC_TABLE, \ + element_symbol, Z_SPIN_DOWN, Z_SPIN_UP +","Python" +"Substrate","tnecio/supercell-core","supercell_core/lattice.py",".py","19546","581","from typing import List, Optional, Tuple + +from .errors import * +from .calc import * +from .physics import Unit, Number, VectorLike, VectorNumpy, PERIODIC_TABLE, \ + atomic_number +from .atom import Atom + + +# noinspection PyPep8Naming +class Lattice: + """""" + Object representing a 2D crystal lattice (or rather its unit cell) + + Initially set with default values: no atoms, unit cell vectors + equal to unit vectors (of length 1 angstrom each) along x, y, z axes. + + Elementary cell vectors are here and elsewhere referred to as b_1, b_2, b_3. + """""" + # Let's keep atoms in a list not set, because most operations will be done + # probably on all atoms together anyway, except maybe for adding atoms; + # list doesn't really create any significant disadvantages over a set + __atoms: List[Atom] + __XA: np.ndarray + + def __init__(self): + # set initial values of attributes + + # store unit cell vectors as a numpy array, unit: angstrom + # vectors in columns; note: this means that this array is also + # a base change matrix from the lattice vectors basis + # to the x-y-z basis + # default value: identity matrix + self.__XA = np.identity(3) + + # store atoms in one unit cell as a list of values of type Atom + # since what we will be doing with them most is adding and iterating + # (when we build a heterostructure unit cell) + # position unit: Crystal + self.__atoms = [] + + def set_vectors(self, *args: VectorLike, + atoms_behaviour: Optional[Unit] = None) -> ""Lattice"": + """""" + Sets (or changes) lattice vectors to given values + + Parameters + ---------- + args : 2 2D vectors, or 3 3D vectors + Two or three vectors describing unit cell. Since this program + is used to calculate values regarding 2D lattices, it is not + necessary to specify z-component of the vectors. In that case, + the z-component defaults to 0 for the first two vectors + (unless it was set by previous invocation of `set_vectors`; + this issues a warning but works). + All vectors must be the same length. + Unit : angstrom (1e-10 m) + atoms_behaviour : Unit, optional + Described how atomic positions of the atoms already added to + the lattice should behave. They are treated as if they were + specified with the unit `atomic_behaviour`. This argument is + optional if the lattice does not contain any atoms, otherwise + necessary. + + Returns + ------- + Lattice + for chaining + + Raises + ----- + TypeError + If supplied values don't match expected types + LinearDependenceError + If supplied vectors are not linearly independent + UndefinedBehaviourError + If trying to change unit cell vectors of a lattice that + contains atoms, without specifying what to do with the atomic + positions in the unit cell + + Warns + ----- + UserWarning + When unit cell vectors are reset in a way that disregards + previous change of the values of z-component or the third vector + (suggesting that user might not be aware that their values are + not default) + """""" + # First, check if we should warn user about something, and if the data + # are correct + if len(args) < 2 or len(args) > 3: + raise TypeError(""Expected 2 or 3 vectors"") + if len(set(map(len, args))) != 1: + # len(set) tells us about # of unique elements; + # in this case set contains lengths of the supplied vectors + raise TypeError(""Different lengths of supplied vectors"") + for i, v in enumerate(args): + if len(v) < 2 or len(v) > 3: + raise TypeError(""Expected 2D or 3D vectors"") + if len(v) == 2 and self.__XA[2, i] != 0: + warnings.warn(WarningText.ReassigningPartOfVector.value) + if len(v) == 3 and v[2] != 0 and len(args) == 2: + warnings.warn(WarningText.ZComponentWhenNoZVector.value) + if (not isinstance(atoms_behaviour, Unit)) and len(self.__atoms) > 0: + raise UndefinedBehaviourError + + # Then, convert received values into a numpy ndarray and replace + # the relevant parts of self.__XA + old_XA = np.copy(self.__XA) + + new_vectors = np.array(args).T + self.__XA[0:len(args[0]), 0:len(args)] = new_vectors + if np.isclose(np.linalg.det(self.__XA), 0): + bad_XA = self.__XA + self.__XA = old_XA + raise LinearDependenceError(""{}"".format(bad_XA)) + + if atoms_behaviour == Unit.Angstrom: + for i, a in enumerate(self.__atoms): + self.__atoms[i] = Atom(a.element, + self.__to_crystal_base(old_XA @ a.pos), + Unit.Crystal, + spin=a.spin) + + return self + + def rotate(self, theta: float): + """""" + Rotates the lattice around the origin. + + Parameters + ---------- + theta : float + Angle in radians + + Returns + ------- + Lattice + for chaining + """""" + # TODO: tests + vecs = self.vectors() + v1 = vecs[0][0:2] + v2 = vecs[1][0:2] + v1 = rotate(v1, theta) + v2 = rotate(v2, theta) + self.set_vectors(v1, v2, atoms_behaviour=Unit.Crystal) + return self + + def vectors(self) -> List[VectorNumpy]: + """""" + Lists lattice vectors + + Returns + ------- + List[Vec3D] + List of unit cell vectors (in angstrom) + """""" + return self.__XA.T.tolist() + + def basis_change_matrix(self) -> np.ndarray: + """""" + Returns basis change matrix from basis of lattice vectors (Direct) to + Cartesian basis. + + Returns + ------- + np.ndarray, shape (3,3) + """""" + return self.__XA + + def __to_angstrom_base(self, pos: np.ndarray) -> np.ndarray: + """""" + Convert from crystal base to angstrom xyz base + """""" + return self.__XA @ pos + + def __to_crystal_base(self, pos: np.ndarray) -> np.ndarray: + """""" + Convert from angstrom xyz base to crystal base + """""" + return np.linalg.inv(self.__XA) @ pos + + def add_atom(self, + element: str, + pos: VectorLike, + spin: VectorLike = (0, 0, 0), + unit: Unit = Unit.Angstrom, + normalise_positions: bool = False) -> ""Lattice"": + """""" + Adds a single atom to the unit cell of the lattice + + Parameters + ---------- + element : str + Symbol of the chemical element (does NOT accept full names) + If unknown symbol is passed, warns the user and defaults to hydrogen + pos : 2D or 3D vector + Position of the atom in the unit cell. If atomic position is + not within the parallelepiped described by unit cell vectors, + position is accepted but a warning is issued. + spin : 3D vector, optional + Describes spin of the atom (s_x, s_y, s_z), default: (0, 0, 0) + unit : Unit + Gives unit in which `pos` was given (must be either `Unit.Angstrom` + or `Unit.Crystal`) + normalise_positions : bool + If True, atomic positions are moved to be within the elementary cell + (preserving location of atoms in the whole crystal) + Default: False + + Returns + ------- + Lattice + for chaining + + Warns + ----- + UserWarning + If an unknown chemical element symbol is passed as `element` + If the atomic position is outside the elementary cell defined by + lattice vectors, and `normalise_positions` is False + + Raises + ------ + TypeError + If supplied arguments are of incorrect type + """""" + # TODO: replace with Atom class constructor + # check correctness of input data + if element not in PERIODIC_TABLE: + warnings.warn(WarningText.UnknownChemicalElement.value) + + if len(pos) == 2: + pos = [pos[0], pos[1], 0] + elif len(pos) == 3: + pass + else: + raise TypeError(""Bad length of atomic position vector"") + + if len(spin) != 3: + raise TypeError(""Bad length of spin vector. Must be a triple"") + + pos = np.array(pos) + if unit == Unit.Angstrom: + pos = self.__to_crystal_base(pos) + + if (not ((0 <= pos).all() and (pos < 1).all())) \ + and not normalise_positions: + warnings.warn(WarningText.AtomOutsideElementaryCell.value) + + if normalise_positions: + # move all positions to be within the elementary cell + pos %= 1.0 + + self.__atoms.append(Atom(element, pos, Unit.Crystal, spin=spin)) + return self + + def add_atoms(self, atoms: List[Atom]) -> ""Lattice"": + """""" + Adds atoms listed in `atoms` to the unit cell + + Parameters + ---------- + atoms : List[Atom] + List of atoms to add to the lattice unit cell + + Returns + ------- + Lattice + for chaining + """""" + # TODO: use Atom constructor + for atom in atoms: + self.add_atom(atom.element, atom.pos, spin=atom.spin, unit=atom.pos_unit) + return self + + def atoms(self, unit: Unit = Unit.Angstrom) -> List[Atom]: + """""" + Lists atoms in the unit cell + + Parameters + ---------- + unit : Unit + Unit in which to return atomic positions + + Returns + ------- + List[Atom] + List of atoms in an unit cell of the lattice + """""" + if unit == Unit.Crystal: + return self.__atoms + if unit == Unit.Angstrom: + return [atom.basis_change(self.__XA, Unit.Angstrom) + for atom in self.__atoms] + + def save_POSCAR(self, + filename: Optional[str] = None, + silent: bool = False) -> ""Lattice"": + """""" + Saves lattice structure in VASP POSCAR file. + Order of the atomic species is the same as order of their first + occurence in the list generated by `atoms` method of this object. + This order is printed to stdout. + If atoms have non-zero z-spins, the MAGMOM flag is also printed + to stdout. + + Parameters + ---------- + filename : str, optional + if not provided, writes to stdout + silent : bool, default: False + if True, the atomic order and MAGMOM flag are not printed to stdout + + Returns + ------- + Lattice + for chaining + """""" + # TODO: ensure proper chirality + # let's use 1.0 as scaling constant for simplicity + s = ""supercell_generated_POSCAR\n1.0\n"" + + # lattice vectors + lattice_vectors = self.__XA.T.flatten().tolist() + for i, val in enumerate(lattice_vectors): + s += ""{:.5g}"".format(val) + "" "" + if i % 3 == 2: + s = s[:-1] + '\n' + + # counts of each 'atomic species' in one line + atomic_species = {} + names = [] + + for a in self.__atoms: + try: + atomic_species[a.element].append(a) + except KeyError: + atomic_species[a.element] = [a] + names.append(a.element) + + # New in VASP December 2019 – atomic species names + for name in names: + s += ""{} "".format(name) + s = s[:-1] + '\n' + + for name in names: + atoms_list = atomic_species[name] + s += ""{} "".format(len(atoms_list)) + s = s[:-1] + '\n' + + # coordinate system + s += ""Direct\n"" + + # z-spins counting for magmom + # elements of type (z_spin, atoms count) + magmom: List[Tuple[Number, int]] = [] + + # for each atom write down the coordinates in Crystal coordinates + for name in names: + # while we're at it, we can also already sort atomic_species[name] + # by their atoms' z-spin (useful for calculating the MAGMOM flag) + # reverse=True, so spin up (1) is before down (-1), matter of pref. + atomic_species[name].sort(key=self.__z_spin, reverse=True) + + for atom in atomic_species[name]: + try: + if magmom[-1][0] == self.__z_spin(atom): + magmom[-1] = (magmom[-1][0], magmom[-1][1] + 1) + else: + magmom.append((self.__z_spin(atom), 1)) + except IndexError: + # happens for the first atom only + magmom.append((self.__z_spin(atom), 1)) + + # print atom position + s += ""{:.5g} {:.5g} {:.5g}\n"".format(*atom.pos) + + # saving + if filename is not None: + with open(filename, 'w') as f: + f.write(s) + else: + print(s) + + if not silent: + # magmom + magmom_str = "" "".join([((str(x[1]) + ""*"" if x[1] > 1 else """") + + str(x[0])) for x in magmom]) + print(""MAGMOM flag: "" + magmom_str) + + return self + + def save_xsf(self, filename: Optional[str] = None) -> ""Lattice"": + """""" + Saves lattice structure in XCrysDen XSF file + + Parameters + ---------- + filename : str, optional + if not provided, writes to stdout + + Returns + ------- + Lattice + for chaining + """""" + s = ""CRYSTAL\n\nPRIMVEC\n"" + + # lattice vectors + lattice_vectors = self.__XA.T.flatten().tolist() + for i, val in enumerate(lattice_vectors): + s += ""{:.5g}"".format(val) + "" "" + if i % 3 == 2: + s = s[:-1] + '\n' + + s += ""\nPRIMCOORD\n"" + + # number of atoms and '1' + s += ""{} 1\n"".format(len(self.__atoms)) + + # atoms: 'atomic_number pos in angstroms (x y z) spin (x y z) + for atom in self.atoms(unit=Unit.Angstrom): + s += ""{} {:.5g} {:.5g} {:.5g} {} {} {}\n"".format( + atomic_number(atom.element), + *atom.pos, + *atom.spin + ) + + # saving + if filename is not None: + with open(filename, 'w') as f: + f.write(s) + else: + print(s, end='') + + return self + + @staticmethod + def __z_spin(atom: Atom) -> Number: + return atom.spin[2] + + def translate_atoms(self, vec: VectorLike, unit: Unit = Unit.Angstrom): + """""" + Moves all atoms in the unit cell by some vector `vec` + + Parameters + ---------- + vec : VectorLike + Translation vector. If len(vec) == 2, third argument is set to zero. + unit : Unit, optional + Unit of `vec`, by default: angstroms + + Returns + ------- + None + """""" + if len(vec) == 2: + vec = (vec[0], vec[1], 0) + + atoms = self.atoms(unit=unit) + for a in atoms: + a.pos = tuple(np.array(a.pos) + np.array(vec)) + self.__atoms = [] + self.add_atoms(atoms) + + def draw(self, ax=None, cell_coords=None, scatter_kwargs=None, border_kwargs=None): + """""" + Requires matplotlib. Creates an image of the lattice elementary cell + as a matplotlib plot. + + Parameters + ---------- + cell_coords : List[Vector2D], optional + Each point in `cell_coords` is an offset in Lattice vector basis. + For each of those offsets, all atoms in the cell will be drawn with + their positions moved by this offset. Use integer values to get + consistent drawings. Note: You can use things like [(-0.5, -0.5), + (-0.5, 0.5), (0.5, -0.5), (0.5, 0.5)] to get a picture of a translated + elementary cell. + Default: [(0, 0)] (draws just one elementary cell) + ax : matplotlib axes.Axes object, optional + If given, will draw the elementary cell to ax + + Returns + ------- + Figure, Axes + + Notes + ----- + Resulting axes has points labeled; use + `ax.legend(loc='best')` to turn on the legend. + """""" + if cell_coords is None: + cell_coords = [np.array([0, 0])] + else: + cell_coords = [np.array(pt) for pt in cell_coords] + + if ax is None: + import matplotlib.pyplot as plt + plt.clf() + fig, ax = plt.subplots() + else: + fig = ax.figure + + if scatter_kwargs is None: + scatter_kwargs = { + ""marker"": '.', + ""s"": 2 + } + if border_kwargs is None: + border_kwargs = { + ""linestyle"": '--', + ""color"": (55 / 255, 126 / 255, 184 / 255), # orig. ""gray"" + ""linewidth"": 2 + } + + species = set() + for a in self.atoms(): + species.add(a.element) + species = sorted(species, key=atomic_number) + + # A set of nice colours from ColorBrewer2.org + colors = [ + (228 / 255, 26 / 255, 28 / 255), + #(55 / 255, 126 / 255, 184 / 255), + (77 / 255, 175 / 255, 74 / 255), + (152 / 255, 78 / 255, 163 / 255), + (255 / 255, 127 / 255, 0 / 255), + (255 / 255, 255 / 255, 51 / 255), + (166 / 255, 86 / 255, 40 / 255), + (247 / 255, 129 / 255, 191 / 255), + (153 / 255, 153 / 255, 153 / 255) + ] + + # Hack if there is less colors than species + colors = colors * (len(species) // len(colors) + 1) + + for color, specie in zip(colors, species): + atoms = [a for a in self.atoms() if a.element == specie] + positions = [a.pos for a in atoms] + v1, v2 = self.__XA[0:2, 0], self.__XA[0:2, 1] + for cell_coord in cell_coords: + positions_x = [p[0] + v1[0] * cell_coord[0] + v2[0] * cell_coord[1] + for p in positions] + positions_y = [p[1] + v1[1] * cell_coord[0] + v2[1] * cell_coord[1] + for p in positions] + ax.scatter(positions_x, + positions_y, + label=specie, + color=color, + **scatter_kwargs) + + for a, px, py in zip(atoms, positions_x, positions_y): + if a.spin[2] > 0: + ax.annotate('↑', (px, py)) + elif a.spin[2] < 0: + ax.annotate('↓', (px, py)) + + # Draw cell boundary + vecs = np.array([v[0:2] for v in self.vectors()[0:2]]) + pts = np.array([(0, 0), vecs[0], vecs[0] + vecs[1], vecs[1], (0, 0)]).T + + ax.plot(pts[0], pts[1], **border_kwargs) + + ax.set_aspect('equal', adjustable='box') + return fig, ax + + +def lattice(): + """""" + Creates a Lattice object + + Returns + ------- + Lattice + a new Lattice object + """""" + return Lattice() +","Python" +"Substrate","tnecio/supercell-core","supercell_core/input_parsers.py",".py","6488","207","from typing import List, Optional + +from .errors import * +from .physics import Unit +from .lattice import lattice, Lattice +from .heterostructure import Heterostructure + + +def read_POSCAR(filename: str, + **kwargs) -> Lattice: + """""" + Reads VASP input file ""POSCAR"" + + Parameters + ---------- + filename : str + kwargs + Passed on to `parse_POSCAR` + + Returns + ------- + Lattice + object representing the same lattice as the VASP input files + + Raises + ------ + IOError + If something is wrong with I/O on the file + ParseError + If supplied file is not a valid POSCAR, or if the arguments supplied + cannot be reasonably paired with the input file in a way that makes + a proper Lattice + """""" + with open(filename, 'r') as f: + # I don't think there is any reasonable POSCAR with > 1000 atoms + # so s will be at most a few tens of thousands of kB, so just read() it + s = f.read() + return parse_POSCAR(s, **kwargs) + + +# Helper functions for parser to make the code read better + +def eat_line(s: List[str]) -> List[str]: + # Takes a list of lines, returns list without the first one + return s[1:] + + +def get_line(s: List[str]) -> str: + # Returns first line in list + return s[0].strip() + + +def iter_magmom(magmom: str): + # TODO: Type Hint for generator + # Yields values of spin from magmom string + s = [x.strip() for x in magmom.splitlines()][0].split() + try: + for el in s: + y = el.split('*') + if len(y) == 2: + z_spin = int(y[1]) + count = int(y[0]) + for i in range(count): + yield (0, 0, z_spin) + elif len(y) == 1: + yield (0, 0, int(y[0])) + else: + raise ParseError(""Ambiguous spin description using '*'"") + except Exception: + raise ParseError(""Invalid MAGMOM string supplied"") + + +def parse_POSCAR(poscar: str, + atomic_species: List[str] = None, + magmom: Optional[str] = None, + normalise_positions: Optional[bool] = False) -> Lattice: + """""" + Reads lattice data from a string, treating it as VASP POSCAR file + Format documentation: https://cms.mpi.univie.ac.at/wiki/index.php/POSCAR + + Parameters + ---------- + poscar : str + Contents of the POSCAR file + atomic_species : List[str] + Contains symbols of chemical elements in the same order as in POTCAR + One symbol per atomic species + Required if the POSCAR file does not specify the atomic species + magmom : str, optional + Contents of the MAGMOM line from INCAR file. + Default: all spins set to zero + normalise_positions : bool, optional + If True, atomic positions are moved to be within the elementary cell + (preserving location of atoms in the whole crystal) + Default: False + + Returns + ------- + Lattice + object representing the same lattice as the VASP would-be input + + Raises + ------ + IOError + If something is wrong with I/O on the file + ParseError + If supplied file is not a valid POSCAR, or if the arguments supplied + cannot be reasonably paired with the input file in a way that makes + a proper Lattice + """""" + # Build the lattice the usual way + res = lattice() + + try: + s = poscar.splitlines() + + # 1: system name, irrelevant for us + s = eat_line(s) + + # 2: scale factor + scale = float(get_line(s)) + s = eat_line(s) + + # 3, 4, 5: lattice vectors in angstroms + vecs = [] + for i in range(3): + vecs.append([scale * float(x.strip()) for x in get_line(s).split()]) + if len(vecs[-1]) != 3: + raise ParseError(""Vector length different than 3"") + s = eat_line(s) + + res.set_vectors(*vecs) + + # 6 (optional): atomic species names + line = get_line(s).split() + # Heuristic for species names – failure to parse as int + try: + int(line[0]) + except: + if atomic_species is None: + atomic_species = line + line = get_line(s).split() + s = eat_line(s) + + # 7: atomic species counts + if len(line) != len(atomic_species): + raise ParseError(""Number of atomic species doesn't match ({} != {})"".format( + len(get_line(s).split()), len(atomic_species) + )) + + as_counts = [int(x.strip()) for x in get_line(s).split()] + s = eat_line(s) + + # 8: possibly Selective Dynamics, then remember to ignore Ts and Fs + # at the ends of positions + selective_dynamics = False + if get_line(s)[0] in ""Ss"": + s = eat_line(s) + selective_dynamics = True + + # 9: Cartesian or Direct + unit = Unit.Crystal + if get_line(s)[0] in ""CcKk"": + unit = Unit.Angstrom + s = eat_line(s) + + # 10+: atomic positions + if magmom: + spins = iter_magmom(magmom) + else: + # default spin: 0 + spins = iter([(0, 0, 0)] * sum(as_counts)) + + def letter_to_sd_bool(letter: str): + if letter == 'T': + return True + elif letter == 'F': + return False + raise ParseError(""Bad selective dynamics flag"") + + for specie, count in zip(atomic_species, as_counts): + for i in range(count): + splitted = get_line(s).split() + vec = [float(x) for x in splitted[0:3]] + if selective_dynamics: + if len(splitted) != 6: + raise ParseError(""Vector length different than 3, "" + + ""or bad number of selective dynamics "" + + ""flags"") + sd = tuple(map(letter_to_sd_bool, + [x.strip() for x in splitted[3:6]])) + + else: + if len(splitted) != 3: + raise ParseError(""Vector length different than 3"") + res.add_atom(specie, vec, next(spins), unit=unit, + normalise_positions=normalise_positions) + s = eat_line(s) + + except Exception as e: + raise ParseError(str(e)) + return res + + +def read_supercell_in(filename: str) -> Heterostructure: + pass +","Python" +"Substrate","tnecio/supercell-core","supercell_core/heterostructure.py",".py","24270","698","from typing import Optional, List + +from .lattice import Lattice +from .heterostructure_opt import * + + +class Heterostructure: + """""" + Class describing a system of a number of 2D crystals deposited + on a substrate. + + Elementary cell vectors of the substrate are hereafter described as + a_1 through a_3, of the 2D layers above as b_i_1 through b_i_3 (where + i is layer number, counting from the substrate up, starting at 1), + elementary cell of the whole system (where 2D layers have been changed + due to strain) is called heterostructure _supercell_ and its vectors + are referred to as c_1, c_2, and c_3. + + Do not confuse `Heterostructure` with a class representing heterostructure + lattice. `Heterostructure` describes a collection of crystals that build + up the structure; to obtain the crystal lattice resulting from joining + these crystals you must first define a way in which these crystals come + together (angles, etc. – use `opt` or `calc` methods to do this), + and the resulting lattice will be available as `supercell` attribute + of the `Result` class (see documentation of the relevant methods) + """""" + + # Terminology used throughout the implementation: + # + # MN – basis change matrix from N to M + # (the order of the letters makes it easy to combine these: + # MW @ WN == MN for any W) + # v_M – vector v (unit vector of basis V) in basis M + # v_Ms – an array of vectors v in basis M + # stg_lay – list of ""stg"" for each of the layers + # (len(stg_lay) == len(self.layers())) + # + # A, a – basis of lattice vectors of the substrate + # B, b – basis of lattice vectors of a given layer + # Br, br – basis B rotated by theta angle + # Btr, btr – basis of lattice vectors of a given layer when embedded + # in the heterostructure (rotated – r, and stretched + # due to strain – t) + # D, d – basis of vectors composed of integer linear combinations of + # the B basis vectors + # Dt, dt – basis of vectors composed of the integer linear combinations + # of the A basis vectors, represents possible supercell lattice + # vectors + # X, x – cartesian basis (unit vectors: (1 angstrom, 0), + # (0, 1 angstrom)) + # Xt, xt – Transformation corresponding to Br - Btr transformation, but in + # cartesian basis + # + # Note that the vector space of all the mentioned objects is R^2 + + __layers: List[Tuple[Lattice, AngleRange]] + __substrate: Lattice + + def __init__(self): + # We store data on preferred theta (or theta range) as second element + # of the pair, alongside with the Lattice itself + self.__layers = [] + + ### LATTICES METHODS + + def set_substrate(self, substrate: Lattice) -> ""Heterostructure"": + """""" + Defines substrate layer of the heterostructure + + Parameters + ---------- + substrate : Lattice + Lattice object describing elementary cell of the substrate on which + 2D crystals will be laid down + + Returns + ------- + Heterostructure + for chaining + """""" + self.__substrate = substrate + return self + + def substrate(self) -> Lattice: + """""" + Getter for the substrate of the heterostructure + + Returns + ------- + Lattice + + Raises + ------ + AttributeError + if substrate wasn't set yet + """""" + return self.__substrate + + def add_layer(self, + layer: Lattice, + pos: Optional[int] = None, + theta: Union[Angle, AngleRange] = (0, 180 * DEGREE, 0.1 * DEGREE) + ) -> ""Heterostructure"": + """""" + Adds a 2D crystal to the system + + Parameters + ---------- + layer : Lattice + Lattice object describing elementary cell of the crystal to add to + the system + pos : int, optional + Position of the layer in the stack, counting from the substrate up + (first position is 0). If not specified, layer will be added at the + top of the stack + theta : Angle or AngleRange, optional + If specified, supplied value of `theta` will be used in place of + the default values in calculations such as `opt`. + If a single angle is passed then the `theta` angle of that layer + is fixed to that value. If an AngleRange (three floats) is passed + then it is treated as a range of possible values for the `theta` + value (start, stop, step). + Unit: radians + Default: (0, pi, 0.1 * DEGREE) + + Returns + ------- + Heterostructure + for chaining + """""" + try: + # if theta is an Angle `float` will work + theta = (float(theta), float(theta), 1.0) + except TypeError: + assert len(theta) == 3 + + if pos is None: + self.__layers.append((layer, theta)) + else: + self.__layers.insert(pos, (layer, theta)) + + return self + + def add_layers(self, layers: List[Union[Lattice, + Tuple[Lattice, + Union[Angle, AngleRange]]]]) \ + -> ""Heterostructure"": + """""" + Adds a lot of layers to the heterostructure at once + + Parameters + ---------- + layers : List[ \ + Lattice,res.set_vectors() \ + or (Lattice, float), \ + or (Lattice, (float, float, float)) \ + ] + List of layers to add to the structure. + If list element is a tuple, the second element serves the same way + as `theta` parameter in `add_layer` + + Returns + ------- + Heterostructure + for chaining + """""" + for el in layers: + # if el is a Lattice + if type(el) is Lattice: + self.add_layer(el) + # if el is (Lattice, Angle) or (Lattice, AngleRange) + else: + self.add_layer(el[0], theta=el[1]) + + return self + + def layers(self) -> List[Lattice]: + """""" + Returns layers in the heterostructure + + Returns + ------- + List[Lattice] + List of layers on the substrate as Lattice objects + """""" + return [el[0] for el in self.__layers] + + def remove_layer(self, pos: int) -> ""Heterostructure"": + """""" + Removes layer in position `pos` + + Parameters + ---------- + pos : int + Position of the layer in the stack, counting from the substrate up + (first position is 0). + + Returns + ------- + Heterostructure + + Raises + ------ + IndexError + If there's less layers in the stack than `pos` + """""" + self.__layers.pop(pos) + return self + + def get_layer(self, pos: int) -> Tuple[Lattice, AngleRange]: + """""" + Get Lattice object describing layer at position `pos` and information + on preferred theta angles for that layer + + Parameters + ---------- + pos : int + Position of the layer in the stack, counting from the substrate up + (first position is 0). + + Returns + ------- + Lattice + Lattice object describing the layer + (float, float, float) + (start, stop, step) (radians) – angles used in `calc` and `opt` + If a specific angle is set, returned tuple is (angle, angle, 1.0) + + Raises + ------ + IndexError + If there's less layers in the stack than `pos` + """""" + return self.__layers[pos] + + ### STRAIN TENSOR DEFINITION + + @staticmethod + def __calc_strain_tensor(XBr: Matrix2x2, XXt: Matrix2x2) -> Matrix2x2: + """""" + Calculate strain tensor. + + See docs of `Heterostructure.calc` for definition of strain tensor. + + Parameters + ---------- + XBr : Matrix 2x2 + XXt : Matrix 2x2 + + Returns + ------- + Matrix 2x2 + """""" + BrX = inv(XBr) + BrBtr = BrX @ XXt @ XBr + return inv(BrBtr) - np.identity(2) + + ### CALC METHODS + + def __calc_strain_tensor_from_ADt(self, ADt: Matrix2x2, XBr: Matrix2x2) -> Matrix2x2: + """""" + Calculate strain tensor. + + See docs of `Heterostructure.calc` for definition of strain tensor. + + Parameters + ---------- + ADt : Matrix 2x2 + XBr : Matrix 2x2 + + Returns + ------- + Matrix 2x2 + """""" + BrDt, BtrBr, XXt = self.__get_basis_change_matrices(ADt, XBr) + return Heterostructure.__calc_strain_tensor(XBr, XXt) + + def calc(self, + M=((1, 0), (0, 1)), + thetas=None, + calc_atoms=True) -> Result: + """""" + Calculates strain tensor and other properties of the system in given + circumstances + + !! See Notes for the definition of strain tensor used here. + + Parameters + ---------- + M : 2x2 matrix + Base change matrix from the base of the supercell lattice + elementary cell vectors to the base of the substrate elementary cell + vectors ( -> ), or, in other words, + c_1 = M_11 * a_1 + M_21 * a_2, and c_2 = M_12 * a_1 + M_22 * a_2. + thetas : List[Angle|None], optional + Required if `theta` parameter is not fixed for all the layers + in the system. + If specified, it will be zipped with the layers list (starting from + the layer closest to the substrate), and then, if the value + corresponding to a layer is not None then that layer's `theta` + angle will be set to that value. + Example: + >>> from supercell_core import * + >>> h = heterostructure() + >>> h.set_substrate(lattice()) + >>> lay1, lay2, lay3 = lattice(), lattice(), lattice() + >>> h.add_layers([(lay1, 180 * DEGREE), lay2, lay3]) + >>> h.calc(M=((1, 2), (3, 4)), \ + thetas = [None, 45 * DEGREE, 90 * DEGREE) \ + # will be set to (180, 45, 90) degrees for layers \ + # (lay1, lay2, lay3) repsectively + + Returns + ------- + Result + Result object containing the results of the calculation. + For more information see documentation of `Result` + + Notes + ----- + Let ei be strain tensor of layer i. Let ai_1 and ai_2 be lattice vectors + of layer i when not under strain. Then: + :math:`\sum_{k=1}^2 (ei + I)_j^k ai_k = a'i_j`, where + a'i_j is j-th lattice vector of a when embedded in the heterostructure. + + This definition is different than the one given in [1]. + To calculate strain tensor as defined in [1], use + `wiki_definition=True` in relevant `Result` methods. + + References + ---------- + [1] https://en.wikipedia.org/wiki/Infinitesimal_strain_theory + + """""" + if thetas is not None: + thetas = [arg if arg is not None else lay_desc[1][0] + for arg, lay_desc in zip(thetas, self.__layers)] + else: + thetas = [lay_desc[1][0] for lay_desc in self.__layers] + + ADt = np.array(M) + return self.__calc_aux(ADt, thetas, calc_atoms=calc_atoms) + + def __get_basis_change_matrices(self, ADt, XBr): + """""" + Helper function to retrieve BrDt, BtrBr, XXt matrices + + Parameters + ---------- + ADt : Matrix 2x2 + XBr : Matrix 2x2 + + Returns + ------- + BrDt : Matrix 2x2 + BtrDt : Matrix 2x2 + XXt : Matrix 2x2 + """""" + XA = self.__substrate.basis_change_matrix()[0:2, 0:2] + BrDt = inv(XBr) @ XA @ ADt + BtrBr = Heterostructure.__get_BtrBr(BrDt) + XXt = XBr @ inv(BtrBr) @ inv(XBr) + return BrDt, BtrBr, XXt + + def __calc_aux(self, + ADt: InMatrix2x2, + thetas: List[Angle], + calc_atoms: bool) -> Result: + """""" + Calculates strain tensor and other properties of the system in given + circumstances + + Parameters + ---------- + ADt : Matrix2x2 + AC matrix + thetas : List[float] + List of theta angles of the layers (length must be equal to length + of self.__layers) + + Returns + ------- + Result + see `Result` documentation for details + """""" + XA = self.__substrate.basis_change_matrix()[0:2, 0:2] + XBrs = [rotate(lay_desc[0].basis_change_matrix()[0:2, 0:2], theta) + for theta, lay_desc in zip(thetas, self.__layers)] + strain_tensors = [self.__calc_strain_tensor_from_ADt(ADt, XBr) + for XBr in XBrs] + BrDts = [] + BtrBrs = [] + XXts = [] + for XBr in XBrs: + BrDt, BtrBr, XXt = self.__get_basis_change_matrices(ADt, XBr) + BrDts.append(BrDt) + BtrBrs.append(BtrBr) + XXts.append(XXt) + + ABtrs = [inv(XA) @ XBr @ inv(BtrBr) for XBr, BtrBr in zip(XBrs, BtrBrs)] + + # also add the alternative strain tensor definition to the Result + strain_tensors_wiki = [Heterostructure.__get_strain_tensor_wiki(XXt) + for XXt in XXts] + + superlattice = self.__build_superlattice(XA @ ADt, ADt, BrDts, calc_atoms) + + A_atoms_per_el_cell = len(self.__substrate.atoms()) + atom_count = np.abs(np.linalg.det(ADt) * A_atoms_per_el_cell) + for layer, BrDt in zip(self.__layers, BrDts): + B_atoms_per_el_cell = len(layer[0].atoms()) + atom_count += np.round(np.abs(np.linalg.det(BrDt) * B_atoms_per_el_cell)) + + return Result( + self, + superlattice, + thetas, + strain_tensors, + strain_tensors_wiki, + ADt, + ABtrs, + atom_count=atom_count + ) + + @staticmethod + def __get_strain_tensor_wiki(XXt: Matrix2x2) -> np.ndarray: + """""" + Calculates strain tensor as defined in [1]. + + Parameters + ---------- + XXt : Matrix2x2 + + Returns + ------- + Matrix 2x2 + + References + ---------- + [1] https://en.wikipedia.org/wiki/Infinitesimal_strain_theory#Infinitesimal_strain_tensor + """""" + # Notice that XXt = deformation gradient tensor (F) + # [1] + # https://en.wikipedia.org/wiki/Finite_strain_theory#Deformation_gradient_tensor + F = np.array(XXt) + + # replace F with strain tensor + F += F.swapaxes(-1, -2) # F + F^T + F /= 2 + F -= np.identity(2) + return F + + def __build_superlattice(self, XDt: Matrix2x2, ADt: Matrix2x2, + BrDts: List[Matrix2x2], calc_atoms=True) -> Lattice: + """""" + Creates Lattice object describing superlattice (supercell) + of the heterostructure + + Parameters + ---------- + XDt : Matrix2x2 + ADt : Matrix2x2 + BrDts : List[Matrix2x2] + + Returns + ------- + Lattice + """""" + res = Lattice() + # We also need to include substrate here + lattices = [self.__substrate] + [lay_desc[0] for lay_desc in self.__layers] + MDts = [ADt] + BrDts + + # lattice vectors + full_XDt = np.zeros((3, 3)) + full_XDt[0:2, 0:2] = XDt + full_XDt[0:3, 2] = sum([lay.basis_change_matrix()[2, 0:3] for lay in lattices]) + res.set_vectors(*full_XDt.T.tolist()) + + # atoms + if calc_atoms: + for i, lay, MDt in zip(range(len(lattices)), lattices, MDts): + # We stack the layers one above the other so atoms must be moved up + # by the sum of z-sizes of all elementary cells of layers below + z_offset = self.__get_z_offset(i) + z_offset /= full_XDt[2, 2] # angstrom -> Direct coordinates + Heterostructure.__superlattice_add_atoms(res, lay, MDt, z_offset) + + return res + + @staticmethod + def __superlattice_add_atoms(superlattice, lay, MDt, z_offset): + """""" + Adds atoma from a given heterostructure-embedded lattice to the super- + lattice. To do this, atomic positions must be transformed to occupy + the same positions in the ""stretched"" elementary cell; and atoms + themselves must be copied a few times because one superlattice cell is + composed of a few layer cells. + + Parameters + ---------- + superlattice : Lattice + Superlattice to modify + lay : Lattice + Layer of the heterostr.; Source of the atoms to add to superlattice + MDt : Matrix 2x2 + z_offset : float + Describes how much above 0 in the supercell should be the layer + `lay`. This value will be added to z-component of all atomic + positions of atoms from this layer. (Unit: angstroms) + + Returns + ------- + None + """""" + # Safe upper bound on the size of the supercell in any direction + cell_upper_bound = 2 * int(round(np.max(np.abs(MDt))) + 1) + + atoms = lay.atoms(unit=Unit.Crystal) + atomic_pos_Dt_basis = [inv(MDt) @ atom.pos[0:2] for atom in atoms] + + # vecs = 2x2 columns of DtBrt + DtBrt = inv(MDt) @ inv(Heterostructure.__get_BtrBr(MDt)) + vecs = DtBrt.T[0:2, 0:2] + + # We will copy atoms many times, each time translated by some integer + # linear combination of layer vecs, and those atoms that will be inside + # the supercell will be kept + # Those integer linear combinations are called here 'nodes' + get_node = lambda j, k: j * vecs[0] + k * vecs[1] + # 10 is arbtrary; hopefully it's enough + epsilon = 10 * np.finfo(np.dtype('float64')).eps + nodes = [get_node(j, k) + for j in range(-cell_upper_bound, cell_upper_bound + 1) + for k in range(-cell_upper_bound, cell_upper_bound + 1) + if 0 <= get_node(j + 0.1, k + 0.1)[0] < 1 - epsilon + and 0 <= get_node(j + 0.1, k + 0.1)[1] < 1 - epsilon] + + for pos, a in zip(atomic_pos_Dt_basis, atoms): + for node in nodes: + superlattice.add_atom(a.element, + (pos[0] + node[0], + pos[1] + node[1], + a.pos[2] + z_offset), + spin=a.spin, + unit=Unit.Crystal, + normalise_positions=True) + + def __get_z_offset(self, pos: int) -> float: + """""" + Return sum of z-sizes of lattices below specified position (in angstrom) + for `Heterostructure.__build_superlattice` + + Parameters + ---------- + pos : int + Position of the layer in the stack (lowest is 1) + + Returns + ------- + float + z-offset in Angstrom + """""" + offset = 0 + # We need to include substrate since we are also adding atoms from it + # ld == LayerDescription (Lattice, thetas) + lays = [self.__substrate] + [ld[0] for ld in self.__layers] + for lay in lays[:pos]: + offset += lay.vectors()[2][2] + return offset + + @staticmethod + def __get_BtrBr(BrDt): + """""" + BrDt -> BtrBr + """""" + # see why round in implementation of `Heterostructue.__get_d_xs` + BtrDt = np.round(BrDt) + return BtrDt @ inv(BrDt) + + ### OPT METHODS + + def opt(self, + max_el: int = 6, + thetas: Optional[List[Optional[List[float]]]] = None, + algorithm: str = ""fast"", + log: bool = False + ) -> Result: + """""" + Minimises strain, and calculates its value. + Note: definition of strain tensor used here is the same as in + documentation of `Heterostructure.calc` + + Parameters + ---------- + max_el : int, optional + Defines maximum absolute value of the strain tensor element + The opt calculation is O(`max_el`^2). + Default: 6 + + thetas : List[List[float]|None] | List[float], optional + Allows to override thetas specified for the layers. + If specified, it must be equal in length to the number of layers. + For a given layer, the list represents values of theta to check. + If None is is passed instead of one of the inner lists, then default + is not overriden. + If there are only two layers, the argument can be passed just as a list + of floats, without the need for nesting. + All angles are in radians. + + algorithm : str, optional + Default: ""fast"" + Accepted values: ""fast"", ""direct"" + + log : bool, optional + Default: False + If True, the Result will contain pandas.DataFrame in `log` attribute + The resulting DataFrame will contain information on supercell for every + combination of interlayer angles considered. + Requires `pandas` extra dependency + + Returns + ------- + Result + Result object containing the results of the optimisation. + For more information see documentation of `Result` + """""" + + # Prepare ranges of theta values + def is_iterable(x): + try: + iter(x) + return True + except Exception: + return False + + if thetas is not None: + if is_iterable(thetas[0]) and len(thetas) == len(self.__layers): + thetas_in = thetas + elif len(self.__layers) == 1: + thetas_in = [thetas] + else: + raise TypeError(""""""Bad argument thetas. If specified, it should be a list of iterables each corresponding to a layer, e.g. +for heterostructure with 2 layers valid arg might be: thetas=[np.arange(0, np.pi, np.pi/16), np.arange(0, 180 * sc.DEGREE, 1 * sc.DEGREE)] + -- the first np.arange specifies the range of angles to check for the first layer, second is for the second layer etc. +If, and only if, there is only one layer in the heterostructure, you don't need to wrap the range in a list, e.g. +thetas=np.arange(0, 180 * sc.DEGREE, 1 * sc.DEGREE) +"""""") + else: + thetas_in = [np.arange(*lay_desc[1]) for lay_desc in self.__layers] + + # Using (1, 1) norm since we are usually interested in minimising + # |strain_ij| over i, j (where 'strain' is strain tensor) + + config = OptSolverConfig() + config.max_el = max_el + config.ord = (1, 1) + config.log = log + + XA, XBs = self.__get_lattice_matrices() + if algorithm == ""fast"": + thetas, ADt, additional = MoireFinder(XA, XBs, thetas_in, config).solve() + else: # ""direct"" + thetas, ADt, additional = StrainOptimisator(XA, XBs, thetas_in, config).solve() + + res = self.calc(ADt, thetas) + if log: + res.log = additional[""log""] + return res + + def __get_lattice_matrices(self): + """""" + Calculates basis change vectors between Cartesian basis and + basis of lattice vectors of lattices in the Heterostructure + + Returns + ------- + XA : Matrix2x2 + XBs : List[Matrix2x2] + Length of list is equal to the number of layers + """""" + XA = np.transpose(np.array(self.substrate().vectors())[0:2, 0:2]) + XBs = [np.transpose(np.array(lay_desc[0].vectors())[0:2, 0:2]) + for lay_desc in self.__layers] + return XA, XBs + + +def heterostructure() -> Heterostructure: + """""" + Creates a Heterostructure object + + Returns + ------- + Heterostructure + a new Heterostructure object + """""" + return Heterostructure() +","Python" +"Substrate","tnecio/supercell-core","supercell_core/atom.py",".py","4623","133","from typing import Tuple, Optional + +import numpy as np + +from .physics import VectorLike, Unit, Matrix2x2 + + +class Atom: + """""" + Class representing an atom in a crystal lattice. + This is a container class, and doesn't implement any methods except for + basis change. + Access its properties directly. + + Properties + ---------- + element : string + Symbol of the chemical element + pos : (float, float, float) + Position in a cell + pos_unit : Unit + Unit of `pos` vector (Crystal or Angstrom) + velocity : (float, float, float), optional + Velocity in angstrom/fs. When read from / written to VASP POSCAR file + this is the atoms' intitial velocity + spin: (int, int, int) + Magnetic moment of the atom. Usually you are interested in the + z-component, i.e. spins are of the form (0, 0, int). + Default: (0, 0, 0) + selective_dynamics: (bool, bool, bool) + Specifies whether the respective coordinates of the atom were / will be + allowed to change during the ionic relaxation in VASP calculations + """""" + element: str + pos: VectorLike + pos_unit: Unit + velocity: Optional[VectorLike] + spin: VectorLike + selective_dynamics: Tuple[bool, bool, bool] + + def __init__(self, + element: str, + pos: VectorLike, + pos_unit: Unit = Unit.Angstrom, + velocity: VectorLike = None, + spin: VectorLike = (0, 0, 0), + selective_dynamics=(True, True, True)): + """""" + Constructor of the Atom class. + + Parameters + ---------- + element : string + Symbol of the chemical element + pos : (float, float, float) + Position in a cell + pos_unit : Unit, optional + Unit of `pos` vector (Crystal or Angstrom) + Default: Unit.Angstrom + velocity : (float, float, float), optional + Velocity in angstrom/fs. When read from / written to VASP POSCAR + file this is the atoms' intitial velocity + Default: None + spin: (int, int, int), optional + Magnetic moment of the atom. Usually you are interested in the + z-component, i.e. spins are of the form (0, 0, int). + Default: (0, 0, 0) + selective_dynamics: (bool, bool, bool) + Specifies whether the respective coordinates of the atom were / + will be allowed to change during the ionic relaxation in VASP + calculations + Default: (True, True, True) + """""" + self.element = element + self.pos = pos if len(pos) == 3 else (pos[0], pos[1], 0) + self.pos_unit = pos_unit + self.velocity = velocity + self.spin = spin + self.selective_dynamics = selective_dynamics + + def __eq__(self, other: ""Atom"") -> bool: + return self.element == other.element \ + and np.allclose(self.pos, other.pos) \ + and self.pos_unit == other.pos_unit \ + and (self.velocity == other.velocity + or np.allclose(self.velocity, other.velocity)) \ + and np.allclose(self.spin, other.spin) \ + and np.allclose(self.selective_dynamics, other.selective_dynamics) + + def __str__(self): + sd = "" "".join([""T"" if x else ""F"" for x in self.selective_dynamics]) + + return self.element + "" at: "" + str(self.pos) + "" ("" \ + + (""A"" if self.pos_unit == Unit.Angstrom else ""crystal coord."") + "")"" \ + + (f"" (velocity: {self.velocity})"" if self.velocity is not None else """") \ + + (f"" (spin: {self.spin})"" if np.any([x != 0 for x in self.spin]) else """") \ + + ("" "" + sd if sd != ""T T T"" else """") + + def __repr__(self): + return str(self) + + def basis_change(self, + M: Matrix2x2, + new_unit: Unit) -> ""Atom"": + """""" + Creates new atom with values in different basis. + Note: currently, this has no effect on the value of spin parameter! + + Parameters + ---------- + M : Matrix2x2 + basis change matrix + new_unit : Unit + unit of `pos` of the new atom + + Returns + ------- + Atom + """""" + new_pos = M @ np.array(self.pos) + + if self.velocity is not None: + new_velocity = M @ np.array(self.velocity) + else: + new_velocity = None + + return Atom(self.element, + new_pos, + new_unit, + velocity=new_velocity, + spin=self.spin + ) +","Python" +"Substrate","tnecio/supercell-core","supercell_core/tests/test_errors.py",".py","139","11","import unittest as ut + +import supercell_core as sc + +from ..errors import * + + +class TestErrors(ut.TestCase): + # nothing to test + pass +","Python" +"Substrate","tnecio/supercell-core","supercell_core/tests/test_physics.py",".py","690","23","import unittest as ut + +import supercell_core as sc + +from ..errors import * +from ..physics import * + +class TestPhysics(ut.TestCase): + def test_element_symbol(self): + self.assertEqual(sc.element_symbol(1), ""H"") + self.assertEqual(sc.element_symbol(8), ""O"") + with self.assertRaises(IndexError): + sc.element_symbol(0) + sc.element_symbol(200) + with self.assertRaises(TypeError): + sc.element_symbol(""Helium"") + + def test_atomic_number(self): + self.assertEqual(atomic_number(""Fe""), 26) + with self.assertRaises(ValueError): + atomic_number(""Zinc"") + atomic_number(""E"") + atomic_number(""1"")","Python" +"Substrate","tnecio/supercell-core","supercell_core/tests/__init__.py",".py","0","0","","Python" +"Substrate","tnecio/supercell-core","supercell_core/tests/test_input_parsers.py",".py","2867","102","import unittest as ut + +import supercell_core as sc +import os + +from ..errors import * +from ..input_parsers import * + + +class TestInputParsers(ut.TestCase): + def test_read_POSCAR_IO_fail(self): + with self.assertRaises(IOError): + sc.read_POSCAR(""csnadkjndksca"") + + def test_parse_POSCAR_1(self): + example_poscar = """"""whatever +1.0 +1 2 3 +0.5 0.7 0.91 +3 1 0 +1 3 +Direct +-21.84 72 -4.72 +17.38 -54 3.54 +2.66 -8 0.48 +0 0 0"""""" + + lay = sc.parse_POSCAR(example_poscar, [""Fe"", ""Zn""], magmom=""2*-1 1 1*0"") + # a hack around np.ndarray's lack of test-friendly __eq__ + self.assertEqual([lay.vectors()[j][i] for j in range(3) for i in range(3)], + [1, 2, 3, 0.5, 0.7, 0.91, 3, 1, 0]) + + atoms = [ + sc.Atom(""Fe"", (0, 2, 0), spin=(0, 0, -1)), + sc.Atom(""Zn"", (1, 0.5, 3), spin=(0, 0, -1)), + sc.Atom(""Zn"", (0.1, 0.2, 0.7), spin=(0, 0, 1)), + sc.Atom(""Zn"", (0, 0, 0), spin=(0, 0, 0)) + ] + + for a1, a2 in zip(atoms, lay.atoms()): + self.assertEqual(a1, a2) + + self.assertEqual(len(lay.atoms()), 4) + + def test_parse_POSCAR_2(self): + # This time with specie names, selective dynamics and initial velocities + example_poscar = """"""whatever +1.0 +1 2 3 +0.5 0.7 0.91 +3 1 0 +1 3 +Selective dynamics +d +-21.84 72 -4.72 T T F +17.38 -54 3.54 F T F +2.66 -8 0.48 F F T +0 0 0 F F F + +0 0 0 +1 2 3 +1.00000 2.000000 3.000000 +3.0 1 0.000"""""" + + lay = sc.parse_POSCAR(example_poscar, [""Fe"", ""Zn""], magmom=""2*-1 1 1*0"") + # a hack around np.ndarray's lack of test-friendly __eq__ + self.assertEqual([lay.vectors()[j][i] for j in range(3) for i in range(3)], + [1, 2, 3, 0.5, 0.7, 0.91, 3, 1, 0]) + + atoms = [ + sc.Atom(""Fe"", (0, 2, 0), spin=(0, 0, -1)), + sc.Atom(""Zn"", (1, 0.5, 3), spin=(0, 0, -1)), + sc.Atom(""Zn"", (0.1, 0.2, 0.7), spin=(0, 0, 1)), + sc.Atom(""Zn"", (0, 0, 0), spin=(0, 0, 0)) + ] + + for a1, a2 in zip(atoms, lay.atoms()): + self.assertEqual(a1, a2) + + self.assertEqual(len(lay.atoms()), 4) + + def test_read_POSCAR_2(self): + example_poscar = """""" Si + 1.00000000000000 + 5.4365330000000000 0.0000000000000000 0.0000000000000000 + 0.0000000000000000 5.4365330000000000 0.0000000000000000 + 0.0000000000000000 0.0000000000000000 5.4365330000000000 + 1 +Cartesian + 0.8750000000000000 0.8750000000000000 0.8750000000000000"""""" + + lay = sc.parse_POSCAR(example_poscar, [""Si""]) + self.assertEqual(lay.atoms()[0], sc.Atom(""Si"", (0.875, 0.875, 0.875))) + self.assertEqual(len(lay.atoms()), 1) + + # TODO: test bad POSCARs + # TODO: test magmoms + # TODO: test correct IO + + def test_supercell_in(self): + pass +","Python" +"Substrate","tnecio/supercell-core","supercell_core/tests/test_lattice.py",".py","12817","352","import os +import numpy as np +import unittest as ut + +from io import StringIO +from unittest.mock import patch + +import supercell_core as sc + +from ..errors import * + + +class TestLattice(ut.TestCase): + """""" + Test Lattice object + """""" + + def test_vectors_good(self) -> None: + """""" + Tests methods: set_vectors, and vectors + (cases where it succeeds) + """""" + lay = sc.lattice() + + # Testing default values + self.assertEqual(lay.vectors(), [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + + # Setting two 2D elementary cell vectors, omitting z axis as irrelevant + lay.set_vectors([2, 3], [1, 4]) + self.assertEqual(lay.vectors(), [[2, 3, 0], [1, 4, 0], [0, 0, 1]]) + + # Set two 3D elementary cell vectors while omitting the 3rd one is + # nonsensical, unless you give '0' as z-component of these vectors + lay.set_vectors([2, 3, 0], [1, 5, 0]) + self.assertEqual(lay.vectors(), [[2, 3, 0], [1, 5, 0], [0, 0, 1]]) + + # When z-component is non '0' but the 3rd vector is left default, + # (which means it's unclear whether 'z' direction is important for + # the user) a warning should be issued + with self.assertWarns(UserWarning, msg=WarningText.ZComponentWhenNoZVector): + lay.set_vectors([2, 3, 0], [1, 5, 0.2]) + self.assertEqual(lay.vectors(), [[2, 3, 0], [1, 5, 0.2], [0, 0, 1]]) + + # Set three 3D vectors + lay.set_vectors([2, 3, 0], [1, 6, 1], [7, 8, 9]) + self.assertEqual(lay.vectors(), [[2, 3, 0], [1, 6, 1], [7, 8, 9]]) + + # Change only part of the vector – are you sure z-component is what you + # think it is? + lay = sc.lattice() + lay.set_vectors([1, 0, 1], [0, 1, 1], [0, 0, 1]) + with self.assertWarns(UserWarning, msg=WarningText.ReassigningPartOfVector): + lay.set_vectors([2, 0], [0, 3]) + + def test_vectors_bad(self) -> None: + """""" + Tests methods: set_vectors, and vectors + (cases where they should fail) + """""" + lay = sc.lattice() + + # Test bad type of values passed to the function + with self.assertRaises(TypeError): + # Too few arguments – less than two + lay.set_vectors([1, 2]) + + # Too many arguments – more than three + lay.set_vectors([1, 2, 0], [3, 4, 0], [5, 6, 7], [8, 9, 0]) + + # Too short vectors + lay.set_vectors([1], [5]) + + # Too long vectors + lay.set_vectors([1, 2, 3, 4], [5, 6, 7, 8]) + + # Mismatched vectors length + lay.set_vectors([1, 2], [1, 2, 3]) + + # Wrong type + lay.set_vectors([1, 2, 3], [""5"", ""6"", ""7""]) + + # Any arguments passed to vectors + lay.vectors(""whatever"") + + # Test incorrect data passed to function + with self.assertRaises(LinearDependenceError): + # Two linearly dependent vectors + lay.set_vectors([1, 2], [2, 4]) + + # One vector is linear combination of the second and the default + # third vector ([0, 0, 1]) + lay.set_vectors([0, 1, 1], [0, 1, 0]) + + def test_add_atoms_good(self) -> None: + """""" + Tests methods: add_atom, add_atoms, and atoms + """""" + lay = sc.lattice() + + # Test default (no atoms in an elementary cell) + self.assertEqual(lay.atoms(), []) + + # Test add_atom Helium (default unit: angstrom) + he = sc.Atom(""He"", (0.1, 0.2, 0.3)) + lay.add_atom(he.element, he.pos) + self.assertEqual(lay.atoms()[0], he) + + # Test add_atoms: Hydrogen and Lithium + # Retaining element order is expected + h, li = sc.Atom(""H"", np.array([0, 0, 0])), \ + sc.Atom(""Li"", np.array([0.9, 0.9, 0.9]), spin=(0, 1, 2)) + lay.add_atoms([h, li]) + for a1, a2 in zip(lay.atoms(), [he, h, li]): + self.assertEqual(a1, a2) + + # Add atom using 2D position vector + be = sc.Atom(""Be"", (0.5, 0.5), spin=(0, 0, 1)) + lay.add_atoms([be]) + self.assertEqual(lay.atoms()[-1], + sc.Atom(""Be"", np.array([0.5, 0.5, 0]), spin=(0, 0, 1))) + + # When atom is outside the elementary cell, a warning should be logged + with self.assertWarns(UserWarning, msg=WarningText.AtomOutsideElementaryCell): + lay.add_atom(""C"", (2, 0, 0)) + + # Element symbol not in the periodic table + with self.assertWarns(UserWarning, msg=WarningText.UnknownChemicalElement): + lay.add_atom(""Helium"", (1, 0, 0)) # should be: ""He"" + + # Add atom using crystal units + lay = sc.lattice() + lay.set_vectors([2, 0, 0], [2, 2, 0], [0, 0, 3]) + lay.add_atom(""Na"", (0.5, 0.5, 0.5), unit=sc.Unit.Crystal) + self.assertEqual(lay.atoms()[0], sc.Atom(""Na"", (2, 1, 1.5))) + + # Change lattice vectors after adding atoms + lay.set_vectors([4, 0, 0], [4, 4, 0], [0, 0, 6], + atoms_behaviour=sc.Unit.Crystal) + self.assertEqual(lay.atoms()[0], sc.Atom(""Na"", (4, 2, 3))) + + lay.set_vectors([8, 0, 0], [8, 8, 0], [0, 0, 12], + atoms_behaviour=sc.Unit.Angstrom) + self.assertEqual(lay.atoms()[0], sc.Atom(""Na"", (4, 2, 3))) + + # List atoms using CRYSTAL units + lay = sc.lattice() + lay.set_vectors([2, 0, 0], [2, 2, 0], [0, 0, 3]) + lay.add_atom(""Na"", (0.5, 0.5, 0.5), unit=sc.Unit.Crystal) + self.assertEqual(lay.atoms()[0], sc.Atom(""Na"", (2, 1, 1.5))) + self.assertEqual(lay.atoms(unit=sc.Unit.Crystal)[0], + sc.Atom(""Na"", (0.5, 0.5, 0.5), + pos_unit=sc.Unit.Crystal)) + + def test_add_atoms_bad(self) -> None: + """""" + Tests methods: add_atom, and add_atoms, where they should fail + """""" + lay = sc.lattice() + + # Adding atoms before changing elementary cell vectors: + # (we don't know what to do with the atomic positions, + # so we refuse the temptation to guess and raise an error) + # Note: set_vectors should have a behaviour flag allowing + # specifying what to do with the atomic positions + lay.add_atom(""Na"", (0.5, 0.5, 0.5), unit=sc.Unit.Crystal) + with self.assertRaises(UndefinedBehaviourError): + lay.set_vectors([4, 0, 0], [4, 4, 0], [0, 0, 6]) + + # Test bad type of values passed to function + with self.assertRaises(TypeError): + # Bad length of atomic position vector + lay.add_atom(""O"", 0) + lay.add_atom(""O"", (1, 2, 3, 4)) + + # Bad number of arguments to add atom + lay.add_atom(""N"") + lay.add_atom(""N"", 0, 0) + + # Non-atom passed to add_atoms + lay.add_atoms([""whatever""]) + + # Non-unit passed as unit + lay.add_atom(""N"", (0, 0), unit=""meter"") + + def test_save_POSCAR(self): + os.system(""mkdir -p tmp"") + fn = ""tmp/test_POSCAR"" + lay = sc.lattice() + lay.set_vectors([1, 2, 3], [0.5, 0.7, 0.91], [3, 1, 0]) + lay.add_atoms([ + sc.Atom(""Fe"", (0, 2)), + sc.Atom(""Zn"", (1, 0.5, 3), spin=(0, 1, -1)), + sc.Atom(""Zn"", (0.1, 0.2, 0.7)), + sc.Atom(""Zn"", (0, 0, 0)) + ]) + lay.add_atoms([ + sc.Atom(""Zn"", (0.1, 0, 0), pos_unit=sc.Unit.Crystal, spin=(0, 0, 1)), + sc.Atom(""Zn"", (0.2, 0, 0), pos_unit=sc.Unit.Crystal, spin=(0, 0, -1)), + sc.Atom(""Zn"", (0.3, 0, 0), pos_unit=sc.Unit.Crystal, spin=(0, 0, 1)) + ]) + + # first goes Fe (-21.84...) + # then Zn, starting with z-spin=1 and in order of adding, + # so: z-spin=1: (0.1, 0, 0), (0.3, 0, 0) etc. + expected_poscar = """"""supercell_generated_POSCAR +1.0 +1 2 3 +0.5 0.7 0.91 +3 1 0 +Fe Zn +1 6 +Direct +-21.84 72 -4.72 +0.1 0 0 +0.3 0 0 +2.66 -8 0.48 +0 0 0 +17.38 -54 3.54 +0.2 0 0 +"""""" + + lay.save_POSCAR(filename=fn) + with open(fn, 'r') as f: + poscar = f.read() + os.system(""rm -f "" + fn) + + self.assertEqual(expected_poscar, poscar) + + # test stdout + names = [""Fe"", ""Zn""] + # https://stackoverflow.com/questions/4219717/how-to-assert-output-with-nosetest-unittest-in-python + with patch('sys.stdout', new=StringIO()) as fakeOutput: + lay.save_POSCAR() + self.assertEqual(fakeOutput.getvalue(), expected_poscar + ""\n"" + \ + ""MAGMOM flag: 0 2*1 2*0 2*-1\n"") + # TODO: test sorting by z-spin in atomic species + + def test_save_xsf(self): + os.system(""mkdir -p tmp"") + fn = ""tmp/test.xsf"" + lay = sc.lattice() + lay.set_vectors([1, 2, 3], [0.5, 0.7, 0.91], [3, 1, 0]) + lay.add_atoms([ + sc.Atom(""Fe"", (0, 2)), + sc.Atom(""Zn"", (1, 0.5, 3), spin=(0, 1, -1)), + sc.Atom(""Zn"", (0.1, 0.2, 0.7)), + sc.Atom(""Zn"", (0, 0, 0)) + ]) + + expected_xsf = """"""CRYSTAL + +PRIMVEC +1 2 3 +0.5 0.7 0.91 +3 1 0 + +PRIMCOORD +4 1 +26 0 2 0 0 0 0 +30 1 0.5 3 0 1 -1 +30 0.1 0.2 0.7 0 0 0 +30 0 0 0 0 0 0 +"""""" + + lay.save_xsf(filename=fn) + with open(fn, 'r') as f: + xsf = f.read() + os.system(""rm -f "" + fn) + + self.assertEqual(expected_xsf, xsf) + + # test stdout + # https://stackoverflow.com/questions/4219717/how-to-assert-output-with-nosetest-unittest-in-python + with patch('sys.stdout', new=StringIO()) as fakeOutput: + lay.save_xsf() + self.assertEqual(fakeOutput.getvalue(), expected_xsf) + + def load_graphene(self): + return sc.read_POSCAR( + os.path.join(os.path.dirname(__file__), + ""../resources/vasp/graphene/POSCAR""), atomic_species=[""C""]) + + def test_translate(self): + l = sc.lattice().set_vectors([2, 0], [0, 2]) + l.add_atom(""H"", (0.0, 1.0)) + l.add_atom(""He"", (1.0, 3.0)) + + l.translate_atoms((-1, -2)) + self.assertEqual(l.atoms()[0], sc.Atom(""H"", (-1, -1))) + self.assertEqual(l.atoms()[1], sc.Atom(""He"", (0, 1))) + + l.translate_atoms((0.5, 0.5), unit=sc.Unit.Crystal) + self.assertEqual(l.atoms()[0], sc.Atom(""H"", (0, 0))) + self.assertEqual(l.atoms()[1], sc.Atom(""He"", (1, 2))) + + def test_draw(self): + pass + # TODO https://stackoverflow.com/a/27948646 + # graphene = self.load_graphene() + # nips3 = sc.read_POSCAR( + # os.path.join(os.path.dirname(__file__), + # ""../resources/vasp/NiPS3/POSCAR""), atomic_species=[""Ni"", ""P"", ""S""], + # magmom="""" + # ) + # + # def test_filesave(callback, expected_md5): + # import hashlib + # from io import BytesIO + # + # outfile = BytesIO() + # callback(outfile) + # outfile.seek(0) + # content = outfile.read() + # self.assertEqual(expected_md5, hashlib.md5(content).hexdigest()) + # outfile.close() + # + # # Graphene + # fig, ax = graphene.draw() + # test_filesave(fig.savefig, '5d1af27b61783e722a45e2990dc9c7d0') + # + # # NiPS_3 + # fig, ax = nips3.draw() + # test_filesave(fig.savefig, '3061bcb600da108c9dcb678dcadbf0ff') + # + # # Two at the same time + # fig, ax = graphene.draw() + # fig, ax = nips3.draw(ax) + # test_filesave(fig.savefig, '6dc6abe70d8ff04eda06e1f26c618377') + + def test_read_poscar_without_atomic_species(self): + graphene = sc.read_POSCAR( + os.path.join(os.path.dirname(__file__), + ""../resources/vasp/graphene/POSCAR""), atomic_species=[""C""]) + + self.assertEqual(graphene.atoms()[0], sc.Atom(""C"", (0, 0))) + self.assertEqual(graphene.atoms()[1], sc.Atom(""C"", np.array([2/3, 2/3, 0]) @ graphene.vectors())) + self.assertAlmostEqual(graphene.vectors()[0][0], 2.133341911) + self.assertAlmostEqual(graphene.vectors()[0][1], -1.231685527) + self.assertAlmostEqual(graphene.vectors()[1][0], 2.133341911) + self.assertAlmostEqual(graphene.vectors()[1][1], 1.231685527) + + def test_read_poscar_with_atomic_species(self): + graphene = sc.read_POSCAR( + os.path.join(os.path.dirname(__file__), + ""../resources/vasp/graphene/POSCAR_with_atomic_species_names"")) + + self.assertEqual(graphene.atoms()[0], sc.Atom(""C"", (0, 0))) + self.assertEqual(graphene.atoms()[1], sc.Atom(""C"", np.array([2/3, 2/3, 0]) @ graphene.vectors())) + self.assertAlmostEqual(graphene.vectors()[0][0], 2.133341911) + self.assertAlmostEqual(graphene.vectors()[0][1], -1.231685527) + self.assertAlmostEqual(graphene.vectors()[1][0], 2.133341911) + self.assertAlmostEqual(graphene.vectors()[1][1], 1.231685527)","Python" +"Substrate","tnecio/supercell-core","supercell_core/tests/test_heterostructure.py",".py","4538","138","import unittest as ut +from os import path + +import numpy as np + +import supercell_core as sc + + +class TestHeterostructure(ut.TestCase): + """""" + Test of the Heterostructure and Result classes + """""" + + def test_substrate(self): + # Tests `substrate` and `set_substrate` methods + h = sc.heterostructure() + sub = sc.lattice() + h.set_substrate(sub) + self.assertEqual(h.substrate(), sub) + + h = sc.heterostructure() + with self.assertRaises(AttributeError): + h.substrate() + + def test_layers(self): + # Tests `layers`, `add_layer`, `add_layers`, `remove_layer`, + # and `get_layer` methods + h = sc.heterostructure() + lay = sc.lattice() + lay.add_atom(""H"", (0, 0, 0)) + h.add_layer(lay, theta=1 * sc.DEGREE) + + lay2 = sc.lattice() + lay2.add_atom(""He"", (0.1, 0.1, 0.1)) + h.add_layer(lay2) + + lay3 = sc.lattice() + lay3.add_atom(""Li"", (0.2, 0.2, 0.2)) + h.add_layer(lay3, theta=(0, 45 * sc.DEGREE, 0.2 * sc.DEGREE)) + + lay4 = sc.lattice() + lay4.add_atom(""Be"", (0.3, 0.3, 0.3)) + h.add_layer(lay4, pos=1) + + self.assertEqual( + [lay, lay4, lay2, lay3], + h.layers() + ) + + h.remove_layer(1) + + self.assertEqual( + [lay, lay2, lay3], + h.layers() + ) + + h = sc.heterostructure() + h.add_layers([ + (lay, 1 * sc.DEGREE), + lay2, + (lay3, (0, 45 * sc.DEGREE, 0.2 * sc.DEGREE)), + lay4 + ]) + + self.assertEqual( + [lay, lay2, lay3, lay4], + h.layers() + ) + + got_lay = h.get_layer(0) + + self.assertEqual(lay, got_lay[0]) + self.assertEqual((1 * sc.DEGREE, 1 * sc.DEGREE, 1.0), got_lay[1]) + + with self.assertRaises(IndexError): + h.get_layer(10) + + def test_opt(self, algorithm=""fast""): + # graphene-NiPS3 low-strain angle 21.9, theta range 16-30-0.1 + graphene = sc.read_POSCAR( + path.join(path.dirname(__file__), ""../resources/vasp/graphene/POSCAR""), + atomic_species=[""C""]) + nips3 = sc.read_POSCAR( + path.join(path.dirname(__file__), ""../resources/vasp/NiPS3/POSCAR""), + atomic_species=[""Ni"", ""P"", ""S""] + ) + + h = sc.heterostructure() + h.set_substrate(graphene) + h.add_layer(nips3) + + res = h.opt(max_el=11, + thetas=np.arange(16 * sc.DEGREE, 30 * sc.DEGREE, 0.1 * sc.DEGREE), + algorithm=algorithm) + + self.assertTrue(np.allclose(res.M(), np.array([[7, 9], [10, -8]])) + or np.allclose(res.M(), np.array([[9, 7], [-8, 10]]))) + self.assertTrue(np.allclose(res.layer_Ms()[0], np.array([[6, -1], [-1, -2]])) + or np.allclose(res.layer_Ms()[0], np.array([[-1, 6], [-2, -1]]))) + self.assertAlmostEqual(res.thetas()[0], 21.9 * sc.DEGREE) + self.assertAlmostEqual(res.max_strain(), 0.000608879275296, places=5) + self.assertEqual(res.atom_count(), 552) + + def test_opt_direct(self): + return self.test_opt(algorithm=""direct"") + + def test_opt_graphene_fast(self): + graphene = sc.read_POSCAR( + path.join(path.dirname(__file__), ""../resources/vasp/graphene/POSCAR""), + atomic_species=[""C""]) + + h = sc.heterostructure() + h.set_substrate(graphene) + h.add_layer(graphene) + + res = h.opt(max_el=20, thetas=np.arange(5.5 * sc.DEGREE, 7 * sc.DEGREE, 0.001 * sc.DEGREE)) + self.assertAlmostEqual(res.max_strain(), 0, places=6) + self.assertEqual(res.atom_count(), 364) + + def test_homogeneous_trilayer(self): + graphene = sc.read_POSCAR( + path.join(path.dirname(__file__), ""../resources/vasp/graphene/POSCAR""), + atomic_species=[""C""]) + + h = sc.heterostructure().set_substrate(graphene).add_layer(graphene).add_layer(graphene) + res = h.opt(max_el=4, thetas=[np.arange(0, 10*sc.DEGREE, 1 * sc.DEGREE)]*2) + + self.assertEqual(res.atom_count(), 3 * len(graphene.atoms())) + + def test_bad_arg_thetas(self): + graphene = sc.read_POSCAR( + path.join(path.dirname(__file__), ""../resources/vasp/graphene/POSCAR""), + atomic_species=[""C""]) + + h = sc.heterostructure().set_substrate(graphene).add_layer(graphene).add_layer(graphene) + with self.assertRaises(TypeError): + h.opt(max_el=4, thetas=[np.arange(0, 10 * sc.DEGREE, 1 * sc.DEGREE)]) +","Python" +"Substrate","tnecio/supercell-core","supercell_core/tests/test_calc.py",".py","2305","62","import unittest as ut + +from ..calc import * + + +class TestCalc(ut.TestCase): + def test_inv(self): + # this also tests det since inv uses det internally + a = 3 + m = np.random.random((a, a, a, a, 2, 2)) + expected = np.empty((a, a, a, a, 2, 2)) + for i in range(a): + for j in range(a): + for k in range(a): + for l in range(a): + expected[i, j, k, l] = np.linalg.inv(m[i, j, k, l]) + self.assertTrue(np.allclose(expected, inv(m))) + + def test_matvecmul(self): + a = 3 + m1 = np.random.random((a, a, a, a, 2, 2)) + m2 = np.random.random((a, a, a, a, 2)) + expected = np.empty((a, a, a, a, 2)) + for i in range(a): + for j in range(a): + for k in range(a): + for l in range(a): + expected[i, j, k, l] = m1[i, j, k, l] @ m2[i, j, k, l] + actual = matvecmul(m1, m2) + self.assertTrue(np.allclose(expected, actual)) + + def test_rotate(self): + a = 3 + theta = np.random.random() + m = np.random.random((a, a, a, a, 2, 2)) + expected = np.empty((a, a, a, a, 2, 2)) + for i in range(a): + for j in range(a): + for k in range(a): + for l in range(a): + expected[i, j, k, l] = np.array([[np.cos(theta), -np.sin(theta)], + [np.sin(theta), np.cos(theta)]]) @ m[i, j, k, l] + actual = rotate(m, theta) + self.assertTrue(np.allclose(expected, actual)) + + def test_matnorm(self): + a = 3 + theta = np.random.random() + m = np.random.random((a, a, a, a, 2, 2)) + expected1 = np.empty((a, a, a, a)) + expected2 = np.empty((a, a, a, a)) + for i in range(a): + for j in range(a): + for k in range(a): + for l in range(a): + expected1[i, j, k, l] = np.max(np.sum(np.abs(m[i, j, k, l]))) + expected2[i, j, k, l] = np.linalg.norm(m[i, j, k, l]) + actual1 = matnorm(m, 1, 1) + actual2 = matnorm(m, 2, 2) + self.assertTrue(np.allclose(expected1, actual1)) + self.assertTrue(np.allclose(expected2, actual2)) +","Python" +"Substrate","tnecio/supercell-core","examples/ManuscriptExamples.ipynb",".ipynb","81010","418","{ + ""cells"": [ + { + ""cell_type"": ""code"", + ""execution_count"": 1, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""import supercell_core as sc\n"", + ""import numpy as np\n"", + ""import matplotlib.pyplot as plt\n"", + ""import pandas as pd"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 32, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""gr = (sc.lattice()\n"", + "" # Default unita are Angstrom coordinates\n"", + "" .set_vectors([2.13, -1.23], [2.13, 1.23])\n"", + "" .add_atom(\""C\"", [0, 0], unit=sc.Unit.Crystal)\n"", + "" .add_atom(\""C\"", [2 / 3, 2 / 3], unit=sc.Unit.Crystal)\n"", + "" )\n"", + ""ph = sc.read_POSCAR(\""data/POSCAR-P-NEW\"", atomic_species=[\""P\""])\n"", + ""hbn = sc.read_POSCAR(\""data/POSCAR_hBN\"", atomic_species=[\""B\"", \""N\""])\n"", + ""ni = sc.read_POSCAR(\""data/POSCAR_Ni111\"", atomic_species=[\""Ni\""])\n"", + ""\n"", + ""bilayer = (sc.heterostructure()\n"", + "" .set_substrate(gr)\n"", + "" .add_layer(gr)\n"", + "" )\n"", + ""trilayer = (sc.heterostructure()\n"", + "" .set_substrate(gr)\n"", + "" .add_layer(gr)\n"", + "" .add_layer(gr)\n"", + "" )\n"", + ""hgp = (sc.heterostructure()\n"", + "" .set_substrate(hbn)\n"", + "" .add_layer(gr)\n"", + "" .add_layer(ph)\n"", + "" )\n"", + ""\n"", + ""hpg = (sc.heterostructure()\n"", + "" .set_substrate(hbn)\n"", + "" .add_layer(ph)\n"", + "" .add_layer(gr)\n"", + "" )"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 27, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""MAGMOM flag: 2052*0\n"" + ] + }, + { + ""data"": { + ""text/plain"": [ + ""0.04098389728877475"" + ] + }, + ""execution_count"": 27, + ""metadata"": {}, + ""output_type"": ""execute_result"" + } + ], + ""source"": [ + ""thetas = [[0], [0.4 * sc.DEGREE]]\n"", + ""tmp = hgp.opt(max_el=20, thetas=thetas)\n"", + ""res_0_04 = hgp.calc(M=tmp.M(), thetas=tmp.thetas())\n"", + ""res_0_04.superlattice().save_POSCAR(\""POSCAR_hgp_0_04\"")\n"", + ""res_0_04.max_strain()"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 23, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""MAGMOM flag: 922*0\n"" + ] + }, + { + ""data"": { + ""text/plain"": [ + ""0.09177894628439413"" + ] + }, + ""execution_count"": 23, + ""metadata"": {}, + ""output_type"": ""execute_result"" + } + ], + ""source"": [ + ""thetas = [[3.8 * sc.DEGREE], [18.1 * sc.DEGREE]]\n"", + ""tmp = hpg.opt(max_el=20, thetas=thetas)\n"", + ""res_3_18 = hpg.calc(M=tmp.M(), thetas=tmp.thetas())\n"", + ""res_3_18.superlattice().save_POSCAR(\""POSCAR_hpg_3_18\"")\n"", + ""res_3_18.max_strain()"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 16, + ""metadata"": {}, + ""outputs"": [ + { + ""data"": { + ""text/plain"": [ + ""(
,\n"", + "" )"" + ] + }, + ""execution_count"": 16, + ""metadata"": {}, + ""output_type"": ""execute_result"" + }, + { + ""data"": { + ""text/plain"": [ + ""
"" + ] + }, + ""metadata"": {}, + ""output_type"": ""display_data"" + }, + { + ""data"": { + ""image/png"": ""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\n"", + ""text/plain"": [ + ""
"" + ] + }, + ""metadata"": { + ""needs_background"": ""light"" + }, + ""output_type"": ""display_data"" + } + ], + ""source"": [ + ""res_3_18.superlattice().draw()"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 17, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""# Temporary workaround for atom counts not being logged, Also, calculate thetas in deg instead of radians\n"", + ""def fix_log(df, *layers): \n"", + "" def cellsize(lattice):\n"", + "" vecs = [v[0:2] for v in lattice.vectors()[0:2]]\n"", + "" return np.abs(np.linalg.det(np.array(vecs)))\n"", + "" \n"", + "" df[\""atom_count\""] = 0\n"", + "" for lay in layers:\n"", + "" df[\""atom_count\""] += df[\""supercell_size\""] / cellsize(lay) * len(lay.atoms())\n"", + "" \n"", + "" df[\""atom_count\""] = np.round(df[\""atom_count\""]).astype('int64')\n"", + "" \n"", + "" df[\""theta_0_deg\""] = df[\""theta_0\""] / sc.DEGREE\n"", + "" if \""theta_1\"" in df.columns:\n"", + "" df[\""theta_1_deg\""] = df[\""theta_1\""] / sc.DEGREE\n"", + "" \n"", + "" return df"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 33, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""# Optimise hbn/gr/ph for Lmax=10 or Lmax=40 using fast algorithm\n"", + ""# Only for angles up to 30 degrees but in principle since there is no symmetry here,\n"", + ""# we should perform full search\n"", + ""res_hgp10 = hgp.opt(\n"", + "" max_el=10,\n"", + "" thetas=[np.arange(0, 30 * sc.DEGREE, 0.1 * sc.DEGREE), np.arange(0, 30 * sc.DEGREE, 0.1 * sc.DEGREE)],\n"", + "" algorithm=\""fast\"",\n"", + "" log=True\n"", + "")\n"", + ""\n"", + ""log_hgp10 = fix_log(res_hgp10.log, hbn, gr, ph)\n"", + ""log_hgp10.to_csv(\""hgp10.csv\"")\n"", + ""log_hgp10_head = log_hgp10.sort_values(\""max_strain\"").head(20)\n"", + ""log_hgp10_head.to_csv(\""hgp10_head.csv\"")"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 34, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""res_hgp40 = hgp.opt(\n"", + "" max_el=40,\n"", + "" thetas=[np.arange(0, 30 * sc.DEGREE, 0.1 * sc.DEGREE), np.arange(0, 30 * sc.DEGREE, 0.1 * sc.DEGREE)],\n"", + "" algorithm=\""fast\"",\n"", + "" log=True\n"", + "")\n"", + ""\n"", + ""log_hgp40 = fix_log(res_hgp40.log, hbn, gr, ph)\n"", + ""log_hgp40.to_csv(\""hgp40.csv\"")\n"", + ""log_hgp40_head = log_hgp40.sort_values(\""max_strain\"").head(20)\n"", + ""log_hgp40_head.to_csv(\""hgp40_head.csv\"")"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 36, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""MAGMOM flag: 300*0\n"", + ""MAGMOM flag: 3804*0\n"" + ] + }, + { + ""data"": { + ""text/plain"": [ + """" + ] + }, + ""execution_count"": 36, + ""metadata"": {}, + ""output_type"": ""execute_result"" + } + ], + ""source"": [ + ""# Save POSCARs\n"", + ""hgp.calc(M=res_hgp10.M(), thetas=res_hgp10.thetas()).superlattice().save_POSCAR(\""POSCAR10\"")\n"", + ""hgp.calc(M=res_hgp40.M(), thetas=res_hgp40.thetas()).superlattice().save_POSCAR(\""POSCAR40\"")"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 39, + ""metadata"": {}, + ""outputs"": [ + { + ""data"": { + ""text/plain"": [ + ""[10.9, 29.900000000000002]"" + ] + }, + ""execution_count"": 39, + ""metadata"": {}, + ""output_type"": ""execute_result"" + }, + { + ""data"": { + ""text/plain"": [ + ""
"" + ] + }, + ""metadata"": {}, + ""output_type"": ""display_data"" + }, + { + ""data"": { + ""image/png"": ""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\n"", + ""text/plain"": [ + ""
"" + ] + }, + ""metadata"": { + ""needs_background"": ""light"" + }, + ""output_type"": ""display_data"" + } + ], + ""source"": [ + ""hgp.calc(M=res_hgp10.M(), thetas=res_hgp10.thetas()).superlattice().draw()\n"", + ""[x / sc.DEGREE for x in res_hgp10.thetas()]"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 47, + ""metadata"": {}, + ""outputs"": [ + { + ""data"": { + ""text/plain"": [ + ""0.022797574474801068"" + ] + }, + ""execution_count"": 47, + ""metadata"": {}, + ""output_type"": ""execute_result"" + } + ], + ""source"": [ + ""hgp.calc(M=res_hgp10.M(), thetas=res_hgp10.thetas()).max_strain()"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 22, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""# Optimise bilayer graphene using fast algorithm\n"", + ""res_bilayer = bilayer.opt(\n"", + "" max_el=61,\n"", + "" thetas=[np.arange(0, 30 * sc.DEGREE, 0.1 * sc.DEGREE)],\n"", + "" algorithm=\""fast\"",\n"", + "" log=True\n"", + "")\n"", + ""\n"", + ""log_bilayer = fix_log(res_bilayer.log, gr, gr)\n"", + ""log_bilayer.to_csv(\""bilayer_graphene.csv\"")"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 53, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""101 101\n"" + ] + }, + { + ""data"": { + ""image/png"": ""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\n"", + ""text/plain"": [ + ""
"" + ] + }, + ""metadata"": { + ""needs_background"": ""light"" + }, + ""output_type"": ""display_data"" + } + ], + ""source"": [ + ""# Colormap\n"", + ""log4 = log_hgp10\n"", + ""log_subset = log4[(log4.theta_0 >= 0 * sc.DEGREE)\n"", + "" & (log4.theta_0 <= 10 * sc.DEGREE)\n"", + "" & (log4.theta_1 >= 0 * sc.DEGREE)\n"", + "" & (log4.theta_1 <= 10 * sc.DEGREE)]\n"", + ""side1 = len(log_subset.theta_0.unique())\n"", + ""side2 = len(log_subset.theta_1.unique())\n"", + ""print(side1, side2)\n"", + ""import matplotlib\n"", + ""params = {'legend.fontsize': 'x-large',\n"", + "" 'axes.labelsize': 'x-large',\n"", + "" 'axes.titlesize':'x-large',\n"", + "" 'xtick.labelsize':'x-large',\n"", + "" 'ytick.labelsize':'x-large'}\n"", + ""plt.rcParams.update(params)\n"", + ""\n"", + ""plt.pcolormesh(log_subset.theta_0.unique() / sc.DEGREE,\n"", + "" log_subset.theta_1.unique() / sc.DEGREE,\n"", + "" np.array(log_subset.max_strain).reshape(side1, side2),\n"", + "" cmap=\""inferno\"", norm=matplotlib.colors.LogNorm())\n"", + ""plt.colorbar()\n"", + ""plt.xlabel(\""$\\\\theta_0$ [°]\"", fontsize=14)\n"", + ""plt.ylabel(\""$\\\\theta_1$ [°]\"", fontsize=14)\n"", + ""plt.title(\""min $\\sum_i L_{1, 1}(\\\\varepsilon_i)$\"", fontsize=14)\n"", + ""plt.tight_layout()\n"", + ""plt.savefig(\""hgp_map_Lmax10_2020_07_26.png\"")"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [] + } + ], + ""metadata"": { + ""kernelspec"": { + ""display_name"": ""python3-system"", + ""language"": ""python"", + ""name"": ""python3-system"" + }, + ""language_info"": { + ""codemirror_mode"": { + ""name"": ""ipython"", + ""version"": 3 + }, + ""file_extension"": "".py"", + ""mimetype"": ""text/x-python"", + ""name"": ""python"", + ""nbconvert_exporter"": ""python"", + ""pygments_lexer"": ""ipython3"", + ""version"": ""3.7.6"" + } + }, + ""nbformat"": 4, + ""nbformat_minor"": 4 +} +","Unknown" +"Substrate","tnecio/supercell-core","examples/bilayer_graphene.py",".py","616","23","import supercell_core as sc + +# Defining unit cell of graphene +graphene = sc.lattice() +graphene.set_vectors([2.13, -1.23], [2.13, 1.23]) +# ""C"" (carbon) atoms in the unit cell in either +# angstrom or direct coordinates +graphene.add_atom(""C"", (0, 0, 0))\ +.add_atom(""C"", (2/3, 2/3, 0), +unit=sc.Unit.Crystal) + +# Combining graphene layers +h = sc.heterostructure().set_substrate(graphene)\ +.add_layer(graphene) + +import numpy as np +# Optimise with theta as a free parameter +res = h.opt(max_el=12, thetas=\ +[np.arange(0, 7*sc.DEGREE, 0.1*sc.DEGREE)]) + +# Save supercell to VASP POSCAR +res.superlattice().save_POSCAR(""POSCAR"") +","Python" +"Substrate","tnecio/supercell-core","examples/graphene_nips3.py",".py","607","18","import supercell_core as sc +import matplotlib.pyplot as plt + +# Read graphene and NiPS3 definition from POSCAR +graphene = sc.read_POSCAR(""supercell_core/resources/vasp/POSCAR_Gr"") +nips3 = sc.read_POSCAR(""supercell_core/resources/vasp/POSCAR_NiPS3"", atomic_species=['Ni', 'P', 'S']) +h = sc.heterostructure().set_substrate(graphene)\ +.add_layer(nips3) + +res = h.opt(max_el=8, thetas=[ +np.arange(0, 30 * sc.DEGREE, 0.25*sc.DEGREE)]) + +# Draw the resulting supercell +res.superlattice().draw() +plt.title(""""""Best supercell found for $\\theta$ = +{} max strain = {:.4g}"""""" +.format(res.thetas()[0], res.max_strain())) +","Python" +"Substrate","tnecio/supercell-core","docs/source/conf.py",".py","5853","194","# -*- coding: utf-8 -*- +# +# Configuration file for the Sphinx documentation builder. +# +# This file does only contain a selection of the most common options. For a +# full list see the documentation: +# http://www.sphinx-doc.org/en/master/config + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('../..')) + + +# -- Project information ----------------------------------------------------- + +project = u'supercell_core' +copyright = u'2019, Tomasz Necio' +author = u'Tomasz Necio' + +# The short X.Y version +version = u'' +# The full version, including alpha/beta/rc tags +release = u'0.0.2' + + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.intersphinx', + 'sphinx.ext.coverage', + 'sphinx.ext.mathjax', + 'sphinx.ext.ifconfig', + 'sphinx.ext.viewcode', + 'sphinx.ext.githubpages', + 'sphinx.ext.napoleon', + 'recommonmark', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set ""language"" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = None + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +add_module_names = False + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named ""default.css"" will overwrite the builtin ""default.css"". +html_static_path = ['_static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. +# +# html_sidebars = {} + + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'supercell_coredoc' + + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'supercell_core.tex', u'supercell\\_core Documentation', + u'Tomasz Necio', 'manual'), +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'supercell_core', u'supercell_core Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'supercell_core', u'supercell_core Documentation', + author, 'supercell_core', 'One line description of project.', + 'Miscellaneous'), +] + + +# -- Options for Epub output ------------------------------------------------- + +# Bibliographic Dublin Core info. +epub_title = project + +# The unique identifier of the text. This can be a ISBN number +# or the project homepage. +# +# epub_identifier = '' + +# A unique identification for the text. +# +# epub_uid = '' + +# A list of files that should not be packed into the epub file. +epub_exclude_files = ['search.html'] + + +# -- Extension configuration ------------------------------------------------- + +# -- Options for intersphinx extension --------------------------------------- + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'https://docs.python.org/': None} +","Python" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","deps/DeprecateKeywords.jl",".jl","4806","154","module DeprecateKeywords + +using MacroTools + +"""""" + @depkws [force=false] def + +Macro to deprecate keyword arguments. Use by wrapping a function signature, +while using `@deprecate(old_kw, new_kw)` within the function signature to deprecate. + +# Examples + +```julia +@depkws function f(; a=2, @deprecate(b, a)) + a +end +``` + +```julia +# force the deprecation warning to be emitted +@depkws force=true function f(; a=2, @deprecate(b, a)) + a +end +``` +"""""" +macro depkws(args...) + options = parse_options(args[1:end-1]) + return esc(_depkws(args[end], options)) +end + +function parse_options(args) + options = default_options() + for arg in args + if isa(arg, Expr) && arg.head == :(=) + @assert arg.args[1] ∈ keys(options) ""Unknown option: $(arg.args[1])"" + options[arg.args[1]] = arg.args[2] + else + error(""Invalid option: $arg"") + end + end + return options +end + +function default_options() + return Dict{Symbol, Any}(:force => false) +end + +abstract type DeprecatedDefault end + +function _depkws(def, options) + sdef = splitdef(def) + func_symbol = Expr(:quote, sdef[:name]) # Double quote for expansion + + new_symbols = Symbol[] + deprecated_symbols = Symbol[] + kwargs_to_remove = Int[] + for (i, param) in enumerate(sdef[:kwargs]) + isa(param, Symbol) && continue + # Look for @deprecated macro: + if param.head == :macrocall && param.args[1] == Symbol(""@deprecate"") + # e.g., params.args[2] is the line number + deprecated_symbol = param.args[end-1] + new_symbol = param.args[end] + if !isa(new_symbol, Symbol) + # Remove line numbers nodes: + clean_param = deepcopy(param) + filter!(x -> !isa(x, LineNumberNode), clean_param.args) + error( + ""The expression\n $(clean_param)\ndoes not appear to be two symbols in a `@deprecate`. This can happen if you use `@deprecate` in a function "" * + ""definition without "" * + ""parentheses, such as `f(; @deprecate a b, c=2)`. Instead, you should write `f(; (@deprecate a b), c=2)` or alternatively "" * + ""`f(; @deprecate(a, b), c=2)`.)"" + ) + end + push!(deprecated_symbols, deprecated_symbol) + push!(new_symbols, new_symbol) + push!(kwargs_to_remove, i) + end + end + deleteat!(sdef[:kwargs], kwargs_to_remove) + + # Add deprecated kws: + for deprecated_symbol in deprecated_symbols + pushfirst!(sdef[:kwargs], Expr(:kw, deprecated_symbol, DeprecatedDefault)) + end + + symbol_mapping = Dict(new_symbols .=> deprecated_symbols) + + # Update new symbols to use deprecated kws if passed: + for (i, kw) in enumerate(sdef[:kwargs]) + no_default_type_assertion = !isa(kw, Symbol) && kw.head != :kw + no_default_naked = isa(kw, Symbol) + no_default = no_default_naked || no_default_type_assertion + + (kw, type_assertion) = if no_default_type_assertion + @assert kw.head == :(::) + # Remove type assertion from keyword; we will + # assert it later. + kw.args + else + (kw, Nothing) + end + + new_kw, default = if no_default + (kw, DeprecatedDefault) + else + (kw.args[1], kw.args[2]) + end + + _get_symbol(new_kw) in deprecated_symbols && continue + !(_get_symbol(new_kw) in new_symbols) && continue + + deprecated_symbol = symbol_mapping[_get_symbol(new_kw)] + depwarn_string = ""Keyword argument `$(deprecated_symbol)` is deprecated. Use `$(_get_symbol(new_kw))` instead."" + new_kwcall = quote + if $deprecated_symbol !== $(DeprecatedDefault) + Base.depwarn($depwarn_string, $func_symbol; force=$(options[:force])) + $deprecated_symbol + else + $default + end + end + sdef[:kwargs][i] = Expr(:kw, new_kw, new_kwcall) + + if no_default_type_assertion + pushfirst!( + sdef[:body].args, + Expr(:(::), _get_symbol(new_kw), type_assertion) + ) + end + + if no_default + # Propagate UndefKeywordError + pushfirst!( + sdef[:body].args, + Expr(:if, + Expr(:call, :(===), _get_symbol(new_kw), DeprecatedDefault), + Expr(:call, :throw, + Expr(:call, :UndefKeywordError, QuoteNode(_get_symbol(new_kw))) + ) + ) + ) + end + end + + return combinedef(sdef) +end + +# This is used to go from a::Int to a +_get_symbol(e::Expr) = first(map(_get_symbol, e.args)) +_get_symbol(e::Symbol) = e + +end +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/export.jl",".jl","16938","403","using LightXML, PhysiCellXMLRules + +export exportSimulation + +"""""" + exportSimulation(simulation_id::Integer[, export_folder::AbstractString]) + +Create a `user_project` folder from a simulation that can be loaded into PhysiCell. + +Warning: not all features in drbergman/PhysiCell/latest/release are not supported in MathCancer/PhysiCell. + +# Arguments +- `simulation_id::Integer`: the id of the simulation to export. Can also be a `Simulation` object. +- `export_folder::AbstractString`: the folder to export the simulation to. Default is the simulation output folder. + +# Returns +- `export_folder::AbstractString`: the folder where the simulation was exported to +"""""" +function exportSimulation(simulation_id::Integer, export_folder::AbstractString=""$(joinpath(trialFolder(Simulation, simulation_id), ""UserProjectExport""))"") + assertInitialized() + simulation = Simulation(simulation_id) + return exportSimulation(simulation, export_folder) +end + +function exportSimulation(simulation::Simulation, export_folder::AbstractString=""$(joinpath(trialFolder(simulation), ""UserProjectExport""))"") + success, physicell_version = createExportFolder(simulation, export_folder) + if success + msg = """""" + Exported simulation $(simulation.id) successfully to $(export_folder). + Copy this folder into `PhysiCell/user_projects` for a PhysiCell folder with version $(physicell_version). + Load it with + make load PROJ=UserProjectExport # or however you renamed the folder + Then run it with + make && $(baseToExecutable(""project"")) # or however you renamed the executable + """""" + println(msg) + else + msg = """""" + Exporting simulation $(simulation.id) failed. + See the error messages above for more information. + Cleaning up what was created in $(export_folder). + """""" + println(msg) + rm(export_folder; force=true, recursive=true) + end + return export_folder +end + +"""""" + createExportFolder(simulation::Simulation, export_folder::AbstractString) + +Create and populate the export folder for a simulation. +"""""" +function createExportFolder(simulation::Simulation, export_folder::AbstractString) + export_config_folder = joinpath(export_folder, ""config"") + mkpath(export_config_folder) + + query = constructSelectQuery(""simulations"", ""WHERE simulation_id = $(simulation.id)"") + row = queryToDataFrame(query; is_row=true) + + #! config file + path_to_xml = joinpath(locationPath(:config, simulation), locationVariationsFolder(:config), ""config_variation_$(row.config_variation_id[1]).xml"") + cp(path_to_xml, joinpath(export_config_folder, ""PhysiCell_settings.xml"")) + + #! custom code + path_to_custom_codes_folder = locationPath(:custom_code, simulation) + for filename in [""main.cpp"", ""Makefile""] + cp(joinpath(path_to_custom_codes_folder, filename), joinpath(export_folder, filename)) + end + cp(joinpath(path_to_custom_codes_folder, ""custom_modules""), joinpath(export_folder, ""custom_modules"")) + + #! rulesets + if row.rulesets_collection_id[1] != -1 + path_to_xml = joinpath(locationPath(:rulesets_collection, simulation), locationVariationsFolder(:rulesets_collection), ""rulesets_collection_variation_$(row.rulesets_collection_variation_id[1]).xml"") + path_to_csv = joinpath(export_folder, ""config"", ""cell_rules.csv"") + exportCSVRules(path_to_csv, path_to_xml) + end + + #! intracellulars + if row.intracellular_id[1] != -1 + exportIntracellular(simulation, export_folder) + end + + #! ic cells + if row.ic_cell_id[1] != -1 + path_to_ic_cells_folder = locationPath(:ic_cell, simulation) + ic_cell_file_name = readdir(path_to_ic_cells_folder) + filter!(x -> x in [""cells.csv"", ""cells.xml""], ic_cell_file_name) + ic_cell_file_name = ic_cell_file_name[1] + if endswith(ic_cell_file_name, "".xml"") + #! rel path from ic_cells_folder + ic_cell_file_name = joinpath(locationVariationsFolder(:ic_cell), ""ic_cell_variation_$(row.ic_cell_variation_id[1])_s$(simulation.id).csv"") + end + cp(joinpath(path_to_ic_cells_folder, ic_cell_file_name), joinpath(export_folder, ""config"", ""cells.csv"")) + end + + #! ic substrates + if row.ic_substrate_id[1] != -1 + path_to_file = joinpath(locationPath(:ic_substrate, simulation), ""substrates.csv"") + cp(path_to_file, joinpath(export_folder, ""config"", ""substrates.csv"")) + end + + #! ic ecm + if row.ic_ecm_id[1] != -1 + path_to_ic_ecm_folder = locationPath(:ic_ecm, simulation) + ic_ecm_file_name = readdir(path_to_ic_ecm_folder) + filter!(x -> x in [""ecm.csv"", ""ecm.xml""], ic_ecm_file_name) + ic_ecm_file_name = ic_ecm_file_name[1] + if endswith(ic_ecm_file_name, "".xml"") + #! rel path from ic_ecm_folder + ic_ecm_file_name = joinpath(locationVariationsFolder(:ic_ecm), ""ic_ecm_variation_$(row.ic_ecm_variation_id[1])_s$(simulation.id).csv"") + end + cp(joinpath(path_to_ic_ecm_folder, ic_ecm_file_name), joinpath(export_folder, ""config"", ""ecm.csv"")) + end + + #! ic dcs + if row.ic_dc_id[1] != -1 + path_to_file = joinpath(locationPath(:ic_dc, simulation), ""dcs.csv"") + cp(path_to_file, joinpath(export_folder, ""config"", ""dcs.csv"")) + end + + #! get physicell version + physicell_version_id = row.physicell_version_id[1] + where_str = ""WHERE physicell_version_id = (:physicell_version_id)"" + stmt_str = constructSelectQuery(""physicell_versions"", where_str) + params = (; :physicell_version_id => physicell_version_id) + row = stmtToDataFrame(stmt_str, params; is_row=true) + physicell_version = row.tag[1] + if ismissing(physicell_version) + physicell_version = row.commit_hash[1] + end + physicell_version = split(physicell_version, ""-"")[1] + return revertSimulationFolderToCurrentPhysiCell(export_folder, physicell_version), physicell_version +end + +"""""" + exportIntracellular(simulation::Simulation, export_folder::AbstractString) + +Export the intracellular model for a simulation to the export folder. +"""""" +function exportIntracellular(simulation::Simulation, export_folder::AbstractString) + path_to_intracellular = joinpath(locationPath(:intracellular, simulation), ""intracellular.xml"") + xml_doc = parse_file(path_to_intracellular) + intracellulars_element = retrieveElement(xml_doc, [""intracellulars""]) + intracellular_mapping = Dict{String,Tuple{String,String}}() + for intracellular_element in child_elements(intracellulars_element) + intracellular_id = attribute(intracellular_element, ""ID"") + intracellular_type = attribute(intracellular_element, ""type"") + new_root = child_elements(intracellular_element) |> first + new_xml_doc = XMLDocument() + set_root(new_xml_doc, new_root) + path_end = joinpath(""config"", ""intracellular_$(intracellular_type)_$(intracellular_id).xml"") + new_path = joinpath(export_folder, path_end) + save_file(new_xml_doc, new_path) + free(new_xml_doc) + intracellular_mapping[intracellular_id] = (intracellular_type, path_end) + end + + path_to_exported_config = joinpath(export_folder, ""config"", ""PhysiCell_settings.xml"") + config_xml = parse_file(path_to_exported_config) + + cell_definitions_element = retrieveElement(xml_doc, [""cell_definitions""]) + for cell_definition_element in child_elements(cell_definitions_element) + if name(cell_definition_element) != ""cell_definition"" + continue + end + cell_type = attribute(cell_definition_element, ""name"") + intracellular_ids_element = find_element(cell_definition_element, ""intracellular_ids"") + ID_elements = get_elements_by_tagname(intracellular_ids_element, ""ID"") + @assert length(ID_elements) <= 1 ""Do not (yet?) support multiple intracellular models for a single cell type."" + intracellular_id = ID_elements |> first |> content + config_cell_def_intracellular_element = retrieveElement(config_xml, [""cell_definitions"", ""cell_definition:name:$(cell_type)"", ""phenotype"", ""intracellular""]) + set_attribute(config_cell_def_intracellular_element, ""type"", intracellular_mapping[intracellular_id][1]) + + #! get (or create) the sbml_filename element + sbml_filename_element = makeXMLPath(config_cell_def_intracellular_element, ""sbml_filename"") + set_content(sbml_filename_element, intracellular_mapping[intracellular_id][2]) + end + + save_file(config_xml, path_to_exported_config) + free(config_xml) + free(xml_doc) + return +end + +"""""" + revertSimulationFolderToCurrentPhysiCell(export_folder::AbstractString, physicell_version::AbstractString) + +Revert the simulation folder to the given PhysiCell version. +"""""" +function revertSimulationFolderToCurrentPhysiCell(export_folder::AbstractString, physicell_version::AbstractString) + success = revertMain(export_folder, physicell_version) + success &= revertMakefile(export_folder, physicell_version) + success &= revertConfig(export_folder, physicell_version) + success &= revertCustomModules(export_folder, physicell_version) + return success +end + +"""""" + revertMain(export_folder::AbstractString, physicell_version::AbstractString) + +Revert the main.cpp file in the export folder to the given PhysiCell version. +"""""" +function revertMain(export_folder::AbstractString, physicell_version::AbstractString) + path_to_main = joinpath(export_folder, ""main.cpp"") + lines = readlines(path_to_main) + idx = findfirst(contains(""""), lines) + if !isnothing(idx) + popat!(lines, idx) + end + + idx1 = findfirst(contains(""// read arguments""), lines) + if isnothing(idx1) + idx1 = findfirst(contains(""argument_parser""), lines) + if isnothing(idx1) + msg = """""" + Could not identify where the argument_parser ends in the main.cpp file. + Aborting the export process. + """""" + println(msg) + return false + end + end + idx2 = findfirst(contains(""// OpenMP setup""), lines) + if isnothing(idx2) + idx2 = findfirst(x -> contains(x, ""omp_set_num_threads("") && contains(x, ""PhysiCell_settings.omp_num_threads""), lines) + if isnothing(idx2) + msg = """""" + Could not identify where the omp_set_num_threads is in the main.cpp file. + Aborting the export process. + """""" + println(msg) + return false + end + end + deleteat!(lines, idx1:(idx2-1)) #! delete up to but not including the omp_set_num_threads line + + parsing_block = """""" + // load and parse settings file(s) + + bool XML_status = false; + char copy_command [1024]; + if( argc > 1 ) + { + XML_status = load_PhysiCell_config_file( argv[1] ); + sprintf( copy_command , ""cp %s %s"" , argv[1] , PhysiCell_settings.folder.c_str() ); + } + else + { + XML_status = load_PhysiCell_config_file( ""./config/PhysiCell_settings.xml"" ); + sprintf( copy_command , ""cp ./config/PhysiCell_settings.xml %s"" , PhysiCell_settings.folder.c_str() ); + } + if( !XML_status ) + { exit(-1); } + + // copy config file to output directory + system( copy_command ); + """""" + lines = [lines[1:(idx1-1)]; parsing_block; lines[idx1:end]] + + open(path_to_main, ""w"") do io + for line in lines + println(io, line) + end + end + return true +end + +"""""" + revertMakefile(export_folder::AbstractString, physicell_version::AbstractString) + +Revert the Makefile in the export folder to the given PhysiCell version. +"""""" +function revertMakefile(export_folder::AbstractString, physicell_version::AbstractString) + path_to_makefile = joinpath(export_folder, ""Makefile"") + file_str = read(path_to_makefile, String) + file_str = replace(file_str, ""PhysiCell_rules_extended"" => ""PhysiCell_rules"") + open(path_to_makefile, ""w"") do io + write(io, file_str) + end + return true #! nothing to do as of yet for the Makefile +end + +"""""" + revertConfig(export_folder::AbstractString, physicell_version::AbstractString) + +Revert the config folder in the export folder to the given PhysiCell version. +"""""" +function revertConfig(export_folder::AbstractString, physicell_version::AbstractString) + path_to_config_folder = joinpath(export_folder, ""config"") + path_to_config = joinpath(path_to_config_folder, ""PhysiCell_settings.xml"") + xml_doc = parse_file(path_to_config) + + #! output folder + folder_element = makeXMLPath(xml_doc, [""save"", ""folder""]) + set_content(folder_element, ""output"") + + #! ic substrate + substrate_ic_element = makeXMLPath(xml_doc, [""microenvironment_setup"", ""options"", ""initial_condition""]) + using_substrate_ics = isfile(joinpath(path_to_config_folder, ""substrates.csv"")) + set_attributes(substrate_ic_element; type=""csv"", enabled=string(using_substrate_ics)) + filename_element = makeXMLPath(substrate_ic_element, ""filename"") + set_content(filename_element, joinpath(""."", ""config"", ""substrates.csv"")) + + #! ic cells + cell_ic_element = makeXMLPath(xml_doc, [""initial_conditions"", ""cell_positions""]) + using_cell_ics = isfile(joinpath(path_to_config_folder, ""cells.csv"")) + set_attributes(cell_ic_element; type=""csv"", enabled=string(using_cell_ics)) + folder_element = makeXMLPath(cell_ic_element, ""folder"") + set_content(folder_element, joinpath(""."", ""config"")) + filename_element = makeXMLPath(cell_ic_element, ""filename"") + set_content(filename_element, ""cells.csv"") + + #! ic ecm + using_ecm_ics = isfile(joinpath(path_to_config_folder, ""ecm.csv"")) + if using_ecm_ics + setECMSetupElement(xml_doc) + end + + #! ic dcs + dc_ic_element = makeXMLPath(xml_doc, [""microenvironment_setup"", ""options"", ""dirichlet_nodes""]) + using_dc_ics = isfile(joinpath(path_to_config_folder, ""dcs.csv"")) + set_attributes(dc_ic_element; type=""csv"", enabled=string(using_dc_ics)) + filename_element = makeXMLPath(dc_ic_element, ""filename"") + set_content(filename_element, joinpath(""config"", ""dcs.csv"")) + + #! rulesets + rules_element = makeXMLPath(xml_doc, [""cell_rules"", ""rulesets"", ""ruleset""]) + using_rules = isfile(joinpath(path_to_config_folder, ""cell_rules.csv"")) + set_attributes(rules_element; protocol=""CBHG"", version=""3.0"", format=""csv"", enabled=string(using_rules)) + folder_element = makeXMLPath(rules_element, ""folder"") + set_content(folder_element, joinpath(""."", ""config"")) + filename_element = makeXMLPath(rules_element, ""filename"") + set_content(filename_element, ""cell_rules.csv"") + + #! intracellulars + #! handled in exportIntracellular + + save_file(xml_doc, path_to_config) + free(xml_doc) + return true +end + +"""""" + setECMSetupElement(xml_doc::XMLDocument) + +Set up the ECM element in the XML document to support the ECM module. +"""""" +function setECMSetupElement(xml_doc::XMLDocument) + ecm_setup_element = makeXMLPath(xml_doc, [""microenvironment_setup"", ""ecm_setup""]) + set_attributes(ecm_setup_element; enabled=""true"", format=""csv"") + folder_element = makeXMLPath(ecm_setup_element, ""folder"") + set_content(folder_element, joinpath(""."", ""config"")) + filename_element = makeXMLPath(ecm_setup_element, ""filename"") + set_content(filename_element, ""ecm.csv"") + return +end + +"""""" + revertCustomModules(export_folder::AbstractString, physicell_version::AbstractString) + +Revert the custom modules in the export folder to the given PhysiCell version. +"""""" +function revertCustomModules(export_folder::AbstractString, physicell_version::AbstractString) + path_to_custom_modules = joinpath(export_folder, ""custom_modules"") + success = revertCustomHeader(path_to_custom_modules, physicell_version) + success &= revertCustomCPP(path_to_custom_modules, physicell_version) + return success +end + +"""""" + revertCustomHeader(path_to_custom_modules::AbstractString, physicell_version::AbstractString) + +Revert the custom header file in the export folder to the given PhysiCell version. +"""""" +function revertCustomHeader(::AbstractString, ::AbstractString) + return true #! nothing to do as of yet for the custom header +end + +"""""" + revertCustomCPP(path_to_custom_modules::AbstractString, physicell_version::AbstractString) + +Revert the custom cpp file in the export folder to the given PhysiCell version. +"""""" +function revertCustomCPP(path_to_custom_modules::AbstractString, ::AbstractString) + path_to_custom_cpp = joinpath(path_to_custom_modules, ""custom.cpp"") + lines = readlines(path_to_custom_cpp) + idx = findfirst(contains(""load_initial_cells();""), lines) + + lines[idx] = "" load_cells_from_pugixml();"" + + idx = findfirst(contains(""setup_behavior_rules()""), lines) + if !isnothing(idx) + lines[idx] = "" setup_cell_rules();"" + end + + open(path_to_custom_cpp, ""w"") do io + for line in lines + println(io, line) + end + end + return true +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/recorder.jl",".jl","2094","46",""""""" + recordConstituentIDs(T::Type{<:AbstractTrial}, id::Int, ids::Array{Int}) + recordConstituentIDs(T::AbstractTrial, ids::Array{Int}) + +Record the IDs of the constituents of an [`AbstractTrial`](@ref) object in a CSV file. +"""""" +function recordConstituentIDs(T::Type{<:AbstractTrial}, id::Int, ids::Array{Int}) + path_to_folder = trialFolder(T, id) + mkpath(path_to_folder) + path_to_csv = joinpath(path_to_folder, constituentTypeFilename(T)) + lines_table = compressIDs(ids) + CSV.write(path_to_csv, lines_table; header=false) +end + +recordConstituentIDs(T::AbstractTrial, ids::Array{Int}) = recordConstituentIDs(typeof(T), T.id, ids) + +################## Compression Functions ################## + +"""""" + compressIDs(ids::AbstractArray{Int}) + +Compress a list of IDs into a more compact representation by grouping consecutive IDs together. +"""""" +function compressIDs(ids::AbstractArray{Int}) + ids = ids |> vec |> unique |> sort + lines = String[] + while !isempty(ids) #! while there are still ids to compress + if length(ids) == 1 #! if there's only one id left + next_line = string(ids[1]) #! just add it to the list + popfirst!(ids) #! and remove it from the list of ids + else #! if there's more than one id left + I = findfirst(diff(ids) .!= 1) #! find the first index where the difference between consecutive ids is greater than 1 + I = isnothing(I) ? length(ids) : I #! if none found, then all the diffs are 1 so we want to take the entire list + if I > 1 #! if compressing multiple ids + next_line = ""$(ids[1]):$(ids[I])"" #! add the first and last id separated by a colon + ids = ids[I+1:end] #! remove the ids that were just compressed + else #! if only compressing one id + next_line = string(ids[1]) #! just add the id to the list + popfirst!(ids) #! and remove it from the list of ids + end + end + push!(lines, next_line) #! add the compressed id(s) to the list of lines + end + return Tables.table(lines) +end +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/loader.jl",".jl","35898","859","using DataFrames, MAT, Graphs, MetaGraphsNext, Dates + +export cellDataSequence, getCellDataSequence, PhysiCellSnapshot, PhysiCellSequence, + loadCells!, loadSubstrates!, loadMesh!, loadGraph! + +"""""" + AbstractPhysiCellSequence + +Abstract type representing either a single snapshot or a sequence of snapshots from a PhysiCell simulation. +"""""" +abstract type AbstractPhysiCellSequence end + +"""""" + PhysiCellSnapshot + +A single snapshot of a PhysiCell simulation. + +The `cells`, `substrates`, `mesh`, and graphs (`attachments`, `spring_attachments`, `neighbors`) fields may remain empty until they are needed for analysis or explicitly loaded by the user. + +# Constructors +- `PhysiCellSnapshot(simulation_id::Int, index::Union{Integer, Symbol}, labels::Vector{String}=String[], substrate_names::Vector{String}=String[]; kwargs...)` +- `PhysiCellSnapshot(simulation::Simulation, args...; kwargs...)` + +# Fields +- `simulation_id::Int`: The ID of the simulation. +- `index::Union{Int,Symbol}`: The index of the snapshot. Can be an integer or a symbol (`:initial` or `:final`). +- `time::Float64`: The time of the snapshot (in minutes). +- `runtime::Nanosecond`: The runtime to reach this snapshot (in nanoseconds). +- `cells::DataFrame`: A DataFrame containing cell data. +- `substrates::DataFrame`: A DataFrame containing substrate data. +- `mesh::Dict{String, Vector{Float64}}`: A dictionary containing mesh data. +- `attachments::MetaGraph`: A graph of cell attachment data with vertices labeled by cell IDs. +- `spring_attachments::MetaGraph`: A graph of spring attachment data with vertices labeled by cell IDs. +- `neighbors::MetaGraph`: A graph of cell neighbor data with vertices labeled by cell IDs. + +# Optional Arguments +- `labels::Vector{String}=String[]`: A vector of cell data labels. Users should let PhysiCellModelManager.jl load this. +- `substrate_names::Vector{String}=String[]`: A vector of substrate names. Users should let PhysiCellModelManager.jl load this. + +# Keyword Arguments +- `include_cells::Bool=false`: Whether to load cell data. +- `cell_type_to_name_dict::Dict{Int, String}=Dict{Int, String}()`: A dictionary mapping cell type IDs to cell type names. +- `include_substrates::Bool=false`: Whether to load substrate data. +- `include_mesh::Bool=false`: Whether to load mesh data. +- `include_attachments::Bool=false`: Whether to load attachment data. +- `include_spring_attachments::Bool=false`: Whether to load spring attachment data. +- `include_neighbors::Bool=false`: Whether to load neighbor data. + +# Examples +```julia +simulation_id = 1 +index = 3 # index of the snapshot in the output folder +snapshot = PhysiCellSnapshot(simulation_id, index) + +simulation = Simulation(simulation_id) +index = :initial # :initial or :final are the accepted symbols +snapshot = PhysiCellSnapshot(simulation, index) + +# Load with specific data types +snapshot = PhysiCellSnapshot(simulation_id, index; include_cells=true, include_substrates=true) +``` +"""""" +struct PhysiCellSnapshot <: AbstractPhysiCellSequence + simulation_id::Int + index::Union{Int,Symbol} + time::Float64 + runtime::Nanosecond + cells::DataFrame + substrates::DataFrame + mesh::Dict{String,Vector{Float64}} + attachments::MetaGraph + spring_attachments::MetaGraph + neighbors::MetaGraph +end + +function PhysiCellSnapshot(simulation_id::Int, index::Union{Integer, Symbol}, + labels::Vector{String}=String[], + substrate_names::Vector{String}=String[]; + include_cells::Bool=false, + cell_type_to_name_dict::Dict{Int, String}=Dict{Int, String}(), + include_substrates::Bool=false, + include_mesh::Bool=false, + include_attachments::Bool=false, + include_spring_attachments::Bool=false, + include_neighbors::Bool=false) + + assertInitialized() + filepath_base = pathToOutputFileBase(simulation_id, index) + path_to_xml = joinpath(""$(filepath_base).xml"") + if !isfile(path_to_xml) + println(""Could not find file $path_to_xml. Returning missing."") + return missing + end + xml_doc = parse_file(""$(filepath_base).xml"") + time = getSimpleContent(xml_doc, [""metadata"",""current_time""]) |> x->parse(Float64, x) + seconds_to_nanoseconds = x -> round(x * 1e9) |> Nanosecond + runtime = getSimpleContent(xml_doc, [""metadata"", ""current_runtime""]) |> x -> parse(Float64, x) |> seconds_to_nanoseconds + cells = DataFrame() + if include_cells + if _loadCells!(cells, filepath_base, cell_type_to_name_dict, labels) |> ismissing + println(""Could not load cell data for snapshot $(index) of simulation $simulation_id. Returning missing."") + return missing + end + end + substrates = DataFrame() + if include_substrates + if _loadSubstrates!(substrates, filepath_base, substrate_names) |> ismissing + println(""Could not load substrate data for snapshot $(index) of simulation $simulation_id. Returning missing."") + return missing + end + end + mesh = Dict{String, Vector{Float64}}() + if include_mesh + _loadMesh!(mesh, xml_doc) + end + + attachments = physicellEmptyGraph() + if include_attachments + if _loadGraph!(attachments, ""$(filepath_base)_attached_cells_graph.txt"") |> ismissing + println(""Could not load attachments for snapshot $(index) of simulation $simulation_id. Returning missing."") + return missing + end + end + + spring_attachments = physicellEmptyGraph() + if include_spring_attachments + if _loadGraph!(spring_attachments, ""$(filepath_base)_spring_attached_cells_graph.txt"") |> ismissing + println(""Could not load spring attachments for snapshot $(index) of simulation $simulation_id. Returning missing."") + return missing + end + end + + neighbors = physicellEmptyGraph() + if include_neighbors + if _loadGraph!(neighbors, ""$(filepath_base)_cell_neighbor_graph.txt"") |> ismissing + println(""Could not load neighbors for snapshot $(index) of simulation $simulation_id. Returning missing."") + return missing + end + end + free(xml_doc) + return PhysiCellSnapshot(simulation_id, index, time, runtime, DataFrame(cells), substrates, mesh, attachments, spring_attachments, neighbors) +end + +PhysiCellSnapshot(simulation::Simulation, index::Union{Integer,Symbol}, args...; kwargs...) = PhysiCellSnapshot(simulation.id, index, args...; kwargs...) + +function Base.show(io::IO, snapshot::PhysiCellSnapshot) + println(io, ""PhysiCellSnapshot (SimID=$(snapshot.simulation_id), Index=$(snapshot.index))"") + println(io, "" Time: $(snapshot.time)"") + println(io, "" Current runtime: $(canonicalize(snapshot.runtime))"") + println(io, "" Cells: $(isempty(snapshot.cells) ? ""NOT LOADED"" : ""($(nrow(snapshot.cells)) cells x $(ncol(snapshot.cells)) features) DataFrame"")"") + println(io, "" Substrates: $(isempty(snapshot.substrates) ? ""NOT LOADED"" : ""($(size(snapshot.substrates, 1)) voxels x [x, y, z, volume, $(size(snapshot.substrates, 2)-4) substrates]) DataFrame"")"") + println(io, "" Mesh: $(isempty(snapshot.mesh) ? ""NOT LOADED"" : meshInfo(snapshot))"") + println(io, "" Attachments: $(nv(snapshot.attachments)==0 ? ""NOT LOADED"" : graphInfo(snapshot.attachments))"") + println(io, "" Spring Attachments: $(nv(snapshot.spring_attachments)==0 ? ""NOT LOADED"" : graphInfo(snapshot.spring_attachments))"") + println(io, "" Neighbors: $(nv(snapshot.neighbors)==0 ? ""NOT LOADED"" : graphInfo(snapshot.neighbors))"") +end + +"""""" + indexToFilename(index) + +Convert an index to a filename in the output folder. + +The index can be an integer or a symbol (`:initial` or `:final`). + +```jldoctest +julia> PhysiCellModelManager.indexToFilename(0) +""output00000000"" +``` +```jldoctest +julia> PhysiCellModelManager.indexToFilename(:initial) +""initial"" +``` +"""""" +function indexToFilename(index::Symbol) + @assert index in [:initial, :final] ""The non-integer index must be either :initial or :final"" + return string(index) +end + +indexToFilename(index::Int) = ""output$(lpad(index,8,""0""))"" + +"""""" + AgentID + +A wrapper for the agent ID used in PhysiCell. + +The purpose of this struct is to make it easier to interpret the data in the MetaGraphs loaded from PhysiCell. +The MetaGraphs use `Int`s to index the vertices, which could cause confusion when looking at the mappings to the agent ID metadata if also using `Int`s. +"""""" +struct AgentID + id::Int +end + +Base.parse(::Type{AgentID}, s::AbstractString) = AgentID(parse(Int, s)) + +"""""" + AgentDict{T} <: AbstractDict{AgentID,T} + +A dictionary-like structure that maps `AgentID`s to values of type `T`. +Integers can be passed as keys and they will be converted to `AgentID`s. +"""""" +struct AgentDict{T} <: AbstractDict{AgentID,T} + dict::Dict{AgentID,T} + + function AgentDict(d::Dict{AgentID,T}) where T + return new{T}(d) + end + + function AgentDict(d::Dict{<:Integer,T}) where T + return AgentDict([AgentID(k) => v for (k, v) in d]) + end + + function AgentDict(ps::Vector{<:Pair{AgentID,T}}) where T + return AgentDict(Dict{AgentID,T}(ps)) + end + + function AgentDict(ps::Vector{<:Pair{<:Integer,T}}) where {T} + return AgentDict([AgentID(k) => v for (k, v) in ps]) + end +end + +#! functions to make AgentDict work like a normal dictionary +Base.getindex(d::AgentDict, args...) = getindex(d.dict, args...) +Base.length(d::AgentDict) = length(d.dict) +Base.iterate(d::AgentDict, args...) = iterate(d.dict, args...) +Base.haskey(d::AgentDict, k::AgentID) = haskey(d.dict, k) +Base.setindex!(d::AgentDict, v, k::AgentID) = setindex!(d.dict, v, k) +Base.delete!(d::AgentDict, k::AgentID) = delete!(d.dict, k) + +#! allow users to use integers as keys +Base.getindex(d::AgentDict, k::Integer) = d.dict[AgentID(k)] +Base.haskey(d::AgentDict, k::Integer) = haskey(d.dict, AgentID(k)) +Base.setindex!(d::AgentDict, v, k::Integer) = setindex!(d.dict, v, AgentID(k)) +Base.delete!(d::AgentDict, k::Integer) = delete!(d.dict, AgentID(k)) + +"""""" + physicellEmptyGraph() + +Create an empty graph for use with PhysiCell. + +For all PhysiCell graphs, the vertices are labeled with `AgentID`s and the vertices carry no other information. +The edges also carry no extra information other than that the edge exists. +"""""" +function physicellEmptyGraph() + return MetaGraph(SimpleDiGraph(); + label_type=AgentID, + vertex_data_type=Nothing, + edge_data_type=Nothing) +end + +"""""" + readPhysiCellGraph!(g::MetaGraph, path_to_txt_file::String) + +Read a PhysiCell graph from a text file into a MetaGraph. + +Users should use [`loadGraph!`](@ref) instead of this function directly. +"""""" +function readPhysiCellGraph!(g::MetaGraph, path_to_txt_file::String) + lines = readlines(path_to_txt_file) + for line in lines + cell_id, attached_ids = split(line, "": "") + cell_id = parse(AgentID, cell_id) + g[cell_id] = nothing + if attached_ids == """" + continue + end + for attached_id in split(attached_ids, "","") + attached_id = parse(AgentID, attached_id) + g[attached_id] = nothing + g[cell_id, attached_id] = nothing + end + end +end + +"""""" + PhysiCellSequence + +A sequence of PhysiCell snapshots. + +By default, only the simulation ID, index, and time are recorded for each PhysiCellSnapshot in the sequence. +To include any of `cells`, `substrates`, `mesh`, `attachments`, `spring_attachments`, or `neighbors`, pass in the corresponding keyword argument as `true` (see below). + +# Fields +- `simulation_id::Int`: The ID of the simulation. +- `snapshots::Vector{PhysiCellSnapshot}`: A vector of PhysiCell snapshots. +- `cell_type_to_name_dict::Dict{Int, String}`: A dictionary mapping cell type IDs to cell type names. +- `labels::Vector{String}`: A vector of cell data labels. +- `substrate_names::Vector{String}`: A vector of substrate names. + +# Examples +```julia +sequence = PhysiCellSequence(1; include_cells=true, include_substrates=true) # loads cell and substrate data for simulation ID 1 +sequence = PhysiCellSequence(simulation; include_attachments=true, include_spring_attachments=true) # loads attachment data for a Simulation object +sequence = PhysiCellSequence(1; include_mesh=true, include_neighbors=true) # loads mesh and neighbor data for simulation ID 1 +``` +"""""" +struct PhysiCellSequence <: AbstractPhysiCellSequence + simulation_id::Int + snapshots::Vector{PhysiCellSnapshot} + cell_type_to_name_dict::Dict{Int,String} + labels::Vector{String} + substrate_names::Vector{String} +end + +function PhysiCellSequence(simulation_id::Integer; + include_cells::Bool=false, + include_substrates::Bool=false, + include_mesh::Bool=false, + include_attachments::Bool=false, + include_spring_attachments::Bool=false, + include_neighbors::Bool=false) + + assertInitialized() + path_to_xml = pathToOutputXML(simulation_id, :initial) + cell_type_to_name_dict = cellTypeToNameDict(path_to_xml) + if isempty(cell_type_to_name_dict) + println(""Could not find cell type information in $path_to_xml. This means that there is no initial.xml file, possibly due to pruning. Returning missing."") + return missing + end + labels = cellLabels(path_to_xml) + substrate_names = include_substrates ? substrateNames(path_to_xml) : String[] + index_to_snapshot = index -> PhysiCellSnapshot(simulation_id, index, labels, substrate_names; + include_cells=include_cells, + cell_type_to_name_dict=cell_type_to_name_dict, + include_substrates=include_substrates, + include_mesh=include_mesh, + include_attachments=include_attachments, + include_spring_attachments=include_spring_attachments, + include_neighbors=include_neighbors) + + snapshots = PhysiCellSnapshot[] + index = 0 + while isfile(pathToOutputXML(simulation_id, index)) + push!(snapshots, index_to_snapshot(index)) + index += 1 + end + return PhysiCellSequence(simulation_id, snapshots, cell_type_to_name_dict, labels, substrate_names) +end + +PhysiCellSequence(simulation::Simulation; kwargs...) = PhysiCellSequence(simulation.id; kwargs...) + +function Base.show(io::IO, sequence::PhysiCellSequence) + println(io, ""PhysiCellSequence (SimID=$(sequence.simulation_id))"") + println(io, "" #Snapshots: $(length(sequence.snapshots))"") + println(io, "" Cell Types: $(join(values(sequence.cell_type_to_name_dict), "", ""))"") + println(io, "" Substrates: $(join(sequence.substrate_names, "", ""))"") + loadMesh!(sequence.snapshots[1]) + println(io, "" Mesh: $(meshInfo(sequence))"") +end + +"""""" + pathToOutputFolder(simulation_id::Integer) + +Return the path to the output folder for a PhysiCell simulation. +"""""" +pathToOutputFolder(simulation_id::Integer) = joinpath(trialFolder(Simulation, simulation_id), ""output"") + +"""""" + pathToOutputFileBase(simulation_id::Integer, index::Union{Integer,Symbol}) + +Return the path to the output files for a snapshot of a PhysiCell simulation, i.e., everything but the file extension. +"""""" +pathToOutputFileBase(simulation_id::Integer, index::Union{Integer,Symbol}) = joinpath(pathToOutputFolder(simulation_id), indexToFilename(index)) + +"""""" + pathToOutputFileBase(snapshot::PhysiCellSnapshot) + +Return the path to the output files for a snapshot of a PhysiCell simulation, i.e., everything but the file extension. +"""""" +pathToOutputFileBase(snapshot::PhysiCellSnapshot) = pathToOutputFileBase(snapshot.simulation_id, snapshot.index) + +"""""" + pathToOutputXML(simulation_id::Integer, index::Union{Integer,Symbol}=:initial) + +Return the path to the XML output file for a snapshot of a PhysiCell simulation. +Can also pass in a `Simulation` object for the first argument. +"""""" +pathToOutputXML(simulation_id::Integer, index::Union{Integer,Symbol}=:initial) = ""$(pathToOutputFileBase(simulation_id, index)).xml"" + +pathToOutputXML(simulation::Simulation, index::Union{Integer,Symbol}=:initial) = pathToOutputXML(simulation.id, index) + +"""""" + pathToOutputXML(snapshot::PhysiCellSnapshot) + +Return the path to the XML output file for a snapshot of a PhysiCell simulation. +"""""" +pathToOutputXML(snapshot::PhysiCellSnapshot) = pathToOutputXML(snapshot.simulation_id, snapshot.index) + +"""""" + cellLabels(simulation::Simulation) + +Return the labels from the XML file for a PhysiCell simulation, i.e., the names of the cell data fields. + +# Arguments +- `simulation`: The simulation object. Can also use the simulation ID, an [`AbstractPhysiCellSequence`](@ref), `XMLDocument`, or the path to the XML file (`String`). +"""""" +function cellLabels(path_to_file::String) + if !isfile(path_to_file) + return String[] + end + xml_doc = parse_file(path_to_file) + labels = cellLabels(xml_doc) + free(xml_doc) + return labels +end + +function cellLabels(xml_doc::XMLDocument) + labels = String[] + xml_path = [""cellular_information"", ""cell_populations"", ""cell_population"", ""custom"", ""simplified_data"", ""labels""] + labels_element = retrieveElement(xml_doc, xml_path; required=true) + + for label in child_elements(labels_element) + label_name = content(label) + label_ind_width = attribute(label, ""size""; required=true) |> x -> parse(Int, x) + if label_ind_width > 1 + label_name = [label_name * ""_$i"" for i in 1:label_ind_width] + append!(labels, label_name) + else + if label_name == ""elapsed_time_in_phase"" && label_name in labels + label_name = ""elapsed_time_in_phase_2"" #! hack to get around a MultiCellDS duplicate? + end + push!(labels, label_name) + end + end + return labels +end + +cellLabels(snapshot::PhysiCellSnapshot) = pathToOutputXML(snapshot) |> cellLabels +cellLabels(sequence::PhysiCellSequence) = sequence.labels +cellLabels(simulation_id::Integer) = cellLabels(pathToOutputXML(simulation_id, :initial)) +cellLabels(simulation::Simulation) = cellLabels(simulation.id) + +"""""" + cellTypeToNameDict(simulation::Simulation) + +Return a dictionary mapping cell type IDs to cell type names from the simulation. + +# Arguments +- `simulation`: The simulation object. Can also use the simulation ID, an [`AbstractPhysiCellSequence`](@ref), `XMLDocument`, or the path to the XML file (`String`). +"""""" +function cellTypeToNameDict(path_to_file::String) + if !isfile(path_to_file) + return Dict{Int,String}() + end + xml_doc = parse_file(path_to_file) + cell_type_to_name_dict = cellTypeToNameDict(xml_doc) + free(xml_doc) + return cell_type_to_name_dict +end + +function cellTypeToNameDict(xml_doc::XMLDocument) + cell_type_to_name_dict = Dict{Int, String}() + xml_path = [""cellular_information"", ""cell_populations"", ""cell_population"", ""custom"", ""simplified_data"", ""cell_types""] + cell_types_element = retrieveElement(xml_doc, xml_path; required=true) + + for cell_type_element in child_elements(cell_types_element) + cell_type_id = attribute(cell_type_element, ""ID""; required=true) |> x -> parse(Int, x) + cell_type_name = content(cell_type_element) + cell_type_to_name_dict[cell_type_id] = cell_type_name + end + return cell_type_to_name_dict +end + +cellTypeToNameDict(snapshot::PhysiCellSnapshot) = pathToOutputXML(snapshot) |> cellTypeToNameDict +cellTypeToNameDict(sequence::PhysiCellSequence) = sequence.cell_type_to_name_dict +cellTypeToNameDict(simulation_id::Integer) = cellTypeToNameDict(pathToOutputXML(simulation_id, :initial)) +cellTypeToNameDict(simulation::Simulation) = cellTypeToNameDict(simulation.id) + +"""""" + substrateNames(simulation::Simulation) + +Return the names of the substrates from the simulation. + +# Arguments +- `simulation`: The simulation object. Can also use the simulation ID, an [`AbstractPhysiCellSequence`](@ref), `XMLDocument`, or the path to the XML file (`String`). +"""""" +function substrateNames(path_to_file::String) + if !isfile(path_to_file) + return String[] + end + xml_doc = parse_file(path_to_file) + substrate_names = substrateNames(xml_doc) + free(xml_doc) + return substrate_names +end + +function substrateNames(xml_doc::XMLDocument) + xml_path = [""microenvironment"", ""domain"", ""variables""] + variables_element = retrieveElement(xml_doc, xml_path; required=true) + substrate_dict = Dict{Int, String}() + for element in child_elements(variables_element) + if name(element) != ""variable"" + continue + end + variable_id = attribute(element, ""ID""; required=true) |> x -> parse(Int, x) + substrate_name = attribute(element, ""name""; required=true) + substrate_dict[variable_id] = substrate_name + end + substrate_names = String[] + for i in (substrate_dict |> keys |> collect |> sort) + push!(substrate_names, substrate_dict[i]) + end + return substrate_names +end + +substrateNames(snapshot::PhysiCellSnapshot) = pathToOutputXML(snapshot) |> substrateNames +substrateNames(sequence::PhysiCellSequence) = sequence.substrate_names +substrateNames(simulation_id::Integer) = substrateNames(pathToOutputXML(simulation_id, :initial)) +substrateNames(simulation::Simulation) = substrateNames(simulation.id) + +"""""" + _loadCells!(cells::DataFrame, filepath_base::String, cell_type_to_name_dict::Dict{Int, String}=Dict{Int, String}(), labels::Vector{String}=String[]) + +Internal function to load cell data into a DataFrame associated with an [`AbstractPhysiCellSequence`](@ref) object. +"""""" +function _loadCells!(cells::DataFrame, filepath_base::String, cell_type_to_name_dict::Dict{Int, String}=Dict{Int, String}(), labels::Vector{String}=String[]) + if !isempty(cells) + return + end + + if isempty(labels) || isempty(cell_type_to_name_dict) + xml_doc = parse_file(""$(filepath_base).xml"") + if isempty(labels) + labels = cellLabels(xml_doc) + end + if isempty(cell_type_to_name_dict) + cell_type_to_name_dict = cellTypeToNameDict(xml_doc) + end + free(xml_doc) + + #! confirm that these were both found + @assert !isempty(labels) && !isempty(cell_type_to_name_dict) ""Could not find cell type information and/or labels in $(filepath_base).xml"" + end + + mat_file = ""$(filepath_base)_cells.mat"" + if !isfile(mat_file) + println(""When loading cells, could not find file $mat_file. Returning missing."") + return missing + end + A = matread(mat_file)[""cells""] + conversion_dict = Dict(""ID"" => Int, ""dead"" => Bool, ""cell_type"" => Int) + for (label, row) in zip(labels, eachrow(A)) + if label in keys(conversion_dict) + cells[!, label] = convert.(conversion_dict[label], row) + else + cells[!, label] = row + end + end + cells[!, :cell_type_name] = [cell_type_to_name_dict[ct] for ct in cells[!, :cell_type]] + return +end + +"""""" + loadCells!(S::AbstractPhysiCellSequence[, cell_type_to_name_dict::Dict{Int, String}=Dict{Int, String}(), labels::Vector{String}=String[]]) + +Load the cell data for a PhysiCell simulation into an [`AbstractPhysiCellSequence`](@ref) object. + +If the `cell_type_to_name_dict` and `labels` are not provided, they will be loaded from the XML file. +Users do not need to compute and pass these in. + +# Arguments +- `S::AbstractPhysiCellSequence`: The sequence or snapshot to load the cell data into. +- `cell_type_to_name_dict::Dict{Int, String}=Dict{Int, String}()`: A dictionary mapping cell type IDs to cell type names. If not provided, it will be loaded from the XML file. +- `labels::Vector{String}=String[]`: A vector of cell data labels. If not provided, they will be loaded from the XML file. + +# Examples +```julia +simulation = Simulation(1) +sequence = PhysiCellSequence(simulation) # does not load cell data without setting `PhysiCellSequence(simulation; include_cells=true)` +loadCells!(sequence) +``` +"""""" +function loadCells!(snapshot::PhysiCellSnapshot, cell_type_to_name_dict::Dict{Int, String}=Dict{Int, String}(), labels::Vector{String}=String[]) + _loadCells!(snapshot.cells, pathToOutputFileBase(snapshot), cell_type_to_name_dict, labels) +end + +function loadCells!(sequence::PhysiCellSequence) + cell_type_to_name_dict = cellTypeToNameDict(sequence) + labels = cellLabels(sequence) + for snapshot in sequence.snapshots + loadCells!(snapshot, cell_type_to_name_dict, labels) + end +end + +"""""" + _loadSubstrates!(substrates::DataFrame, filepath_base::String, substrate_names::Vector{String}=String[]) + +Internal function to load substrate data into a DataFrame associated with an [`AbstractPhysiCellSequence`](@ref) object. +"""""" +function _loadSubstrates!(substrates::DataFrame, filepath_base::String, substrate_names::Vector{String}) + if !isempty(substrates) + return + end + + if isempty(substrate_names) + substrate_names = ""$(filepath_base).xml"" |> substrateNames + @assert !isempty(substrate_names) ""Could not find substrate names in $(filepath_base).xml"" + end + + mat_file = ""$(filepath_base)_microenvironment0.mat"" + if !isfile(mat_file) + println(""When loading substrates, could not find file $mat_file. Returning missing."") + return missing + end + A = matread(mat_file)[""multiscale_microenvironment""] + col_names = [:x; :y; :z; :volume; substrate_names] + for (col_name, row) in zip(col_names, eachrow(A)) + substrates[!, col_name] = row + end +end + +"""""" + loadSubstrates!(S::AbstractPhysiCellSequence[, substrate_names::Vector{String}=String[]]) + +Load the substrate data for a PhysiCell simulation into an [`AbstractPhysiCellSequence`](@ref) object. + +If the `substrate_names` are not provided, they will be loaded from the XML file. +Users do not need to compute and pass these in. + +# Arguments +- `S::AbstractPhysiCellSequence`: The sequence or snapshot to load the substrate data into. +- `substrate_names::Vector{String}=String[]`: The names of the substrates to load. If not provided, they will be loaded from the XML file. +"""""" +function loadSubstrates!(snapshot::PhysiCellSnapshot, substrate_names::Vector{String}=String[]) + _loadSubstrates!(snapshot.substrates, pathToOutputFileBase(snapshot), substrate_names) +end + +function loadSubstrates!(sequence::PhysiCellSequence) + for snapshot in sequence.snapshots + loadSubstrates!(snapshot, sequence.substrate_names) + end +end + +"""""" + _loadMesh!(mesh::Dict{String, Vector{Float64}}, xml_doc::XMLDocument) + +Internal function to load mesh data into a dictionary associated with an [`AbstractPhysiCellSequence`](@ref) object. +"""""" +function _loadMesh!(mesh::Dict{String, Vector{Float64}}, xml_doc::XMLDocument) + if !isempty(mesh) + return + end + xml_path = [""microenvironment"", ""domain"", ""mesh""] + mesh_element = retrieveElement(xml_doc, xml_path; required=true) + mesh[""bounding_box""] = parse.(Float64, split(content(find_element(mesh_element, ""bounding_box"")), "" "")) + for tag in [""x_coordinates"", ""y_coordinates"", ""z_coordinates""] + coord_element = find_element(mesh_element, tag) + mesh[string(tag[1])] = parse.(Float64, split(content(coord_element), attribute(coord_element, ""delimiter""; required=true))) + end +end + +"""""" + loadMesh!(S::AbstractPhysiCellSequence) + +Load the mesh data for a PhysiCell simulation into an [`AbstractPhysiCellSequence`](@ref) object. + +# Arguments +- `S::AbstractPhysiCellSequence`: The sequence or snapshot to load the mesh data into. +"""""" +function loadMesh!(snapshot::PhysiCellSnapshot) + path_to_file = pathToOutputXML(snapshot) + @assert isfile(path_to_file) ""Could not find file $path_to_file. However, snapshot required this file to be created."" + xml_doc = parse_file(path_to_file) + _loadMesh!(snapshot.mesh, xml_doc) + free(xml_doc) + return +end + +function loadMesh!(sequence::PhysiCellSequence) + for snapshot in sequence.snapshots + loadMesh!(snapshot) + end +end + +"""""" + meshInfo(S::AbstractPhysiCellSequence) + +Return a string describing the mesh for an [`AbstractPhysiCellSequence`](@ref) object. +"""""" +function meshInfo(snapshot::PhysiCellSnapshot) + mesh = snapshot.mesh + grid_size = [length(mesh[k]) for k in [""x"", ""y"", ""z""] if length(mesh[k]) > 1] + domain_size = [[mesh[k][1], mesh[k][end]] + 0.5*(mesh[k][2] - mesh[k][1]) * [-1, 1] for k in [""x"", ""y"", ""z""] if length(mesh[k]) > 1] + return ""$(join(grid_size, "" x "")) grid on $(join(domain_size, "" x ""))"" +end + +meshInfo(sequence::PhysiCellSequence) = meshInfo(sequence.snapshots[1]) + +"""""" + _loadGraph!(G::MetaGraph, path_to_txt_file::String) + +Load a graph from a text file into a `MetaGraph`. + +Users should use `loadGraph!` with an [`AbstractPhysiCellSequence`](@ref) object instead of this function directly.` +"""""" +function _loadGraph!(G::MetaGraph, path_to_txt_file::String) + if nv(G) > 0 #! If the graph is already loaded, do nothing + return + end + if !isfile(path_to_txt_file) + println(""When loading graph, could not find file $path_to_txt_file. Returning missing."") + return missing + end + readPhysiCellGraph!(G, path_to_txt_file) +end + +"""""" + loadGraph!(S::AbstractPhysiCellSequence, graph::Symbol) + +Load a graph for a snapshot or sequence into a MetaGraph(s). + +# Arguments +- `S::AbstractPhysiCellSequence`: The [`AbstractPhysiCellSequence`](@ref) object to load the graph into. +- `graph`: The type of graph to load (must be one of `:attachments`, `:spring_attachments`, or `:neighbors`). Can also be a string. +"""""" +function loadGraph!(snapshot::PhysiCellSnapshot, graph::Symbol) + @assert graph in [:attachments, :spring_attachments, :neighbors] ""Graph must be one of [:attachments, :spring_attachments, :neighbors]"" + if graph == :attachments + path_to_txt_file = pathToOutputFileBase(snapshot) * ""_attached_cells_graph.txt"" + elseif graph == :spring_attachments + path_to_txt_file = pathToOutputFileBase(snapshot) * ""_spring_attached_cells_graph.txt"" + elseif graph == :neighbors + path_to_txt_file = pathToOutputFileBase(snapshot) * ""_cell_neighbor_graph.txt"" + end + _loadGraph!(getfield(snapshot, graph), path_to_txt_file) +end + +function loadGraph!(sequence::PhysiCellSequence, graph::Symbol) + for snapshot in sequence.snapshots + loadGraph!(snapshot, graph) + end +end + +loadGraph!(S::AbstractPhysiCellSequence, graph::String) = loadGraph!(S, Symbol(graph)) + +"""""" + graphInfo(g::MetaGraph) + +Return a string describing the graph. + +Used for printing the graph information in the `show` function. +"""""" +function graphInfo(g::MetaGraph) + return ""directed graph with $(nv(g)) vertices and $(ne(g)) edges"" +end + +"""""" + cellDataSequence(simulation_id::Integer, labels::Vector{String}; include_dead::Bool=false, include_cell_type_name::Bool=false) + +Return an [`AgentDict`](@ref) where the keys are cell IDs from the PhysiCell simulation and the values are NamedTuples containing the time and the values of the specified labels for that cell. + +For scalar values, such as `volume`, the values are in a length `N` vector, where `N` is the number of snapshots in the simulation. +In the case of a label that has multiple columns, such as `position`, the values are concatenated into a length(snapshots) x number of columns array. +Note: If doing multiple calls to this function, it is recommended to use the `PhysiCellSequence` object so that all the data is loaded one time instead of once per call. + +# Arguments +- `simulation_id::Integer`: The ID of the PhysiCell simulation. Alternatively, can be a `Simulation` object or a `PhysiCellSequence` object. +- `labels::Vector{String}`: The labels to extract from the cell data. If a label has multiple columns, such as `position`, the columns are concatenated into a single array. Alternatively, a single label string can be passed. +- `include_dead::Bool=false`: Whether to include dead cells in the data. +- `include_cell_type_name::Bool=false`: Whether to include the cell type name in the data. Equivalent to including `\""cell_type_name\""` in `labels`. + +# Examples +``` +data = cellDataSequence(sequence, [""position"", ""elapsed_time_in_phase""]; include_dead=true, include_cell_type_name=true) +data[1] # the data for cell with ID 1 +data[1].position # an Nx3 array of the cell's position over time +data[1].elapsed_time_in_phase # an Nx1 array of the cell's elapsed time in phase over time +data[1].cell_type_name # an Nx1 array of the cell type name of the first cell over time +``` +"""""" +function cellDataSequence(simulation_id::Integer, labels::Vector{String}; kwargs...) + assertInitialized() + sequence = PhysiCellSequence(simulation_id) + return cellDataSequence(sequence, labels; kwargs...) +end + +function cellDataSequence(simulation_id::Integer, label::String; kwargs...) + return cellDataSequence(simulation_id, [label]; kwargs...) +end + +function cellDataSequence(simulation::Simulation, labels::Vector{String}; kwargs...) + sequence = PhysiCellSequence(simulation) + return cellDataSequence(sequence, labels; kwargs...) +end + +function cellDataSequence(simulation::Simulation, label::String; kwargs...) + return cellDataSequence(simulation, [label]; kwargs...) +end + +function cellDataSequence(sequence::PhysiCellSequence, label::String; kwargs...) + return cellDataSequence(sequence, [label]; kwargs...) +end + +function cellDataSequence(sequence::PhysiCellSequence, labels::Vector{String}; include_dead::Bool=false, include_cell_type_name::Bool=false) + loadCells!(sequence) + cell_features = cellLabels(sequence) + label_features = Symbol[] + temp_dict = Dict{Symbol, Vector{Symbol}}() + for label in labels + if label in cell_features + L = Symbol(label) + push!(label_features, L) + temp_dict[L] = [L] + else + index = 1 + while ""$(label)_$(index)"" in cell_features + index += 1 + end + @assert index > 1 ""Label $label not found in cell data"" + new_labels = [Symbol(""$(label)_$(i)"") for i in 1:(index-1)] + append!(label_features, new_labels) + temp_dict[Symbol(label)] = new_labels + end + end + labels = Symbol.(labels) + if include_cell_type_name && !(:cell_type_name in labels) + push!(labels, :cell_type_name) + push!(label_features, :cell_type_name) + temp_dict[:cell_type_name] = [:cell_type_name] + end + types = eltype.(eachcol(sequence.snapshots[1].cells)[label_features]) + data = Dict{Int, NamedTuple{(:time, label_features...), Tuple{Vector{Float64}, [Vector{type} for type in types]...}}}() + for snapshot in sequence.snapshots + for row in eachrow(snapshot.cells) + if !include_dead && row[:dead] + continue + end + if row.ID in keys(data) + push!(data[row.ID].time, snapshot.time) + for label_feature in label_features + push!(data[row.ID][label_feature], row[label_feature]) + end + else + data[row.ID] = NamedTuple{(:time, label_features...)}([[snapshot.time], [[row[label_feature]] for label_feature in label_features]...]) + end + end + end + + if all(length.(values(temp_dict)) .== 1) + return AgentDict(data) + end + C(v, label) = begin #! Concatenation of columns that belong together + if length(temp_dict[label]) == 1 + return v[temp_dict[label][1]] + end + return hcat(v[temp_dict[label]]...) + end + return [ID => NamedTuple{(:time, labels...)}([[v.time]; [C(v,label) for label in labels]]) for (ID, v) in data] |> AgentDict +end + +"""""" + getCellDataSequence(args...; kwargs...) + +Deprecated alias for [`cellDataSequence`](@ref). Use `cellDataSequence` instead. +"""""" +function getCellDataSequence(args...; kwargs...) + Base.depwarn(""`getCellDataSequence` is deprecated. Use `cellDataSequence` instead."", :getCellDataSequence; force=true) + return cellDataSequence(args...; kwargs...) +end +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/user_api.jl",".jl","7310","158","import Base.run + +export createTrial, run + +"""""" + createTrial([method=GridVariation()], inputs::InputFolders, avs::Vector{<:AbstractVariation}=AbstractVariation[]; + n_replicates::Integer=1, use_previous::Bool=true) + +Return an object of type `<:AbstractTrial` (simulation, monad, sampling, trial) with the given input folders and elementary variations. + +Uses the `avs` and `n_replicates` to determine whether to create a simulation, monad, or sampling. +Despite its name, trials cannot yet be created by this function. +If `n_replicates` is 0, and each variation has a single value, a simulation will be created. + +By default, the `method` is `GridVariation()`, which creates a grid of variations from the vector `avs`. +Other methods are: [`LHSVariation`](@ref), [`SobolVariation`](@ref), and [`RBDVariation`](@ref). + +Alternate forms (all work with the optional `method` argument in the first position): +Only supplying a single `AbstractVariation`: +``` +createTrial(inputs::InputFolders, av::AbstractVariation; n_replicates::Integer=1, use_previous::Bool=true) +``` +Using a reference simulation or monad: +``` +createTrial(reference::AbstractMonad, avs::Vector{<:AbstractVariation}=AbstractVariation[]; n_replicates::Integer=1, + use_previous::Bool=true) +``` +``` +createTrial(reference::AbstractMonad, av::AbstractVariation; n_replicates::Integer=1, use_previous::Bool=true) +``` +Using a `PCMMOutput` holding a simulation or monad: +``` +createTrial(output_ref::PCMMOutput{<:AbstractMonad}, avs::Vector{<:AbstractVariation}=AbstractVariation[]; + n_replicates::Integer=1, use_previous::Bool=true) +``` + +# Examples +``` +inputs = InputFolders(config_folder, custom_code_folder) +dv_max_time = DiscreteVariation(configPath(""max_time""), 1440) +dv_apoptosis = DiscreteVariation(configPath(cell_type, ""apoptosis"", ""rate""), [1e-6, 1e-5]) +simulation = createTrial(inputs, dv_max_time) +monad = createTrial(inputs, dv_max_time; n_replicates=2) +sampling = createTrial(monad, dv_apoptosis; n_replicates=2) # uses the max time defined for monad +out = run(simulation) # run the simulation and return type `PCMMOutput{Simulation}` +new_sampling = createTrial(out, dv_apoptosis; n_replicates=2) # same as sampling above +``` +"""""" +function createTrial(method::AddVariationMethod, inputs::InputFolders, avs::Vector{<:AbstractVariation}=AbstractVariation[]; + n_replicates::Integer=1, use_previous::Bool=true) + return _createTrial(method, inputs, VariationID(inputs), avs, n_replicates, use_previous) +end + +function createTrial(method::AddVariationMethod, inputs::InputFolders, avs::Vararg{AbstractVariation}; kwargs...) + return createTrial(method, inputs, [avs...]; kwargs...) +end + +function createTrial(method::AddVariationMethod, inputs::InputFolders, avs::Vector; kwargs...) + avs = convertToAbstractVariationVector(avs) + return createTrial(method, inputs, avs; kwargs...) +end + +createTrial(method::AddVariationMethod, inputs::InputFolders, avs::Vararg; kwargs...) = createTrial(method, inputs, [avs...]; kwargs...) + +createTrial(inputs::InputFolders, args...; kwargs...) = createTrial(GridVariation(), inputs, args...; kwargs...) + +function createTrial(method::AddVariationMethod, reference::AbstractMonad, avs::Vector{<:AbstractVariation}=AbstractVariation[]; + n_replicates::Integer=1, use_previous::Bool=true) + return _createTrial(method, reference.inputs, reference.variation_id, avs, n_replicates, use_previous) +end + +function createTrial(method::AddVariationMethod, reference::AbstractMonad, avs::Vararg{AbstractVariation}; kwargs...) + return createTrial(method, reference, [avs...]; kwargs...) +end + +function createTrial(method::AddVariationMethod, reference::AbstractMonad, avs::Vector; kwargs...) + avs = convertToAbstractVariationVector(avs) + return createTrial(method, reference, avs; kwargs...) +end + +createTrial(method::AddVariationMethod, reference::AbstractMonad, avs::Vararg; kwargs...) = createTrial(method, reference, [avs...]; kwargs...) + +createTrial(reference::AbstractMonad, args...; kwargs...) = createTrial(GridVariation(), reference, args...; kwargs...) + +function convertToAbstractVariationVector(avs::Vector) + try + return Vector{AbstractVariation}(avs) + catch _ + msg = """""" + Variations must be a subtype AbstractVariation. + The following indices of the provided variations are not: + """""" + for (i, av) in enumerate(avs) + if av isa AbstractVariation + continue + end + msg *= ""\n - Index $i: $(typeof(av))"" + end + throw(ArgumentError(msg)) + end +end + +createTrial(output_ref::PCMMOutput{<:AbstractMonad}, args...; kwargs...) = createTrial(output_ref.trial, args...; kwargs...) + +"""""" + _createTrial(args...; kwargs...) + +Internal function to create a trial with the given input folders and elementary variations. +Users should use [`createTrial`](@ref) instead. + +# Arguments +- `method::AddVariationMethod`: The method to use for creating the trial. Default is `GridVariation()`. +- `inputs::InputFolders`: The input folders for the simulation. +- `reference_variation_id::VariationID`: The variation ID of the reference simulation or monad. +- `avs::Vector{<:AbstractVariation}`: A vector of variations to add to the reference simulation or monad. +- `n_replicates::Integer`: The number of replicates to create. Default is 1. +- `use_previous::Bool`: Whether to use previous simulations. +"""""" +function _createTrial(method::AddVariationMethod, inputs::InputFolders, reference_variation_id::VariationID, + avs::Vector{<:AbstractVariation}, n_replicates::Integer, use_previous::Bool) + + add_variations_result = addVariations(method, inputs, avs, reference_variation_id) + all_variation_ids = add_variations_result.all_variation_ids + if length(all_variation_ids) == 1 + variation_ids = all_variation_ids[1] + monad = Monad(inputs, variation_ids; n_replicates=n_replicates, use_previous=use_previous) + if n_replicates != 1 + return monad + end + return Simulation(simulationIDs(monad)[end]) + else + location_variation_ids = [loc => [variation_id[loc] for variation_id in all_variation_ids] for loc in projectLocations().varied] |> + Dict{Symbol,Union{Integer,AbstractArray{<:Integer}}} + + return Sampling(inputs, location_variation_ids; + n_replicates=n_replicates, + use_previous=use_previous + ) + end +end + +"""""" + run(args...; force_recompile::Bool=false, prune_options::PruneOptions=PruneOptions(), kwargs...) + +Run a simulation, monad, sampling, or trial with the same signatures available to [`createTrial`](@ref). +"""""" +function run(method::AddVariationMethod, args...; force_recompile::Bool=false, + prune_options::PruneOptions=PruneOptions(), kwargs...) + trial = createTrial(method, args...; kwargs...) + return run(trial; force_recompile=force_recompile, prune_options=prune_options) +end + +run(inputs::InputFolders, args...; kwargs...) = run(GridVariation(), inputs, args...; kwargs...) + +run(reference::AbstractMonad, arg1, args...; kwargs...) = run(GridVariation(), reference, arg1, args...; kwargs...) + +run(output_ref::PCMMOutput{<:AbstractMonad}, args...; kwargs...) = run(output_ref.trial, args...; kwargs...) +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/physicell_version.jl",".jl","10239","268","using SQLite + +"""""" + resolvePhysiCellVersionID() + +Get the PhysiCell version ID from the database, adding it to the database if it doesn't exist. +"""""" +function resolvePhysiCellVersionID() + if !physicellIsGit() + + tag = readlines(joinpath(physicellDir(), ""VERSION.txt""))[1] + full_tag = ""$tag-download"" + + stmt_str = ""INSERT OR IGNORE INTO physicell_versions (commit_hash) VALUES (:full_tag) RETURNING physicell_version_id;"" + params = (; :full_tag => full_tag) + df = stmtToDataFrame(stmt_str, params) + if isempty(df) + where_str = ""WHERE commit_hash=(:full_tag)"" + stmt_str = constructSelectQuery(""physicell_versions"", where_str; selection=""physicell_version_id"") + df = stmtToDataFrame(stmt_str, params; is_row=true) + end + return df.physicell_version_id[1] + end + + repo_is_dirty = false + if !gitDirectoryIsClean(physicellDir()) + println("""""" + \nWARNING: PhysiCell repo is dirty. The latest commit hash will be marked with the ""-dirty"" suffix in the database. + These results may not be reproducible. + To regain reproducibility, make a new commit or stash changes to clean the repository. + To see the changed files, run the following command from your terminal:\n + \tgit -C $(physicellDir()) status + """""" + ) + repo_is_dirty = true + end + + #! then, get the current commit hash + commit_hash = readchomp(`git -C $(physicellDir()) rev-parse HEAD`) + commit_hash *= repo_is_dirty ? ""-dirty"" : """" + + #! then, compare that hash with hashes in the database + query = constructSelectQuery(""physicell_versions"", ""WHERE commit_hash = '$commit_hash'"") + current_entry_df = queryToDataFrame(query) + @assert size(current_entry_df, 1) <= 1 ""The database should have unique 'commit_hash' entries."" + is_hash_in_db = !isempty(current_entry_df) + no_entries_missing = is_hash_in_db && all(.!ismissing.([x[1] for x in eachcol(current_entry_df)])) + if no_entries_missing + #! if the commit hash is already in the database, and it has a tag, then we are done + return current_entry_df.physicell_version_id[1] + end + entry_dict = Dict{String,String}() + + #! then, compare that hash with remote hashes to identify the tag, repo owner, and date + hash_to_tag_dict = commitHashToTagDict(physicellDir()) + if !repo_is_dirty && haskey(hash_to_tag_dict, commit_hash) + entry_dict[""tag""] = hash_to_tag_dict[commit_hash] + else + entry_dict[""tag""] = ""NULL"" + end + + entry_dict[""repo_owner""] = repo_is_dirty ? ""NULL"" : repoOwner(commit_hash, entry_dict[""tag""]) + entry_dict[""date""] = repo_is_dirty ? ""NULL"" : readchomp(`git -C $(physicellDir()) show -s --format=%ci $commit_hash`) + + db_entry_dict = [k => v==""NULL"" ? v : ""'$v'"" for (k,v) in entry_dict] |> Dict #! surround non-NULL values with single quotes, so NULL really go in as NULL + if is_hash_in_db + for (name, col) in pairs(eachcol(current_entry_df)) + if !ismissing(col[1]) + continue + end + name_str = string(name) + DBInterface.execute(centralDB(), ""UPDATE physicell_versions SET $(name_str) = $(db_entry_dict[name_str]) WHERE commit_hash = '$commit_hash';"") + end + query = constructSelectQuery(""physicell_versions"", ""WHERE commit_hash = '$commit_hash'""; selection=""physicell_version_id"") + df = queryToDataFrame(query; is_row=true) + else + df = DBInterface.execute(centralDB(), ""INSERT INTO physicell_versions (commit_hash, tag, repo_owner, date) VALUES ('$commit_hash', $(db_entry_dict[""tag""]), $(db_entry_dict[""repo_owner""]), $(db_entry_dict[""date""])) RETURNING physicell_version_id;"") |> DataFrame + end + return df.physicell_version_id[1] +end + +"""""" + physicellIsGit() + +Check if the PhysiCell directory is a git repository. +"""""" +function physicellIsGit() + is_git = isdir(joinpath(physicellDir(), "".git"")) + if !is_git #! possible it is a submodule + path_to_file = joinpath(physicellDir(), "".git"") + if isfile(path_to_file) + lines = readlines(path_to_file) + if length(lines) > 0 + line_1 = lines[1] + is_git = startswith(line_1, ""gitdir: "") && + contains(line_1, ""modules"") && + endswith(line_1, ""PhysiCell"") + end + end + end + return is_git +end + +"""""" + gitDirectoryIsClean(dir::String) + +Check if the git directory is clean (i.e., no uncommitted changes). +"""""" +function gitDirectoryIsClean(dir::String) + cmd = `git -C $dir status --porcelain` #! -C flag is for changing directory, --porcelain flag is for machine-readable output (much easier to tell if clean this way) + output = read(cmd, String) + is_clean = length(output) == 0 + if is_clean + return true + end + folders_to_ignore = [""beta"", ""config"", ""documentation-deprecated"", ""examples"", + ""licenses"", ""matlab"", ""output"", ""povray"", ""protocols"", ""sample_projects"", + ""sample_projects_intracellular"", ""sample_projects_physipkpd"", ""tests"", ""unit_tests"", + ""user_projects""] + files_to_ignore = [""ALL_CITATIONS.txt""] + lines = split(output, ""\n"") + filter!(x -> x != """", lines) + for folder in folders_to_ignore + filter!(x -> !contains(x, "" $folder/""), lines) + end + for file in files_to_ignore + filter!(x -> !contains(x, "" $file""), lines) + end + is_clean = isempty(lines) + if !is_clean + println(""PhysiCell repository is dirty. The following files are modified in the PhysiCell repository:"") + println(output) + println(""\nOf those, the following files are not in the folders to ignore for cleanliness:"") + println.(lines); + end + return is_clean +end + +"""""" + commitHashToTagDict(dir::String) + +Get a dictionary mapping commit hashes to tags in the git repository at `dir`. +"""""" +function commitHashToTagDict(dir::String) + hash_to_tag_dict = Dict{String, String}() + has_tags = !isempty(readchomp(`git -C $dir tag`)) + if !has_tags + return hash_to_tag_dict + end + tags_output = readchomp(`git -C $dir show-ref --tags`) + tags = split(tags_output, ""\n"") + for tag in tags + parts = split(tag) + if length(parts) == 2 + commit_hash, tag_ref = parts + tag_name = split(tag_ref, '/')[end] + hash_to_tag_dict[commit_hash] = tag_name + else + println(""Error: tag is not in the expected format ( ):\n\t$tag"") + end + end + return hash_to_tag_dict +end + +"""""" + repoOwner(commit_hash::String, tag::String) + +Get the owner of the repository for a given commit hash and tag. +"""""" +function repoOwner(commit_hash, tag::String) + if tag == ""NULL"" + return ""NULL"" + end + remotes = gitRemotes(physicellDir()) + for remote in remotes + remote_hash_tags = try + readchomp(`git -C $(physicellDir()) ls-remote --tags $remote`) + catch _ + return ""REPO_OWNER_UNKNOWN_UNABLE_TO_ACCESS_REMOTE"" + end + + remote_hash_tags = split(remote_hash_tags, ""\n"") + for remote_hash_tag in remote_hash_tags + remote_commit_hash, remote_tag_name = split(remote_hash_tag, ""\t"") + if remote_commit_hash != commit_hash + continue + end + remote_tag_name = split(remote_tag_name, ""/"")[end] + if remote_tag_name == tag + remote_url = readchomp(`git -C $(physicellDir()) remote get-url $remote`) + repo_owner = split(remote_url, ""/"")[end-1] + return repo_owner + end + end + end + return ""NULL"" +end + +"""""" + gitRemotes(dir::String) + +Get the remotes for the git repository at `dir`. +"""""" +function gitRemotes(dir::String) + remotes_output = readchomp(`git -C $dir remote`) + remotes = split(remotes_output, ""\n"") + return remotes +end + +"""""" + physicellVersion() + physiCellVersion(physicell_version_id::Int) + physiCellVersion(simulation::Simulation) + +Get the PhysiCell version from the database or, if not in the database, from the VERSION.txt file. +"""""" +function physicellVersion(physicell_version_id::Int) + query = constructSelectQuery(""physicell_versions"", ""WHERE physicell_version_id = $(physicell_version_id)"") + df = queryToDataFrame(query; is_row=true) + if !ismissing(df.tag[1]) + return df.tag[1] + end + #! untagged commit, so use the VERSION.txt file + path_to_version_file = joinpath(physicellDir(), ""VERSION.txt"") + @assert isfile(path_to_version_file) ""PhysiCell version undefined. Not at a tagged commit AND file not found at $path_to_version_file"" + lines = readlines(path_to_version_file) + return lines[1] +end + +physicellVersion() = physicellVersion(pcmm_globals.current_physicell_version_id) + +function physicellVersion(simulation::Simulation) + query = constructSelectQuery(""simulations"", ""WHERE simulation_id = $(simulation.id)""; selection=""physicell_version_id"") + df = queryToDataFrame(query; is_row=true) + return physicellVersion(df.physicell_version_id[1]) +end + +"""""" + physicellInfo() + +Return a string representing the PhysiCell version information to display on initializing the model manager. +"""""" +function physicellInfo() + query = constructSelectQuery(""physicell_versions"", ""WHERE physicell_version_id = $(pcmm_globals.current_physicell_version_id)"") + df = queryToDataFrame(query; is_row=true) + str_begin = ismissing(df.repo_owner[1]) ? """" : ""($(df.repo_owner[1])) "" + str_middle = ismissing(df.tag[1]) ? df.commit_hash[1] : df.tag[1] + str_end = ismissing(df.date[1]) ? """" : "" COMMITTED ON $(df.date[1])"" + return ""$str_begin$str_middle$str_end"" +end + +"""""" + physicellCommitHash() + +Get the commit hash for the current PhysiCell version. +"""""" +function physiCellCommitHash() + query = constructSelectQuery(""physicell_versions"", ""WHERE physicell_version_id = $(pcmm_globals.current_physicell_version_id)""; selection=""commit_hash"") + df = queryToDataFrame(query; is_row=true) + return df.commit_hash[1] +end + +"""""" + currentPhysiCellVersionID() + +Get the current PhysiCell version ID. +"""""" +currentPhysiCellVersionID() = pcmm_globals.current_physicell_version_id","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/sensitivity.jl",".jl","28965","604","using Distributions, DataFrames, CSV, Sobol, FFTW +import GlobalSensitivity #! do not bring in their definition of Sobol as it conflicts with the Sobol module + +export MOAT, Sobolʼ, SobolPCMM, RBD + +"""""" + GSAMethod + +Abstract type for global sensitivity analysis methods. + +# Subtypes +- [`MOAT`](@ref) +- [`Sobolʼ`](@ref) +- [`RBD`](@ref) + +# Methods +[`run`](@ref) +"""""" +abstract type GSAMethod end + +"""""" + GSASampling + +Store the information that comes out of a global sensitivity analysis method. + +# Subtypes +- [`MOATSampling`](@ref) +- [`SobolSampling`](@ref) +- [`RBDSampling`](@ref) + +# Methods +[`calculateGSA!`](@ref), [`evaluateFunctionOnSampling`](@ref), +[`getMonadIDDataFrame`](@ref), [`simulationIDs`](@ref), [`methodString`](@ref), +[`sensitivityResults!`](@ref), [`recordSensitivityScheme`](@ref) +"""""" +abstract type GSASampling end + +"""""" + getMonadIDDataFrame(gsa_sampling::GSASampling) + +Get the DataFrame of monad IDs that define the scheme of the sensitivity analysis. +"""""" +getMonadIDDataFrame(gsa_sampling::GSASampling) = gsa_sampling.monad_ids_df + +"""""" + simulationIDs(gsa_sampling::GSASampling) + +Get the simulation IDs that were run in the sensitivity analysis. +"""""" +simulationIDs(gsa_sampling::GSASampling) = simulationIDs(gsa_sampling.sampling) + +"""""" + methodString(gsa_sampling::GSASampling) + +Get the string representation of the method used in the sensitivity analysis. +"""""" +function methodString(gsa_sampling::GSASampling) + method = typeof(gsa_sampling) |> string |> lowercase + method = split(method, ""."")[end] #! remove module name that comes with the type, e.g. Main.PhysiCellModelManager.MOATSampling -> MOATSampling + return endswith(method, ""sampling"") ? method[1:end-8] : method +end + +"""""" + run(method::GSAMethod, args...; functions::AbstractVector{<:Function}=Function[], kwargs...) + +Run a global sensitivity analysis method on the given arguments. + +# Arguments +- `method::GSAMethod`: the method to run. Options are [`MOAT`](@ref), [`Sobolʼ`](@ref), and [`RBD`](@ref). +- `inputs::InputFolders`: the input folders shared across all simuations to run. +- `avs::AbstractVector{<:AbstractVariation}`: the elementary variations to sample. These can be either [`DiscreteVariation`](@ref)'s or [`DistributedVariation`](@ref)'s. + +Alternatively, the third argument, `inputs`, can be replaced with a `reference::AbstractMonad`, i.e., a simulation or monad to be the reference. +This should be preferred to setting reference variation IDs manually, i.e., if not using the base files in the input folders. + +# Keyword Arguments +The `reference_variation_id` keyword argument is only compatible when the third argument is of type `InputFolders`. +Otherwise, the `reference` simulation/monad will set the reference variation values. +- `reference_variation_id::VariationID`: the reference variation IDs as a `VariationID` +- `ignore_indices::AbstractVector{<:Integer}=[]`: indices into `avs` to ignore when perturbing the parameters. Only used for Sobolʼ. See [`Sobolʼ`](@ref) for a use case. +- `force_recompile::Bool=false`: whether to force recompilation of the simulation code +- `prune_options::PruneOptions=PruneOptions()`: the options for pruning the simulation results +- `n_replicates::Integer=1`: the number of replicates to run for each monad, i.e., at each sampled parameter vector. +- `use_previous::Bool=true`: whether to use previous simulation results if they exist +- `functions::AbstractVector{<:Function}=Function[]`: the functions to calculate the sensitivity indices for. Each function must take a simulation ID as the singular input and return a real number. +"""""" +function run(method::GSAMethod, inputs::InputFolders, avs::AbstractVector{<:AbstractVariation}; functions::AbstractVector{<:Function}=Function[], kwargs...) + pv = ParsedVariations(avs) + gsa_sampling = runSensitivitySampling(method, inputs, pv; kwargs...) + sensitivityResults!(gsa_sampling, functions) + return gsa_sampling +end + +function run(method::GSAMethod, reference::AbstractMonad, avs::Vector{<:AbstractVariation}; functions::AbstractVector{<:Function}=Function[], kwargs...) + return run(method, reference.inputs, avs; reference_variation_id=reference.variation_id, functions, kwargs...) +end + +function run(method::GSAMethod, inputs_or_ref::Union{InputFolders, AbstractMonad}, av1::AbstractVariation, avs::Vararg{AbstractVariation}; kwargs...) + return run(method, inputs_or_ref, [av1; avs...]; kwargs...) +end + +"""""" + sensitivityResults!(gsa_sampling::GSASampling, functions::AbstractVector{<:Function}) + +Calculate the global sensitivity analysis for the given functions and record the sampling scheme. +"""""" +function sensitivityResults!(gsa_sampling::GSASampling, functions::AbstractVector{<:Function}) + calculateGSA!(gsa_sampling, functions) + recordSensitivityScheme(gsa_sampling) +end + +"""""" + calculateGSA!(gsa_sampling::GSASampling, functions::AbstractVector{<:Function}) + +Calculate the sensitivity indices for the given functions. + +This function is also used to compute the sensitivity indices for a single function: +```julia +calculateGSA!(gsa_sampling, f) +``` + +# Arguments +- `gsa_sampling::GSASampling`: the sensitivity analysis to calculate the indices for. +- `functions::AbstractVector{<:Function}`: the functions to calculate the sensitivity indices for. Each function must take a simulation ID as the singular input and return a real number. +"""""" +function calculateGSA!(gsa_sampling::GSASampling, functions::AbstractVector{<:Function}) + for f in functions + calculateGSA!(gsa_sampling, f) + end + return +end + +############# Morris One-At-A-Time (MOAT) ############# + +"""""" + MOAT + +Store the information necessary to run a Morris One-At-A-Time (MOAT) global sensitivity analysis. + +# Fields +- `lhs_variation::LHSVariation`: the Latin Hypercube Sampling (LHS) variation to use for the MOAT. See [`LHSVariation`](@ref). + +# Examples +Note: any keyword arguments in the `MOAT` constructor are passed to [`LHSVariation`](@ref). +``` +MOAT() # default to 15 base points +MOAT(10) # 10 base points +MOAT(10; add_noise=true) # do not restrict the base points to the center of their cells +``` +"""""" +struct MOAT <: GSAMethod + lhs_variation::LHSVariation +end + +MOAT() = MOAT(LHSVariation(15)) #! default to 15 points +MOAT(n::Int; kwargs...) = MOAT(LHSVariation(n; kwargs...)) + +"""""" + MOATSampling + +Store the information that comes out of a Morris One-At-A-Time (MOAT) global sensitivity analysis. + +# Fields +- `sampling::Sampling`: the sampling used in the sensitivity analysis. +- `monad_ids_df::DataFrame`: the DataFrame of monad IDs that define the scheme of the sensitivity analysis. +- `results::Dict{Function, GlobalSensitivity.MorrisResult}`: the results of the sensitivity analysis for each function. +"""""" +struct MOATSampling <: GSASampling + sampling::Sampling + monad_ids_df::DataFrame + results::Dict{Function, GlobalSensitivity.MorrisResult} +end + +MOATSampling(sampling::Sampling, monad_ids_df::DataFrame) = MOATSampling(sampling, monad_ids_df, Dict{Function, GlobalSensitivity.MorrisResult}()) + +function Base.show(io::IO, moat_sampling::MOATSampling) + println(io, ""MOAT sampling"") + println(io, ""-------------"") + println(io, moat_sampling.sampling) + println(io, ""Sensitivity functions calculated:"") + for f in keys(moat_sampling.results) + println(io, "" $f"") + end +end + +"""""" + runSensitivitySampling(method::GSAMethod, args...; kwargs...) + +Run a global sensitivity analysis method on the given arguments. + +# Arguments +- `method::GSAMethod`: the method to run. Options are [`MOAT`](@ref), [`Sobolʼ`](@ref), and [`RBD`](@ref). +- `inputs::InputFolders`: the input folders shared across all simuations to run. +- `pv::ParsedVariations`: the [`ParsedVariations`](@ref) object that contains the variations to sample. + +# Keyword Arguments +- `reference_variation_id::VariationID`: the reference variation IDs as a `VariationID` +- `ignore_indices::AbstractVector{<:Integer}=[]`: indices into `pv.variations` to ignore when perturbing the parameters. Only used for [Sobolʼ](@ref). +- `force_recompile::Bool=false`: whether to force recompilation of the simulation code +- `prune_options::PruneOptions=PruneOptions()`: the options for pruning the simulation results +- `n_replicates::Int=1`: the number of replicates to run for each monad, i.e., at each sampled parameter vector. +- `use_previous::Bool=true`: whether to use previous simulation results if they exist +"""""" +function runSensitivitySampling end + +function runSensitivitySampling(method::MOAT, inputs::InputFolders, pv::ParsedVariations; reference_variation_id::VariationID=VariationID(inputs), + ignore_indices::AbstractVector{<:Integer}=Int[], force_recompile::Bool=false, prune_options::PruneOptions=PruneOptions(), n_replicates::Int=1, use_previous::Bool=true) + + if !isempty(ignore_indices) + error(""MOAT does not support ignoring indices...yet? Only Sobolʼ does for now."") + end + add_variations_result = addVariations(method.lhs_variation, inputs, pv, reference_variation_id) + variation_ids = add_variations_result.all_variation_ids + base_variation_ids = Dict{Symbol, Vector{Int}}() + perturbed_variation_ids = Dict{Symbol, Matrix{Int}}() + + proj_locs = projectLocations() + for location in proj_locs.varied + base_variation_ids[location] = [variation_id[location] for variation_id in variation_ids] + perturbed_variation_ids[location] = repeat(base_variation_ids[location], 1, length(pv.sz)) + end + for (base_point_ind, variation_id) in enumerate(variation_ids) #! for each base point in the LHS + for d in eachindex(pv.sz) #! perturb each feature one time + for location in proj_locs.varied + perturbed_variation_ids[location][base_point_ind, d] = perturbVariation(location, pv, inputs[location].folder, variation_id[location], d) + end + end + end + all_variation_ids = Dict{Symbol, Matrix{Int}}() + for location in proj_locs.varied + all_variation_ids[location] = hcat(base_variation_ids[location], perturbed_variation_ids[location]) + end + location_variation_dict = (loc => all_variation_ids[loc] for loc in proj_locs.varied) |> Dict + monad_dict, monad_ids = variationsToMonads(inputs, location_variation_dict) + header_line = [""base""; columnName.(pv.variations)] + monad_ids_df = DataFrame(monad_ids, header_line) + sampling = Sampling(monad_dict |> values |> collect; n_replicates=n_replicates, use_previous=use_previous) + run(sampling; force_recompile=force_recompile, prune_options=prune_options) + return MOATSampling(sampling, monad_ids_df) +end + +"""""" + perturbVariation(location::Symbol, pv::ParsedVariations, folder::String, reference_variation_id::Int, d::Int) + +Perturb the variation at the given location and dimension for [`MOAT`](@ref) global sensitivity analysis. +"""""" +function perturbVariation(location::Symbol, pv::ParsedVariations, folder::String, reference_variation_id::Int, d::Int) + matching_dims = pv[location].indices .== d + evs = pv[location].variations[matching_dims] #! all the variations associated with the dth feature + if isempty(evs) + return reference_variation_id + end + base_values = variationValue.(evs, reference_variation_id, folder) + + cdfs_at_base = [cdf(ev, bv) for (ev, bv) in zip(evs, base_values)] + @assert maximum(cdfs_at_base) - minimum(cdfs_at_base) < 1e-10 ""All base values must have the same CDF (within tolerance).\nInstead, got $cdfs_at_base."" + dcdf = cdfs_at_base[1] < 0.5 ? 0.5 : -0.5 + new_values = variationValues.(evs, cdfs_at_base[1] + dcdf) #! note, this is a vector of values + + discrete_variations = [DiscreteVariation(variationTarget(ev), new_value) for (ev, new_value) in zip(evs, new_values)] + + new_variation_id = gridToDB(discrete_variations, inputFolderID(location, folder), reference_variation_id) + @assert length(new_variation_id) == 1 ""Only doing one perturbation at a time."" + return new_variation_id[1] +end + +"""""" + variationValue(ev::ElementaryVariation, variation_id::Int, folder::String) + +Get the value of the variation at the given variation ID for [`MOAT`](@ref) global sensitivity analysis. +"""""" +function variationValue(ev::ElementaryVariation, variation_id::Int, folder::String) + location = variationLocation(ev) + query = constructSelectQuery(locationVariationsTableName(location), ""WHERE $(locationVariationIDName(location))=$variation_id""; selection=""\""$(columnName(ev))\"""") + variation_value_df = queryToDataFrame(query; db=locationVariationsDatabase(location, folder), is_row=true) + return variation_value_df[1,1] + +end + +function calculateGSA!(moat_sampling::MOATSampling, f::Function) + if f in keys(moat_sampling.results) + return + end + vals = evaluateFunctionOnSampling(moat_sampling, f) + effects = 2 * (vals[:,2:end] .- vals[:,1]) #! all diffs in the design matrix are 0.5 + means = mean(effects, dims=1) + means_star = mean(abs.(effects), dims=1) + variances = var(effects, dims=1) + moat_sampling.results[f] = GlobalSensitivity.MorrisResult(means, means_star, variances, effects) + return +end + +############# Sobolʼ sequences and sobol indices ############# + +"""""" + Sobolʼ + +Store the information necessary to run a Sobol' global sensitivity analysis as well as how to extract the first and total order indices. + +The rasp symbol is used to avoid conflict with the Sobol module. To type it in VS Code, use `\\rasp` and then press `tab`. +Alternatively, the constructor [`SobolPCMM`](@ref) is provided as an alias for convenience. + +The methods available for the first order indices are `:Sobol1993`, `:Jansen1999`, and `:Saltelli2010`. Default is `:Jansen1999`. +The methods available for the total order indices are `:Homma1996`, `:Jansen1999`, and `:Sobol2007`. Default is `:Jansen1999`. + +# Fields +- `sobol_variation::SobolVariation`: the Sobol' variation to use for the Sobol' analysis. See [`SobolVariation`](@ref). +- `sobol_index_methods::NamedTuple{(:first_order, :total_order), Tuple{Symbol, Symbol}}`: the methods to use for calculating the first and total order indices. + +# Examples +Note: any keyword arguments in the `Sobolʼ` constructor are passed to [`SobolVariation`](@ref), except for the `sobol_index_methods` keyword argument. +Do not use the `n_matrices` keyword argument in the `SobolVariation` constructor as it is set to 2 as required for Sobol' analysis. +``` +Sobolʼ(15) # 15 points from the Sobol' sequence +Sobolʼ(15; sobol_index_methods=(first_order=:Jansen1999, total_order=:Jansen1999)) # use Jansen, 1999 for both first and total order indices +Sobolʼ(15; randomization=NoRand())` # use the default Sobol' sequence with no randomization. See GlobalSensitivity.jl for more options. +Sobolʼ(15; skip_start=true) # force the Sobol' sequence to skip to the lowest denominator in the sequence that can hold 15 points, i.e., choose from [1/32, 3/32, 5/32, ..., 31/32] +Sobolʼ(15; skip_start=false) # force the Sobol' sequence to start at the beginning, i.e. [0, 0.5, 0.25, 0.75, ...] +Sobolʼ(15; include_one=true) # force the Sobol' sequence to include 1 in the sequence +``` +"""""" +struct Sobolʼ <: GSAMethod #! the prime symbol is used to avoid conflict with the Sobol module + sobol_variation::SobolVariation + sobol_index_methods::NamedTuple{(:first_order, :total_order), Tuple{Symbol, Symbol}} +end + +Sobolʼ(n::Int; sobol_index_methods::NamedTuple{(:first_order, :total_order), Tuple{Symbol, Symbol}}=(first_order=:Jansen1999, total_order=:Jansen1999), kwargs...) = + Sobolʼ(SobolVariation(n; n_matrices=2, kwargs...), sobol_index_methods) + +"""""" + SobolPCMM + +Alias for [`Sobolʼ`](@ref) for convenience. +"""""" +SobolPCMM = Sobolʼ #! alias for convenience + +"""""" + SobolSampling + +Store the information that comes out of a Sobol' global sensitivity analysis. + +# Fields +- `sampling::Sampling`: the sampling used in the sensitivity analysis. +- `monad_ids_df::DataFrame`: the DataFrame of monad IDs that define the scheme of the sensitivity analysis. +- `results::Dict{Function, GlobalSensitivity.SobolResult}`: the results of the sensitivity analysis for each function. +- `sobol_index_methods::NamedTuple{(:first_order, :total_order), Tuple{Symbol, Symbol}}`: the methods used for calculating the first and total order indices. +"""""" +struct SobolSampling <: GSASampling + sampling::Sampling + monad_ids_df::DataFrame + results::Dict{Function, GlobalSensitivity.SobolResult} + sobol_index_methods::NamedTuple{(:first_order, :total_order), Tuple{Symbol, Symbol}} +end + +SobolSampling(sampling::Sampling, monad_ids_df::DataFrame; sobol_index_methods::NamedTuple{(:first_order, :total_order), Tuple{Symbol, Symbol}}=(first_order=:Jansen1999, total_order=:Jansen1999)) = SobolSampling(sampling, monad_ids_df, Dict{Function, GlobalSensitivity.SobolResult}(), sobol_index_methods) + +function Base.show(io::IO, sobol_sampling::SobolSampling) + println(io, ""Sobol sampling"") + println(io, ""--------------"") + println(io, sobol_sampling.sampling) + println(io, ""Sobol index methods:"") + println(io, "" First order: $(sobol_sampling.sobol_index_methods.first_order)"") + println(io, "" Total order: $(sobol_sampling.sobol_index_methods.total_order)"") + println(io, ""Sensitivity functions calculated:"") + for f in keys(sobol_sampling.results) + println(io, "" $f"") + end +end + +function runSensitivitySampling(method::Sobolʼ, inputs::InputFolders, pv::ParsedVariations; reference_variation_id::VariationID=VariationID(inputs), + ignore_indices::AbstractVector{<:Integer}=Int[], force_recompile::Bool=false, prune_options::PruneOptions=PruneOptions(), n_replicates::Int=1, use_previous::Bool=true) + + add_variations_result = addVariations(method.sobol_variation, inputs, pv, reference_variation_id) + all_variation_ids = add_variations_result.all_variation_ids + cdfs = add_variations_result.cdfs + d = length(pv.sz) + focus_indices = [i for i in 1:d if !(i in ignore_indices)] + + proj_locs = projectLocations() + location_variation_ids_A = [loc => [variation_id[loc] for variation_id in all_variation_ids[:,1]] for loc in proj_locs.varied] |> Dict + A = cdfs[:,1,:] #! cdfs is of size (d, 2, n), i.e., d = # parameters, 2 design matrices, and n = # samples + location_variation_ids_B = [loc => [variation_id[loc] for variation_id in all_variation_ids[:,2]] for loc in proj_locs.varied] |> Dict + B = cdfs[:,2,:] + Aᵦ = [i => copy(A) for i in focus_indices] |> Dict + location_variation_ids_Aᵦ = [loc => [i => copy(location_variation_ids_A[loc]) for i in focus_indices] |> Dict for loc in proj_locs.varied] |> Dict + for i in focus_indices + Aᵦ[i][i,:] .= B[i,:] + for loc in proj_locs.varied + if i in pv[loc].indices + location_variation_ids_Aᵦ[loc][i][:] .= cdfsToVariations(loc, pv, inputs[loc].id, reference_variation_id[loc], Aᵦ[i]') + end + end + end + location_variation_ids_dict = [loc => hcat(location_variation_ids_A[loc], location_variation_ids_B[loc], [location_variation_ids_Aᵦ[loc][i] for i in focus_indices]...) for loc in proj_locs.varied] |> Dict{Symbol,Matrix{Int}} + monad_dict, monad_ids = variationsToMonads(inputs, location_variation_ids_dict) + monads = monad_dict |> values |> collect + header_line = [""A""; ""B""; columnName.(pv.variations[focus_indices])] + monad_ids_df = DataFrame(monad_ids, header_line) + sampling = Sampling(monads; n_replicates=n_replicates, use_previous=use_previous) + run(sampling; force_recompile=force_recompile, prune_options=prune_options) + return SobolSampling(sampling, monad_ids_df; sobol_index_methods=method.sobol_index_methods) +end + +function calculateGSA!(sobol_sampling::SobolSampling, f::Function) + if f in keys(sobol_sampling.results) + return + end + vals = evaluateFunctionOnSampling(sobol_sampling, f) + d = size(vals, 2) - 2 + A_values = @view vals[:, 1] + B_values = @view vals[:, 2] + Aᵦ_values = [vals[:, 2+i] for i in 1:d] + expected_value² = mean(A_values .* B_values) #! see Saltelli, 2002 Eq 21 + total_variance = var([A_values; B_values]) + first_order_variances = zeros(Float64, d) + total_order_variances = zeros(Float64, d) + si_method = sobol_sampling.sobol_index_methods.first_order + st_method = sobol_sampling.sobol_index_methods.total_order + for (i, Aᵦ) in enumerate(Aᵦ_values) + #! I found Jansen, 1999 to do best for first order variances on a simple test of f(x,y) = x.^2 + y.^2 + c with a uniform distribution on [0,1] x [0,1] including with noise added + if si_method == :Sobol1993 + first_order_variances[i] = mean(B_values .* Aᵦ) .- expected_value² #! Sobol, 1993 + elseif si_method == :Jansen1999 + first_order_variances[i] = total_variance - 0.5 * mean((B_values .- Aᵦ) .^ 2) #! Jansen, 1999 + elseif si_method == :Saltelli2010 + first_order_variances[i] = mean(B_values .* (Aᵦ .- A_values)) #! Saltelli, 2010 + end + + #! I found Jansen, 1999 to do best for total order variances on a simple test of f(x,y) = x.^2 + y.^2 + c with a uniform distribution on [0,1] x [0,1] including with noise added + if st_method == :Homma1996 + total_order_variances[i] = total_variance - mean(A_values .* Aᵦ) + expected_value² #! Homma, 1996 + elseif st_method == :Jansen1999 + total_order_variances[i] = 0.5 * mean((Aᵦ .- A_values) .^ 2) #! Jansen, 1999 + elseif st_method == :Sobol2007 + total_order_variances[i] = mean(A_values .* (A_values .- Aᵦ)) #! Sobol, 2007 + end + end + + first_order_indices = first_order_variances ./ total_variance + total_order_indices = total_order_variances ./ total_variance + + sobol_sampling.results[f] = GlobalSensitivity.SobolResult(first_order_indices, nothing, nothing, nothing, total_order_indices, nothing) #! do not yet support (S1 CIs, second order indices (S2), S2 CIs, or ST CIs) + return +end + +############# Random Balance Design (RBD) ############# + +"""""" + RBD + +Store the information necessary to run a Random Balance Design (RBD) global sensitivity analysis. + +By default, `RBD` will use the Sobol' sequence to sample the parameter space. +See below for how to turn this off. +Currently, users cannot control the Sobolʼ sequence used in RBD to the same degree it can be controlled in Sobolʼ. +Open an [Issue](https://github.com/drbergman-lab/PhysiCellModelManager.jl/issues) if you would like this feature. + +# Fields +- `rbd_variation::RBDVariation`: the RBD variation to use for the RBD analysis. See [`RBDVariation`](@ref). +- `num_harmonics::Int`: the number of harmonics to use from the Fourier transform for the RBD analysis. + +# Examples +Note: any keyword arguments in the `RBD` constructor are passed to [`RBDVariation`](@ref), except for the `num_harmonics` keyword argument. +If `num_harmonics` is not specified, it defaults to 6. +``` +RBD(15) # 15 points from the Sobol' sequence +RBD(15; num_harmonics=10) # use 10 harmonics +RBD(15; use_sobol=false) # opt out of using the Sobol' sequence, instead using a random sequence in each dimension +``` +"""""" +struct RBD <: GSAMethod #! the prime symbol is used to avoid conflict with the Sobol module + rbd_variation::RBDVariation + num_harmonics::Int +end + +RBD(n::Integer; num_harmonics::Integer=6, kwargs...) = RBD(RBDVariation(n; kwargs...), num_harmonics) + +"""""" + RBDSampling + +Store the information that comes out of a Random Balance Design (RBD) global sensitivity analysis. + +# Fields +- `sampling::Sampling`: the sampling used in the sensitivity analysis. +- `monad_ids_df::DataFrame`: the DataFrame of monad IDs that define the scheme of the sensitivity analysis. +- `results::Dict{Function, GlobalSensitivity.SobolResult}`: the results of the sensitivity analysis for each function. +- `num_harmonics::Int`: the number of harmonics used in the Fourier transform. +- `num_cycles::Union{Int, Rational}`: the number of cycles used for each parameter. +"""""" +struct RBDSampling <: GSASampling + sampling::Sampling + monad_ids_df::DataFrame + results::Dict{Function, Vector{<:Real}} + num_harmonics::Int + num_cycles::Union{Int, Rational} +end + +RBDSampling(sampling::Sampling, monad_ids_df::DataFrame, num_cycles; num_harmonics::Int=6) = RBDSampling(sampling, monad_ids_df, Dict{Function, GlobalSensitivity.SobolResult}(), num_harmonics, num_cycles) + +function Base.show(io::IO, rbd_sampling::RBDSampling) + println(io, ""RBD sampling"") + println(io, ""------------"") + println(io, rbd_sampling.sampling) + println(io, ""Number of harmonics: $(rbd_sampling.num_harmonics)"") + println(io, ""Number of cycles (1/2 or 1): $(rbd_sampling.num_cycles)"") + println(io, ""GSA functions:"") + for f in keys(rbd_sampling.results) + println(io, "" $f"") + end +end + +function runSensitivitySampling(method::RBD, inputs::InputFolders, pv::ParsedVariations; reference_variation_id::VariationID=VariationID(inputs), + ignore_indices::AbstractVector{<:Integer}=Int[], force_recompile::Bool=false, prune_options::PruneOptions=PruneOptions(), n_replicates::Int=1, use_previous::Bool=true) + if !isempty(ignore_indices) + error(""RBD does not support ignoring indices...yet? Only Sobolʼ does for now."") + end + add_variations_result = addVariations(method.rbd_variation, inputs, pv, reference_variation_id) + location_variation_ids_dict = add_variations_result.location_variation_ids_dict + monad_dict, monad_ids = variationsToMonads(inputs, location_variation_ids_dict) + monads = monad_dict |> values |> collect + header_line = columnName.(pv.variations) + monad_ids_df = DataFrame(monad_ids, header_line) + sampling = Sampling(monads; n_replicates=n_replicates, use_previous=use_previous) + run(sampling; force_recompile=force_recompile, prune_options=prune_options) + return RBDSampling(sampling, monad_ids_df, method.rbd_variation.num_cycles; num_harmonics=method.num_harmonics) +end + +function calculateGSA!(rbd_sampling::RBDSampling, f::Function) + if f in keys(rbd_sampling.results) + return + end + vals = evaluateFunctionOnSampling(rbd_sampling, f) + if rbd_sampling.num_cycles == 1 // 2 + vals = vcat(vals, vals[end-1:-1:2, :]) + end + ys = fft(vals, 1) .|> abs2 + ys ./= size(vals, 1) + V = sum(ys[2:end, :], dims=1) + Vi = 2 * sum(ys[2:(min(size(ys, 1), rbd_sampling.num_harmonics + 1)), :], dims=1) + rbd_sampling.results[f] = (Vi ./ V) |> vec + return +end + +############# Generic Helper Functions ############# + +"""""" + recordSensitivityScheme(gsa_sampling::GSASampling) + +Record the sampling scheme of the global sensitivity analysis to a CSV file. +"""""" +function recordSensitivityScheme(gsa_sampling::GSASampling) + method = methodString(gsa_sampling) + path_to_csv = joinpath(trialFolder(gsa_sampling.sampling), ""$(method)_scheme.csv"") + return CSV.write(path_to_csv, getMonadIDDataFrame(gsa_sampling); header=true) +end + +"""""" + evaluateFunctionOnSampling(gsa_sampling::GSASampling, f::Function) + +Evaluate the given function on the sampling scheme of the global sensitivity analysis, avoiding duplicate evaluations. +"""""" +function evaluateFunctionOnSampling(gsa_sampling::GSASampling, f::Function) + monad_id_df = getMonadIDDataFrame(gsa_sampling) + value_dict = Dict{Int, Float64}() + vals = zeros(Float64, size(monad_id_df)) + for (ind, monad_id) in enumerate(monad_id_df |> Matrix) + if !haskey(value_dict, monad_id) + simulation_ids = constituentIDs(Monad, monad_id) + sim_values = [f(simulation_id) for simulation_id in simulation_ids] + value = sim_values |> mean + value_dict[monad_id] = value + end + vals[ind] = value_dict[monad_id] + end + return vals +end + +"""""" + variationsToMonads(inputs::InputFolders, variation_ids::Dict{Symbol,Matrix{Int}}) + +Return a dictionary of monads and a matrix of monad IDs based on the given variation IDs. + +For each varied location, a matrix of variation IDs is provided. +This information, together with the `inputs`, identifies the monads to be used. + +# Returns +- `monad_dict::Dict{VariationID, Monad}`: a dictionary of the monads to be used without duplicates. +- `monad_ids::Matrix{Int}`: a matrix of the monad IDs to be used. Matches the shape of the input IDs matrices. +"""""" +function variationsToMonads(inputs::InputFolders, location_variation_ids_dict::Dict{Symbol,Matrix{Int}}) + monad_dict = Dict{VariationID, Monad}() + monad_ids = zeros(Int, size(location_variation_ids_dict |> values |> first)) + for i in eachindex(monad_ids) + monad_variation_id = [loc => location_variation_ids_dict[loc][i] for loc in projectLocations().varied] |> VariationID + if haskey(monad_dict, monad_variation_id) + monad_ids[i] = monad_dict[monad_variation_id].id + continue + end + monad = Monad(inputs, monad_variation_id) + monad_dict[monad_variation_id] = monad + monad_ids[i] = monad.id + end + return monad_dict, monad_ids +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/ic_ecm.jl",".jl","2255","47","using PhysiCellECMCreator + +@compat public createICECMXMLTemplate + +"""""" + createICECMXMLTemplate(folder::String) + +Create folder with a template XML file for IC ECM. + +See the [PhysiCellECMCreator.jl](https://github.com/drbergman-lab/PhysiCellECMCreator.jl) documentation for more information on IC ECM and how this function works outside of PhysiCellModelManager.jl. +This PhysiCellModelManager.jl function runs the `createICECMXMLTemplate` function from PhysiCellECMCreator.jl and then updates the database. +Furthermore, the folder can be passed in just as the name of the folder located in `data/inputs/ics/ecms/` rather than the full path. + +This functionality is run outside of a PhysiCell runtime. +It will not work in PhysiCell! +This function creates a template XML file for IC ECM, showing all the current functionality of this initialization scheme. +The `ID` attribute in `patch` elements is there to allow variations to target specific patches within a layer. +Manually maintain these or you will not be able to vary specific patches effectively. + +Each time a simulation is run that is using a ecm.xml file, a new CSV file will be created. +These will all be stored with `data/inputs/ics/ecms/folder/$(PhysiCellModelManager.locationVariationsFolder(:ic_ecm))` as `ic_ecm_variation_#_s#.csv` where the first `#` is the variation ID associated with variation on the XML file and the second `#` is the simulation ID. +Importantly, no two simulations will use the same CSV file. +"""""" +function createICECMXMLTemplate(folder::String) + if length(splitpath(folder)) == 1 + @assert isInitialized() ""Must supply a full path to the folder if the database is not initialized."" + #! then the folder is just the name of the ics/ecms/folder folder + path_to_folder = locationPath(:ic_ecm, folder) + else + path_to_folder = folder + folder = splitpath(folder)[end] + end + + if isfile(joinpath(path_to_folder, ""ecm.xml"")) + println(""ecm.xml already exists in $path_to_folder. Skipping."") + return folder + end + + PhysiCellECMCreator.createICECMXMLTemplate(path_to_folder) + + #! finish by adding this folder to the database + if isInitialized() + insertFolder(:ic_ecm, folder) + end + + return folder +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/database.jl",".jl","44128","1106","export getAllParameterValues, getParameterValue, printSimulationsTable, simulationsTable + +################## Database Initialization Functions ################## + +"""""" + initializeDatabase() + +Initialize the central database. If the database does not exist, it will be created. +"""""" +function initializeDatabase() + global pcmm_globals + close(centralDB()) #! close the old database connection if it exists + pcmm_globals.db = SQLite.DB(centralDB().file) + SQLite.transaction(centralDB(), ""EXCLUSIVE"") + try + createSchema() + catch e + SQLite.rollback(centralDB()) + println(""Error initializing database: $e"") + pcmm_globals.initialized = false + else + SQLite.commit(centralDB()) + pcmm_globals.initialized = true + end +end + +"""""" + reinitializeDatabase() + +Reinitialize the database by searching through the `data/inputs` directory to make sure all are present in the database. +"""""" +function reinitializeDatabase() + global pcmm_globals + if !isInitialized() + println(""Database not initialized. Initialize the database first before re-initializing. `initializeModelManager` will do this."") + return + end + pcmm_globals.initialized = false #! reset the initialized flag until the database is reinitialized + initializeDatabase() + return isInitialized() +end + +"""""" + createSchema() + +Create the schema for the database. This includes creating the tables and populating them with data. +"""""" +function createSchema() + #! make sure necessary directories are present + @assert necessaryInputsPresent() ""Necessary input folders are not present. Please check the inputs directory."" + + #! initialize and populate physicell_versions table + createPCMMTable(""physicell_versions"", physicellVersionsSchema()) + pcmm_globals.current_physicell_version_id = resolvePhysiCellVersionID() + + #! initialize tables for all inputs + for (location, location_dict) in pairs(inputsDict()) + table_name = locationTableName(location) + table_schema = """""" + $(locationIDName(location)) INTEGER PRIMARY KEY, + folder_name UNIQUE, + description TEXT + """""" + createPCMMTable(table_name, table_schema) + + location_path = locationPath(location) + @assert !location_dict[""required""] || isdir(location_path) ""$location_path is required but not found. This is where to put the folders for $table_name."" + folders = readdir(location_path; sort=false) |> filter(x -> isdir(joinpath(location_path, x))) + for folder in folders + insertFolder(location, folder) + end + end + + simulations_schema = """""" + simulation_id INTEGER PRIMARY KEY, + physicell_version_id INTEGER, + $(inputIDsSubSchema()), + $(inputVariationIDsSubSchema()), + status_code_id INTEGER, + $(abstractSamplingForeignReferenceSubSchema()), + FOREIGN KEY (status_code_id) + REFERENCES status_codes (status_code_id) + """""" + createPCMMTable(""simulations"", simulations_schema) + + #! initialize monads table + createPCMMTable(""monads"", monadsSchema()) + + #! initialize samplings table + createPCMMTable(""samplings"", samplingsSchema()) + + #! initialize trials table + trials_schema = """""" + trial_id INTEGER PRIMARY KEY, + datetime TEXT, + description TEXT + """""" + createPCMMTable(""trials"", trials_schema) + + createDefaultStatusCodesTable() +end + +"""""" + necessaryInputsPresent() + +Check if all necessary input folders are present in the database. +"""""" +function necessaryInputsPresent() + success = true + for (location, location_dict) in pairs(inputsDict()) + if !location_dict[""required""] + continue + end + + location_path = locationPath(location) + if !isdir(location_path) + println(""No $location_path found. This is where to put the folders for $(locationFolder(location))."") + success = false + end + end + return success +end + +"""""" + physicellVersionsSchema() + +Create the schema for the physicell_versions table. This includes the columns and their types. +"""""" +function physicellVersionsSchema() + return """""" + physicell_version_id INTEGER PRIMARY KEY, + repo_owner TEXT, + tag TEXT, + commit_hash TEXT UNIQUE, + date TEXT + """""" +end + +"""""" + monadsSchema() + +Create the schema for the monads table. This includes the columns and their types. +"""""" +function monadsSchema() + return """""" + monad_id INTEGER PRIMARY KEY, + physicell_version_id INTEGER, + $(inputIDsSubSchema()), + $(inputVariationIDsSubSchema()), + $(abstractSamplingForeignReferenceSubSchema()), + UNIQUE (physicell_version_id, + $(join([locationIDName(k) for k in keys(inputsDict())], "",\n"")), + $(join([locationVariationIDName(k) for (k, d) in pairs(inputsDict()) if any(d[""varied""])], "",\n"")) + ) + """""" +end + +"""""" + inputIDsSubSchema() + +Create the part of the schema corresponding to the input IDs. +"""""" +function inputIDsSubSchema() + return join([""$(locationIDName(k)) INTEGER"" for k in keys(inputsDict())], "",\n"") +end + +"""""" + inputVariationIDsSubSchema() + +Create the part of the schema corresponding to the varied inputs and their IDs. +"""""" +function inputVariationIDsSubSchema() + return join([""$(locationVariationIDName(k)) INTEGER"" for (k, d) in pairs(inputsDict()) if any(d[""varied""])], "",\n"") +end + +"""""" + abstractSamplingForeignReferenceSubSchema() + +Create the part of the schema containing foreign key references for the simulations, monads, and samplings tables. +"""""" +function abstractSamplingForeignReferenceSubSchema() + return """""" + FOREIGN KEY (physicell_version_id) + REFERENCES physicell_versions (physicell_version_id), + $(join(["""""" + FOREIGN KEY ($(locationIDName(k))) + REFERENCES $(locationTableName(k)) ($(locationIDName(k)))\ + """""" for k in keys(inputsDict())], "",\n"")) + """""" +end + +"""""" + samplingsSchema() + +Create the schema for the samplings table. This includes the columns and their types. +"""""" +function samplingsSchema() + return """""" + sampling_id INTEGER PRIMARY KEY, + physicell_version_id INTEGER, + $(inputIDsSubSchema()), + $(abstractSamplingForeignReferenceSubSchema()) + """""" +end + +"""""" + metadataDescription(path_to_folder::AbstractString) + +Get the description from the metadata.xml file in the given folder using the `description` element as a child element of the root element. +"""""" +function metadataDescription(path_to_folder::AbstractString) + path_to_metadata = joinpath(path_to_folder, ""metadata.xml"") + description = """" + if isfile(path_to_metadata) + xml_doc = parse_file(path_to_metadata) + metadata = root(xml_doc) + description_element = find_element(metadata, ""description"") + if !isnothing(description_element) + description = content(find_element(metadata, ""description"")) + end + free(xml_doc) + end + return description +end + +"""""" + createPCMMTable(table_name::String, schema::String; db::SQLite.DB=centralDB()) + +Create a table in the database with the given name and schema. The table will be created if it does not already exist. + +The table name must end in ""s"" to help normalize the ID names for these entries. +The schema must have a PRIMARY KEY named as the table name without the ""s"" followed by ""_id."" +"""""" +function createPCMMTable(table_name::String, schema::String; db::SQLite.DB=centralDB()) + #! check that table_name ends in ""s"" + if last(table_name) != 's' + s = ""Table name must end in 's'."" + s *= ""\n\tThis helps to normalize what the id names are for these entries."" + s *= ""\n\tYour table $(table_name) does not end in 's'."" + throw(ErrorException(s)) + end + #! check that schema has PRIMARY KEY named as table_name without the s followed by _id + id_name = tableIDName(table_name) + if !occursin(""$(id_name) INTEGER PRIMARY KEY"", schema) + s = ""Schema must have PRIMARY KEY named as $(id_name)."" + s *= ""\n\tThis helps to normalize what the id names are for these entries."" + s *= ""\n\tYour schema $(schema) does not have \""$(id_name) INTEGER PRIMARY KEY\""."" + throw(ErrorException(s)) + end + SQLite.execute(db, ""CREATE TABLE IF NOT EXISTS $(table_name) ( + $(schema) + ) + "") + return +end + +"""""" + tableIDName(table::String; strip_s::Bool=true) + +Return the name of the ID column for the table as a String. +If `strip_s` is `true`, it removes the trailing ""s"" from the table name. + +# Examples +```jldoctest +julia> PhysiCellModelManager.tableIDName(""configs"") +""config_id"" +``` +"""""" +function tableIDName(table::String; strip_s::Bool=true) + if strip_s + @assert last(table) == 's' ""Table name must end in 's' to strip it."" + table = table[1:end-1] + end + return ""$(table)_id"" +end + +"""""" + insertFolder(location::Symbol, folder::String, description::String="""") + +Insert a folder into the database. If the folder already exists, it will be ignored. + +If the folder already has a description from the metadata.xml file, that description will be used instead of the one provided. +"""""" +function insertFolder(location::Symbol, folder::String, description::String="""") + path_to_folder = locationPath(location, folder) + old_description = metadataDescription(path_to_folder) + description = isempty(old_description) ? description : old_description + + stmt_str = ""INSERT OR IGNORE INTO $(locationTableName(location)) (folder_name, description) VALUES (:folder, :description);"" + params = (; :folder => folder, :description => description) + stmt = SQLite.Stmt(centralDB(), stmt_str) + DBInterface.execute(stmt, params) + if !folderIsVaried(location, folder) + return + end + db_variations = joinpath(path_to_folder, locationVariationsDBName(location)) |> SQLite.DB # create the variations database + location_variation_id_name = locationVariationIDName(location) + table_name = locationVariationsTableName(location) + createPCMMTable(table_name, ""$location_variation_id_name INTEGER PRIMARY KEY, par_key BLOB UNIQUE""; db=db_variations) + DBInterface.execute(db_variations, ""INSERT OR IGNORE INTO $table_name ($location_variation_id_name, par_key) VALUES(?, ?)"", (0, UInt8[])) + input_folder = InputFolder(location, folder) + prepareBaseFile(input_folder) +end + +"""""" + recognizedStatusCodes() + +Return the recognized status codes for simulations. +"""""" +recognizedStatusCodes() = [""Not Started"", ""Queued"", ""Running"", ""Completed"", ""Failed""] + +"""""" + createDefaultStatusCodesTable() + +Create the default status codes table in the database. +"""""" +function createDefaultStatusCodesTable() + status_codes_schema = """""" + status_code_id INTEGER PRIMARY KEY, + status_code TEXT UNIQUE + """""" + createPCMMTable(""status_codes"", status_codes_schema) + status_codes = recognizedStatusCodes() + for status_code in status_codes + DBInterface.execute(centralDB(), ""INSERT OR IGNORE INTO status_codes (status_code) VALUES ('$status_code');"") + end +end + +"""""" + statusCodeID(status_code::String) + +Get the ID of a status code from the database. +"""""" +function statusCodeID(status_code::String) + @assert status_code in recognizedStatusCodes() ""Status code $(status_code) is not recognized. Must be one of $(recognizedStatusCodes())."" + query = constructSelectQuery(""status_codes"", ""WHERE status_code='$status_code';""; selection=""status_code_id"") + return queryToDataFrame(query; is_row=true) |> x -> x[1,:status_code_id] +end + +"""""" + isStarted(simulation_id::Int[; new_status_code::Union{Missing,String}=missing]) + +Check if a simulation has been started. Can also pass in a `Simulation` object in place of the simulation ID. + +If `new_status_code` is provided, update the status of the simulation to this value. +The check and status update are done in a transaction to ensure that the status is not changed by another process. +"""""" +function isStarted(simulation_id::Int; new_status_code::Union{Missing,String}=missing) + query = constructSelectQuery(""simulations"", ""WHERE simulation_id=$(simulation_id)""; selection=""status_code_id"") + mode = ismissing(new_status_code) ? ""DEFERRED"" : ""EXCLUSIVE"" #! if we are possibly going to update, then set to exclusive mode + SQLite.transaction(centralDB(), mode) + status_code = queryToDataFrame(query; is_row=true) |> x -> x[1,:status_code_id] + is_started = status_code != statusCodeID(""Not Started"") + if !ismissing(new_status_code) && !is_started + query = ""UPDATE simulations SET status_code_id=$(statusCodeID(new_status_code)) WHERE simulation_id=$(simulation_id);"" + DBInterface.execute(centralDB(), query) + end + SQLite.commit(centralDB()) + + return is_started +end + +isStarted(simulation::Simulation; new_status_code::Union{Missing,String}=missing) = isStarted(simulation.id; new_status_code=new_status_code) + +################## DB Interface Functions ################## + +"""""" + locationVariationsDatabase(location::Symbol, folder::String) + +Return the variations database for the location and folder. + +The second argument can alternatively be the ID of the folder or an AbstractSampling object (simulation, monad, or sampling) using that folder. +"""""" +function locationVariationsDatabase(location::Symbol, folder::String) + if folder == """" + return nothing + end + path_to_db = joinpath(locationPath(location, folder), locationVariationsDBName(location)) + if !isfile(path_to_db) + return missing + end + return path_to_db |> SQLite.DB +end + +function locationVariationsDatabase(location::Symbol, id::Int) + folder = inputFolderName(location, id) + return locationVariationsDatabase(location, folder) +end + +function locationVariationsDatabase(location::Symbol, S::AbstractSampling) + folder = S.inputs[location].folder + return locationVariationsDatabase(location, folder) +end + +########### Retrieving Database Information Functions ########### + +"""""" + queryToDataFrame(query::String; db::SQLite.DB=centralDB(), is_row::Bool=false) + +Execute a query against the database and return the result as a DataFrame. + +If `is_row` is true, the function will assert that the result has exactly one row, i.e., a unique result. +"""""" +function queryToDataFrame(query::String; db::SQLite.DB=centralDB(), is_row::Bool=false) + df = DBInterface.execute(db, query) |> DataFrame + if is_row + @assert size(df,1)==1 ""Did not find exactly one row matching the query:\n\tDatabase file: $(db)\n\tQuery: $(query)\nResult: $(df)"" + end + return df +end + +"""""" + stmtToDataFrame(stmt::SQLite.Stmt, params; is_row::Bool=false) + stmtToDataFrame(stmt_str::AbstractString, params; db::SQLite.DB=centralDB(), is_row::Bool=false) + +Execute a prepared statement with the given parameters and return the result as a DataFrame. +Compare with [`queryToDataFrame`](@ref). + +The `params` argument must be a type that can be used with `DBInterface.execute(::SQLite.Stmt, params)`. +See the [SQLite.jl documentation](https://juliadatabases.org/SQLite.jl/stable/) for details. + +If `is_row` is true, the function will assert that the result has exactly one row, i.e., a unique result. + +# Arguments +- `stmt::SQLite.Stmt`: A prepared statement object. This includes the database connection and the SQL statement. +- `stmt_str::AbstractString`: A string containing the SQL statement to prepare. +- `params`: The parameters to bind to the prepared statement. Must be either + - `Vector` or `Tuple` and match the order of the placeholders in the SQL statement. + - `NamedTuple` or `Dict` with keys matching the named placeholders in the SQL statement. + +# Keyword Arguments +- `db::SQLite.DB`: The database connection to use. Defaults to the central database. Unnecessary if using a prepared statement. +- `is_row::Bool`: If true, asserts that the result has exactly one row. Defaults to false. +"""""" +function stmtToDataFrame(stmt::SQLite.Stmt, params; is_row::Bool=false) + df = DBInterface.execute(stmt, params) |> DataFrame + if is_row + @assert size(df,1)==1 ""Did not find exactly one row matching the statement."" + end + return df +end + +function stmtToDataFrame(stmt_str::AbstractString, params; db::SQLite.DB=centralDB(), is_row::Bool=false) + stmt = SQLite.Stmt(db, stmt_str) + try + return stmtToDataFrame(stmt, params; is_row=is_row) + catch e + msg = """""" + Error executing SQLite statement: + Statement: $stmt_str + Parameters: $params + Database: $(db.file) + Is row: $is_row + """""" + println(msg) + rethrow(e) + end +end + +"""""" + constructSelectQuery(table_name::String, condition_stmt::String=""""; selection::String=""*"") + +Construct a SELECT query for the given table name, condition statement, and selection. +"""""" +constructSelectQuery(table_name::String, condition_stmt::String=""""; selection::String=""*"") = ""SELECT $(selection) FROM $(table_name) $(condition_stmt);"" + +"""""" + inputFolderName(location::Symbol, id::Int) + +Retrieve the folder name associated with the given location and ID. +"""""" +function inputFolderName(location::Symbol, id::Int) + if id == -1 + return """" + end + + query = constructSelectQuery(locationTableName(location), ""WHERE $(locationIDName(location))=$(id)""; selection=""folder_name"") + return queryToDataFrame(query; is_row=true) |> x -> x.folder_name[1] +end + +"""""" + inputFolderID(location::Symbol, folder::String) + +Retrieve the ID of the folder associated with the given location and folder name. +"""""" +function inputFolderID(location::Symbol, folder::String) + if folder == """" + return -1 + end + primary_key_string = locationIDName(location) + + stmt_str = constructSelectQuery(locationTableName(location), ""WHERE folder_name=(:folder)""; selection=primary_key_string) + params = (; :folder => folder) + df = stmtToDataFrame(stmt_str, params; is_row=true) + return df[1, primary_key_string] +end + +"""""" + tableExists(table_name::String; db::SQLite.DB=centralDB()) + +Check if a table with the given name exists in the database. +"""""" +function tableExists(table_name::String; db::SQLite.DB=centralDB()) + valid_table_names = DBInterface.execute(db, ""SELECT name FROM sqlite_master WHERE type='table';"") |> DataFrame |> x -> x.name + return table_name in valid_table_names +end + +"""""" + columnsExist(column_names::AbstractVector{<:AbstractString}, table_name::String; kwargs...) + columnsExist(column_names::AbstractVector{<:AbstractString}, valid_column_names::AbstractVector{<:AbstractString}) + +Check if all columns in `column_names` exist in the specified table in the database. + +Alternatively, if the `valid_column_names` needs to be reused in the caller, it can be passed directly. +Keyword arguments (such as `db`) are forwarded to [`tableColumns`](@ref). +"""""" +function columnsExist(column_names::AbstractVector{<:AbstractString}, table_name::String; kwargs...) + valid_column_names = tableColumns(table_name; kwargs...) + return columnsExist(column_names, valid_column_names) +end + +function columnsExist(column_names::AbstractVector{<:AbstractString}, valid_column_names::AbstractVector{<:AbstractString}) + return all(c -> c in valid_column_names, column_names) +end + +"""""" + tableColumns(table_name::String; db::SQLite.DB=centralDB()) + +Return the names of the columns in the specified table in the database. +"""""" +function tableColumns(table_name::String; db::SQLite.DB=centralDB()) + @assert tableExists(table_name; db=db) ""Table $(table_name) does not exist in the database."" + return queryToDataFrame(""PRAGMA table_info($(table_name));"", db=db) |> x -> x.name +end + +"""""" + getParameterValue(M::AbstractMonad, xp::XMLPath) + getParameterValue(M::AbstractMonad, xml_path::AbstractVector{<:AbstractString}) + getParameterValue(simulation_id::Int, xp) + +Get the parameter value for the given XML path from the simulation/monad's variations database if it exists, otherwise from the base XML file. + +- If the value is a boolean string (""true"" or ""false""), it will be returned as a Bool. +- Otherwise, if it can be parsed as a Float64, it will be returned as such; otherwise, it will be returned as-is. +"""""" +function getParameterValue(M::AbstractMonad, xp::XMLPath) + location = variationLocation(xp) + db = locationVariationsDatabase(location, M) + @assert !isnothing(db) ""XMLPath $(xp.xml_path) corresponds to location $(location), but that location is not being varied in this $(nameof(typeof(M)))."" + @assert !ismissing(db) ""Variations database for location $(location) not found in folder $(M.inputs[location].folder)."" + if columnsExist([columnName(xp)], locationVariationsTableName(location); db=db) + query = constructSelectQuery(locationVariationsTableName(location), ""WHERE $(locationVariationIDName(location))=$(M.variation_id[location])""; selection=""\"""" * columnName(xp) * ""\"""") + df = queryToDataFrame(query; db=db, is_row=true) + v = df[1, columnName(xp)] + if v ∈ (""true"", ""false"") + return v == ""true"" + end + return v + else + path_to_xml = prepareBaseFile(M.inputs[location]) + xml_doc = parse_file(path_to_xml) + v = getSimpleContent(xml_doc, xp.xml_path) + free(xml_doc) + return parseValueFromString(v) + end +end + +function getParameterValue(M::AbstractMonad, xml_path::AbstractVector{<:AbstractString}) + xp = XMLPath(xml_path) + return getParameterValue(M, xp) +end + +function getParameterValue(simulation_id::Int, xp) + simulation = Simulation(simulation_id) + return getParameterValue(simulation, xp) +end + +"""""" + getAllParameterValues(simulation_id::Int) + getAllParameterValues(S::AbstractSampling) + +Get all parameter values for the given simulation, monad, or sampling as a DataFrame. +Simulation ID can also be passed directly as an integer. + +# Identifying attributes +If sibling elements have identical tags, attributes are programmatically searched to find one that can be used to identify them. +Priority is given to ""name"", ""ID"", and ""id"" attributes. +If sibling elements cannot be uniquely identified by an attribute, artificial IDs will be added to the XML paths to ensure uniqueness for the column names. +These will show up as `:temp_id:` in the column names. +Search for them with `contains(col_name, "":temp_id:"")`. +Note: these are not added to the XML files themselves. +Users must manually insert such artificial IDs into their XML files to use PCMM to vary those parameters. + +# Converting column names into XML paths +To convert the column names in the returned DataFrame back into XML paths, split the column names by '/': + +```julia +df = getAllParameterValues(simulation_id) +col1 = names(df)[1] +xml_path = split(col1, '/') +``` + +Alternatively, the internal [`columnNameToXMLPath`](@ref) function can be used. + +```julia +xml_path = PhysiCellModelManager.columnNameToXMLPath(col1) +``` + +Conversion back can be done either with `join` or the `columnName` function: + +```julia +xml_path = [""overall"", ""max_time""] +col_name = join(xml_path, '/') +# or +col_name = PhysiCellModelManager.columnName(xml_path) +``` +"""""" +function getAllParameterValues(S::Sampling) + monad_ids = monadIDs(S) + dfs = [getAllParameterValues(Monad(monad_id)) for monad_id in monad_ids] + df = vcat(dfs...) + df.monad_id = monad_ids + return df +end + +function getAllParameterValues(M::AbstractMonad) + D = Dict{String,Any}() + for (loc, input_folder) in pairs(M.inputs.input_folders) + if !input_folder.varied + continue # only get values for varied inputs + end + + if isempty(input_folder.folder) + continue # skip missing inputs + end + + path_to_xml = createXMLFile(loc, M) + xml_doc = parse_file(path_to_xml) + xml_root = root(xml_doc) + current_path = String[] + + recurseToGetParameterValues!(D, current_path, xml_root) + free(xml_doc) + end + return DataFrame(D) +end + +function getAllParameterValues(simulation_id::Int) + simulation = Simulation(simulation_id) + return getAllParameterValues(simulation) +end + +"""""" + recurseToGetParameterValues!(D::Dict{String,Any}, current_path::Vector{String}, element::XMLElement) + +Recursively traverse the XML element tree to extract parameter values and populate the dictionary `D` with XML paths as keys and their corresponding values. +Used by [`getAllParameterValues`](@ref). +"""""" +function recurseToGetParameterValues!(D::Dict{String,Any}, current_path::Vector{String}, element::XMLElement) + if elementIsTerminal(element) + v = content(element) + key = columnName(XMLPath(current_path)) + D[key] = parseValueFromString(v) + return + end + child_tags = [name(c) for c in child_elements(element)] + priority_attributes = (""name"", ""ID"", ""id"") + for tag in unique(child_tags) + these_children = [c for c in child_elements(element) if name(c) == tag] + common_attributes = intersect([collect(attributes_dict(c) |> keys) for c in these_children]...) + if length(these_children) == 1 + priority_attribute_found = false + for attr in priority_attributes + if attr in common_attributes + priority_attribute_found = true + recurseToGetParameterValues!(D, [current_path; ""$tag:$attr:$(attribute(these_children[1], attr))""], these_children[1]) + break + end + end + if !priority_attribute_found + # no mandatory attribute found, just use the tag + recurseToGetParameterValues!(D, [current_path; tag], these_children[1]) + end + continue + end + unique_attribute = nothing + for attr in priority_attributes + if !(attr in common_attributes) + continue # skip if any child is missing this attribute + end + attr_values = [attribute(c, attr) for c in these_children] + if length(unique(attr_values)) == length(these_children) + unique_attribute = attr + break + end + end + if isnothing(unique_attribute) # try any common attribute + for attr in common_attributes + attr_values = [attribute(c, attr) for c in these_children] + if length(unique(attr_values)) == length(these_children) + unique_attribute = attr + break + end + end + end + if isnothing(unique_attribute) + @warn ""Could not find unique attribute to distinguish between multiple children with tag $(tag) under path $(columnName(current_path)). Adding artificial IDs to make unique keys."" + for (i, c) in enumerate(these_children) + recurseToGetParameterValues!(D, [current_path; ""$tag:temp_id:$i""], c) + end + else + for c in these_children + recurseToGetParameterValues!(D, [current_path; ""$tag:$unique_attribute:$(attribute(c, unique_attribute))""], c) + end + end + end +end + +"""""" + parseValueFromString(v::String) + +Helper function to parse a value from a string. +If the string is ""true"" or ""false"", it returns a Bool. +If the string can be parsed as a Float64, it returns a Float64. +Otherwise, it returns the original string. +"""""" +function parseValueFromString(v::String) + if v ∈ (""true"", ""false"") + return v == ""true"" + elseif tryparse(Float64, v) |> !isnothing + return parse(Float64, v) + end + return v +end + +########### Summarizing Database Functions ########### + +"""""" + variationIDs(location::Symbol, S::AbstractSampling) + +Return a vector of the variation IDs for the given location associated with `S`. +"""""" +variationIDs(location::Symbol, M::AbstractMonad) = [M.variation_id[location]] +variationIDs(location::Symbol, sampling::Sampling) = [monad.variation_id[location] for monad in sampling.monads] + +"""""" + locationVariationsTable(query::String, db::SQLite.DB; remove_constants::Bool=false) + +Return a DataFrame containing the variations table for the given query and database. + +Remove constant columns if `remove_constants` is true and the DataFrame has more than one row. +"""""" +function locationVariationsTable(query::String, db::SQLite.DB; remove_constants::Bool=false) + df = queryToDataFrame(query, db=db) + select!(df, Not(:par_key)) + if remove_constants && size(df, 1) > 1 + col_names = names(df) + filter!(n -> length(unique(df[!,n])) > 1, col_names) + select!(df, col_names) + end + return df +end + +"""""" + locationVariationsTableName(location::Symbol, variations_database::SQLite.DB, variation_ids::AbstractVector{<:Integer}; remove_constants::Bool=false) + +Return a DataFrame containing the variations table for the given location, variations database, and variation IDs. +"""""" +function locationVariationsTable(location::Symbol, variations_database::SQLite.DB, variation_ids::AbstractVector{<:Integer}; remove_constants::Bool=false) + used_variation_ids = filter(x -> x != -1, variation_ids) #! variation_id = -1 means this input is not even being used + query = constructSelectQuery(locationVariationsTableName(location), ""WHERE $(locationVariationIDName(location)) IN ($(join(used_variation_ids,"","")))"") + df = locationVariationsTable(query, variations_database; remove_constants=remove_constants) + rename!(name -> shortVariationName(location, name), df) + return df +end + +"""""" + locationVariationsTable(location::Symbol, S::AbstractSampling; remove_constants::Bool=false) + +Return a DataFrame containing the variations table for the given location and sampling. +"""""" +function locationVariationsTable(location::Symbol, S::AbstractSampling; remove_constants::Bool=false) + return locationVariationsTable(location, locationVariationsDatabase(location, S), variationIDs(location, S); remove_constants=remove_constants) +end + +"""""" + locationVariationsTable(location::Symbol, ::Nothing, variation_ids::AbstractVector{<:Integer}; kwargs...) + +If the location is not being used, return a DataFrame with all variation IDs set to -1. +"""""" +function locationVariationsTable(location::Symbol, ::Nothing, variation_ids::AbstractVector{<:Integer}; kwargs...) + @assert all(x -> x == -1, variation_ids) ""If the $(location) is not being used, then all $(locationVariationIDName(location))s must be -1."" + return DataFrame(shortLocationVariationID(location)=>variation_ids) +end + +"""""" + locationVariationsTable(location::Symbol, ::Missing, variation_ids::AbstractVector{<:Integer}; kwargs...) + +If the location folder does not contain a variations database, return a DataFrame with all variation IDs set to 0. +"""""" +function locationVariationsTable(location::Symbol, ::Missing, variation_ids::AbstractVector{<:Integer}; kwargs...) + @assert all(x -> x == 0, variation_ids) ""If the $(location)_folder does not contain a $(locationVariationsDBName(location)), then all $(locationVariationIDName(location))s must be 0."" + return DataFrame(shortLocationVariationID(location)=>variation_ids) +end + +"""""" + addFolderNameColumns!(df::DataFrame) + +Add the folder names to the DataFrame for each location in the DataFrame. +"""""" +function addFolderNameColumns!(df::DataFrame) + for (location, location_dict) in pairs(inputsDict()) + if !(locationIDName(location) in names(df)) + continue + end + unique_ids = unique(df[!, locationIDName(location)]) + folder_names_dict = [id => inputFolderName(location, id) for id in unique_ids] |> Dict{Int,String} + if location_dict[""required""] + @assert !any(folder_names_dict |> values .|> isempty) ""Some $(location) folders are empty/missing, but they are required."" + end + df[!, ""$(location)_folder""] .= [folder_names_dict[id] for id in df[!, locationIDName(location)]] + end + return df +end + +"""""" + simulationsTableFromQuery(query::String; remove_constants::Bool=true, sort_by=String[], sort_ignore=[:SimID; shortLocationVariationID.(projectLocations().varied)]) + +Return a DataFrame containing the simulations table for the given query. + +By default, will ignore the simulation ID and the variation IDs for the varied locations when sorting. +The sort order can be controlled by the `sort_by` and `sort_ignore` keyword arguments. + +By default, constant columns (columns with the same value for all simulations) will be removed (unless there is only one simulation). +Set `remove_constants` to false to keep these columns. + +# Arguments +- `query::String`: The SQL query to execute. + +# Keyword Arguments +- `remove_constants::Bool`: If true, removes columns that have the same value for all simulations. Defaults to true. +- `sort_by::Vector{String}`: A vector of column names to sort the table by. Defaults to all columns. To populate this argument, it is recommended to first print the table to see the column names. +- `sort_ignore::Vector{String}`: A vector of column names to ignore when sorting. Defaults to the simulation ID and the variation IDs associated with the simulations. +"""""" +function simulationsTableFromQuery(query::String; + remove_constants::Bool=true, + sort_by=String[], + sort_ignore=[:SimID; shortLocationVariationID.(projectLocations().varied)]) + #! preprocess sort kwargs + sort_by = (sort_by isa Vector ? sort_by : [sort_by]) .|> Symbol + sort_ignore = (sort_ignore isa Vector ? sort_ignore : [sort_ignore]) .|> Symbol + + df = queryToDataFrame(query) + id_col_names_to_remove = names(df) #! a bunch of ids that we don't want to show + + filter!(n -> n != ""simulation_id"", id_col_names_to_remove) #! we will remove all the IDs other than the simulation ID + addFolderNameColumns!(df) #! add the folder columns + + #! handle each of the varying inputs + for loc in projectLocations().varied + df = appendVariations(loc, df) + end + + select!(df, Not(id_col_names_to_remove)) #! now remove the variation ID columns + rename!(df, :simulation_id => :SimID) + col_names = names(df) + if remove_constants && size(df, 1) > 1 + filter!(n -> length(unique(df[!, n])) > 1, col_names) + select!(df, col_names) + end + if isempty(sort_by) + sort_by = deepcopy(col_names) + end + setdiff!(sort_by, sort_ignore) #! remove the columns we don't want to sort by + filter!(n -> n in col_names, sort_by) #! remove any columns that are not in the DataFrame + sort!(df, sort_by) + return df +end + +"""""" + appendVariations(location::Symbol, df::DataFrame) + +Add the varied parameters associated with the `location` to `df`. +"""""" +function appendVariations(location::Symbol, df::DataFrame) + short_var_name = shortLocationVariationID(location) + var_df = DataFrame(short_var_name => Int[], :folder_name => String[]) + unique_tuples = [(row[""$(location)_folder""], row[locationVariationIDName(location)]) for row in eachrow(df)] |> unique + for unique_tuple in unique_tuples + temp_df = locationVariationsTable(location, locationVariationsDatabase(location, unique_tuple[1]), [unique_tuple[2]]; remove_constants=false) + temp_df[!,:folder_name] .= unique_tuple[1] + append!(var_df, temp_df, cols=:union) + end + folder_pair = (""$(location)_folder"" |> Symbol) => :folder_name + id_pair = (locationVariationIDName(location) |> Symbol) => short_var_name + return outerjoin(df, var_df, on = [folder_pair, id_pair]) +end + +"""""" + simulationsTable(args...; kwargs...) + +Return a DataFrame with the simulation data calling [`simulationsTableFromQuery`](@ref) with those keyword arguments. + +There are three options for `args...`: +- `Simulation`, `Monad`, `Sampling`, `Trial`, any array (or vector) of such, or any number of such objects. +- A vector of simulation IDs. +- If omitted, creates a DataFrame for all the simulations. +"""""" +function simulationsTable(T::AbstractArray{<:AbstractTrial}; kwargs...) + query = constructSelectQuery(""simulations"", ""WHERE simulation_id IN ($(join(simulationIDs(T),"","")));"") + return simulationsTableFromQuery(query; kwargs...) +end + +simulationsTable(T::AbstractTrial, Ts::Vararg{AbstractTrial}; kwargs...) = simulationsTable([T; Ts...]; kwargs...) + +function simulationsTable(simulation_ids::AbstractVector{<:Integer}; kwargs...) + assertInitialized() + query = constructSelectQuery(""simulations"", ""WHERE simulation_id IN ($(join(simulation_ids,"","")));"") + return simulationsTableFromQuery(query; kwargs...) +end + +function simulationsTable(; kwargs...) + assertInitialized() + query = constructSelectQuery(""simulations"") + return simulationsTableFromQuery(query; kwargs...) +end + +########### Printing Database Functions ########### + +"""""" + printSimulationsTable(args...; sink=println, kwargs...) + +Print a table of simulations and their varied values. See [`simulationsTable`](@ref) for details on the arguments and keyword arguments. + +First, create a DataFrame by calling [`simulationsTable`](@ref) using `args...` and `kwargs...`. +Then, pass the DataFrame to the `sink` function. + +# Arguments +See [`simulationsTable`](@ref) for details on the arguments. + +# Keyword Arguments +- `sink`: A function to print the table. Defaults to `println`. Note, the table is a DataFrame, so you can also use `CSV.write` to write the table to a CSV file. +See [`simulationsTable`](@ref) for details on the remaining keyword arguments. + +# Examples +```julia +printSimulationsTable([simulation_1, monad_3, sampling_2, trial_1]) +``` +```julia +sim_ids = [1, 2, 3] # vector of simulation IDs +printSimulationsTable(sim_ids; remove_constants=false) # include constant columns +``` +```julia +using CSV +printSimulationsTable(; sink=CSV.write(""temp.csv"")) # write data for all simulations into temp.csv +``` +"""""" +function printSimulationsTable(args...; sink=println, kwargs...) + assertInitialized() + simulationsTable(args...; kwargs...) |> sink +end + +########### Database Validation Functions ########### + +"""""" + validateParsBytes(db::SQLite.DB, table_name::String) + +Validate that the `par_key` bytes in the given table match the expected values based on the other columns. +"""""" +function validateParsBytes(db::SQLite.DB, table_name::String) + df = queryToDataFrame(""SELECT * FROM $table_name;"", db=db) + @assert names(df)[1] == tableIDName(table_name) ""$(table_name) does not have the primary key as the first column."" + @assert names(df)[2] == ""par_key"" ""$(table_name) does not have par_key as the second column."" + for row in eachrow(df) + par_key = row[:par_key] + vals = [row[3:end]...] + vals[vals .== ""true""] .= 1.0 + vals[vals .== ""false""] .= 0.0 + expected_par_key = reinterpret(UInt8, Vector{Float64}(vals)) + @assert par_key == expected_par_key """""" + par_key does not match the expected values for $(table_name) ID $(row[1]). + Expected: $(expected_par_key) + Found: $(par_key) + """""" + end +end + +"""""" + databaseDiagnostics() + +Run diagnostics on the central database to check for consistency and integrity. +"""""" +function databaseDiagnostics() + assertInitialized() + consensus_ids = Dict{Type{<:AbstractTrial}, Set{Int}}() + + #! check that all tables exist and that all entries in the database have corresponding folders + db_ids = Dict{Type{<:AbstractTrial}, Set{Int}}() + folder_ids = Dict{Type{<:AbstractTrial}, Set{Int}}() + missing_dirs = Dict{Type{<:AbstractTrial}, Set{Int}}() + missing_db_entries = Dict{Type{<:AbstractTrial}, Set{Int}}() + for T in (Simulation, Monad, Sampling, Trial) + table_name = lowerClassString(T) * ""s"" + db = centralDB() + @assert tableExists(table_name; db=db) ""Table $(table_name) does not exist in $(basename(db.file)). Database is not complete."" + query = constructSelectQuery(table_name; selection=tableIDName(table_name)) + df = queryToDataFrame(query; db=db) + db_ids[T] = Set(df[!, 1]) + + path_to_output_folder = joinpath(dataDir(), ""outputs"", ""$(lowerClassString(T))s"") + if isdir(path_to_output_folder) + folders = readdir(joinpath(dataDir(), ""outputs"", ""$(lowerClassString(T))s"")) + else + folders = String[] + end + + folder_ids_found = tryparse.(Int, folders) + filter!(!isnothing, folder_ids_found) + folder_ids[T] = Set(folder_ids_found) + + missing_dirs[T] = setdiff(db_ids[T], folder_ids[T]) + missing_db_entries[T] = setdiff(folder_ids[T], db_ids[T]) + + consensus_ids[T] = intersect(db_ids[T], folder_ids[T]) + end + + warning_msg_dirs = """" + for (T, missing_ids) in pairs(missing_dirs) + if !isempty(missing_ids) + warning_msg_dirs *= ""- $(lowerClassString(T))s with IDs: $(sort(collect(missing_ids)))\n"" + end + end + + if !isempty(warning_msg_dirs) + warning_msg_dirs = ""The following have entries in the database but not a corresponding folder. This can happen if the object is created, but never run.\n"" * warning_msg_dirs + @warn warning_msg_dirs + end + + warning_msg_dbs = """" + for (T, missing_ids) in pairs(missing_db_entries) + if !isempty(missing_ids) + warning_msg_dbs *= ""- $(lowerClassString(T))s with IDs: $(sort(collect(missing_ids)))\n"" + end + end + + if !isempty(warning_msg_dbs) + warning_msg_dbs = ""The following folders exist but are missing their corresponding entries in the database:\n"" * warning_msg_dbs + @error warning_msg_dbs + end + + #! check that all abstract trials have extant constituent trials + msg = """" + for T in (Monad, Sampling, Trial) + all_recorded_constituent_ids = Set{Int}() + for id in consensus_ids[T] + push!(all_recorded_constituent_ids, constituentIDs(T, id)...) + end + all_extant_constituent_ids = consensus_ids[constituentType(T)] + missing_ids = setdiff(all_recorded_constituent_ids, all_extant_constituent_ids) + if isempty(missing_ids) + continue + end + msg *= ""- $(lowerClassString(T))s reference non-existent $(lowerClassString(constituentType(T))) IDs: $(sort(collect(missing_ids)))\n"" + end + + if !isempty(msg) + msg = ""The following constituents are expected but not found:\n"" * msg + @error msg + end + + #! check simulation status of all simulations; warn on < 4 (4=Completed, 5=Failed), info on 5 + query = constructSelectQuery(""simulations""; selection=""simulation_id, status_code_id"") + df = queryToDataFrame(query) + status_codes = recognizedStatusCodes() + + #! check none of the concerning status codes are present (i.e., anything other than Completed or Failed) + codes_with_issues = String[] + for status_code in status_codes + if status_code ∈ (""Completed"", ""Failed"") + continue + end + status_code_id = statusCodeID(status_code) + concerning_ids = df[df.status_code_id .== status_code_id, :simulation_id] + if !isempty(concerning_ids) + @warn ""Found $(length(concerning_ids)) simulations in the database with status code '$(status_code)' (ID: $(status_code_id)): $(sort(collect(concerning_ids)))."" + push!(codes_with_issues, status_code) + end + end + + #! log info for all Failed simulations + failed_status_code_id = statusCodeID(""Failed"") + failed_ids = df[df.status_code_id .== failed_status_code_id, :simulation_id] + if !isempty(failed_ids) + @info ""Found $(length(failed_ids)) simulations in the database with status code 'Failed' (ID: $(failed_status_code_id)): $(sort(collect(failed_ids)))."" + push!(codes_with_issues, ""Failed"") + end + + #! suggest deletion of simulations with issues + if !isempty(codes_with_issues) + arg_string = length(codes_with_issues) == 1 ? ""\""$(codes_with_issues[1])\"""" : ""[$(join([""\""$c\"""" for c in codes_with_issues], "", ""))]"" + @info """""" + If these simulations are no longer needed, you can use `deleteSimulations(simulation_ids)` to remove them from the database. + You can also use `deleteSimulationsByStatus($arg_string; user_check=false)` to remove all simulations with these status codes. + """""" + end +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/pruner.jl",".jl","3165","90","using Glob, Parameters + +export PruneOptions + +"""""" + PruneOptions + +Automatically prune some of the generated output files from a simulation. + +# Fields +- `prune_svg::Bool=false`: Prune SVG files +- `prune_txt::Bool=false`: Prune TXT files +- `prune_mat::Bool=false`: Prune MAT files +- `prune_initial::Bool=false`: If any of the above are true, also prune the initial files for that type +- `prune_final::Bool=false`: If any of the above are true, also prune the final files for that type + +# Examples +```jldoctest +julia> PruneOptions(prune_svg=true, prune_txt=true, prune_mat=true) +PruneOptions + prune_mat: Bool true + prune_svg: Bool true + prune_txt: Bool true + prune_xml: Bool false + prune_initial: Bool false + prune_final: Bool false +``` +"""""" +@with_kw struct PruneOptions + prune_mat::Bool = false + prune_svg::Bool = false + prune_txt::Bool = false + prune_xml::Bool = false + + prune_initial::Bool = false + prune_final::Bool = false +end + +"""""" + pruneSimulationOutput(simulation_id::Integer, prune_options::PruneOptions=PruneOptions()) + +Prune the output files from a simulation. + +# Arguments +- `simulation_id::Integer`: The ID of the PhysiCell simulation. A [`Simulation`](@ref) object can also be passed in. +- `prune_options::PruneOptions=PruneOptions()`: The options for pruning the output files. See [`PruneOptions`](@ref) for more information. +``` +"""""" +function pruneSimulationOutput(simulation_id::Integer, prune_options::PruneOptions=PruneOptions()) + path_to_output_folder = pathToOutputFolder(simulation_id) + if prune_options.prune_svg + glob(""snapshot*.svg"", path_to_output_folder) .|> x->rm(x, force=true) + if prune_options.prune_initial + glob(""initial*.svg"", path_to_output_folder) .|> x->rm(x, force=true) + end + if prune_options.prune_final + glob(""final*.svg"", path_to_output_folder) .|> x->rm(x, force=true) + end + end + if prune_options.prune_txt + glob(""output*.txt"", path_to_output_folder) .|> x->rm(x, force=true) + if prune_options.prune_initial + glob(""initial*.txt"", path_to_output_folder) .|> x->rm(x, force=true) + end + if prune_options.prune_final + glob(""final*.txt"", path_to_output_folder) .|> x->rm(x, force=true) + end + end + if prune_options.prune_mat + glob(""output*.mat"", path_to_output_folder) .|> x->rm(x, force=true) + if prune_options.prune_initial + glob(""initial*.mat"", path_to_output_folder) .|> x->rm(x, force=true) + end + if prune_options.prune_final + glob(""final*.mat"", path_to_output_folder) .|> x->rm(x, force=true) + end + end + if prune_options.prune_xml + glob(""output*.xml"", path_to_output_folder) .|> x->rm(x, force=true) + if prune_options.prune_initial + glob(""initial*.xml"", path_to_output_folder) .|> x->rm(x, force=true) + end + if prune_options.prune_final + glob(""final*.xml"", path_to_output_folder) .|> x->rm(x, force=true) + end + end +end + +pruneSimulationOutput(simulation::Simulation, args...; kwargs...) = pruneSimulationOutput(simulation.id, args...; kwargs...) +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/hpc.jl",".jl","2017","68","@compat public setJobOptions + +"""""" + shellCommandExists(cmd::Union{String,Cmd}) + +Check if a shell command exists in the current environment. +"""""" +function shellCommandExists(cmd::Union{String,Cmd}) + cmd_ = Sys.iswindows() ? `where $cmd` : `which $cmd` + p = quietRun(ignorestatus(cmd_)) + return p.exitcode == 0 +end + +"""""" + isRunningOnHPC() + +Return `true` if the current environment is an HPC environment, `false` otherwise. + +Currently, this function checks if the `sbatch` command is available, indicating a SLURM environment. +"""""" +isRunningOnHPC() = shellCommandExists(`sbatch`) + +"""""" + useHPC([use::Bool=true]) + +Set the global variable `run_on_hpc` to `use`. + +# Examples +``` +useHPC() # Set to true so `sbatch` is used for running simulations +useHPC(true) # set to true so `sbatch` is used for running simulations +useHPC(false) # Set to false so simulations are run locally +``` +"""""" +function useHPC(use::Bool=true) + pcmm_globals.run_on_hpc = use +end + +"""""" + defaultJobOptions() + +Return a dictionary with default options for a job script for use with SLURM. See [`setJobOptions`](@ref) for setting these options and others. + +Current defaults are: +- `job-name`: `simulation_id -> \""S\$(simulation_id)\""` (use the simulation ID for the job name) +- `mem`: `""1G""` (1 GB of memory) +"""""" +function defaultJobOptions() + return Dict( + ""job-name"" => simulation_id -> ""S$(simulation_id)"", + ""mem"" => ""1G"" + ) +end + +"""""" + setJobOptions(options::Dict) + +Set the default job options for use with SLURM. + +Add every key-value pair in `options` to the global `sbatch_options` dictionary, i.e., add and/or overwrite the current sbatch options. +A flag is then added to the sbatch command for each key-value pair in `options`: `--key=value`. +When running simulations, any values in this dictionary that are `Function`'s will be assumed to be functions of the simulation id. +"""""" +function setJobOptions(options::Dict) + for (key, value) in options + pcmm_globals.sbatch_options[key] = value + end +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/compilation.jl",".jl","16468","406","#! This file will likely end up being part of PhysiCellModelManager.jl + +using LightXML + +"""""" + loadCustomCode(S::AbstractSampling[; force_recompile::Bool=false]) + +Load and compile custom code for a simulation, monad, or sampling. + +Determines if recompilation is necessary based on the previously used macros. +If compilation is required, copy the PhysiCell directory to a temporary directory to avoid conflicts. +Then, compile the project, recording the output and error in the `custom_codes` folder used. +Move the compiled executable into the `custom_codes` folder and the temporary PhysiCell folder deleted. +"""""" +function loadCustomCode(S::AbstractSampling; force_recompile::Bool=false) + cflags, recompile, clean = compilerFlags(S) + recompile = writePhysiCellCommitHash(S) || recompile #! no matter what, write the PhysiCell version; if it is different, make sure to set recompile to true + + recompile |= force_recompile #! if force_recompile is true, then recompile no matter what + + if !recompile + return true + end + + rand_suffix = randstring(10) #! just to ensure that no two nodes try to compile at the same place at the same time + temp_physicell_dir = joinpath(trialFolder(S), ""temp_physicell_$(rand_suffix)"") + #! copy the entire PhysiCell directory to a temporary directory to avoid conflicts with concurrent compilation + cp(physicellDir(), temp_physicell_dir; force=true) + + temp_custom_modules_dir = joinpath(temp_physicell_dir, ""custom_modules"") + if isdir(temp_custom_modules_dir) + rm(temp_custom_modules_dir; force=true, recursive=true) + end + path_to_input_custom_codes = locationPath(:custom_code, S) + cp(joinpath(path_to_input_custom_codes, ""custom_modules""), temp_custom_modules_dir; force=true) + + cp(joinpath(path_to_input_custom_codes, ""main.cpp""), joinpath(temp_physicell_dir, ""main.cpp""), force=true) + cp(joinpath(path_to_input_custom_codes, ""Makefile""), joinpath(temp_physicell_dir, ""Makefile""), force=true) + + if clean + cd(()->quietRun(`make clean`), temp_physicell_dir) + end + + executable_name = baseToExecutable(""project_ccid_$(S.inputs[:custom_code].id)"") + cmd = Cmd(`make -j 8 CC=$(pcmm_globals.physicell_compiler) PROGRAM_NAME=$(executable_name) CFLAGS=$(cflags)`; env=ENV, dir=temp_physicell_dir) #! compile the custom code in the PhysiCell directory and return to the original directory + + println(""Compiling custom code for $(S.inputs[:custom_code].folder). See $(joinpath(path_to_input_custom_codes, ""compilation.log"")) for more information."") + + try + run(pipeline(cmd; stdout=joinpath(path_to_input_custom_codes, ""compilation.log""), stderr=joinpath(path_to_input_custom_codes, ""compilation.err""))) + catch e + println("""""" + Compilation failed. + Error: $e + Check $(joinpath(path_to_input_custom_codes, ""compilation.err"")) for more information. + Here is the compilation.log: + $(read(joinpath(path_to_input_custom_codes, ""compilation.log""), String)) + Here is the compilation.err: + $(read(joinpath(path_to_input_custom_codes, ""compilation.err""), String)) + """""" + ) + rm(temp_physicell_dir; force=true, recursive=true) + return false + end + + #! check if the error file is empty, if it is, delete it + if filesize(joinpath(path_to_input_custom_codes, ""compilation.err"")) == 0 + rm(joinpath(path_to_input_custom_codes, ""compilation.err""); force=true) + else + println(""Compilation exited without error, but check $(joinpath(path_to_input_custom_codes, ""compilation.err"")) for warnings."") + end + + mv(joinpath(temp_physicell_dir, executable_name), joinpath(path_to_input_custom_codes, baseToExecutable(""project"")), force=true) + + rm(temp_physicell_dir; force=true, recursive=true) + return true +end + +"""""" + compilerFlags(S::AbstractSampling) + +Generate the compiler flags for the given sampling object `S`. + +Generate the necessary compiler flags based on the system and the macros defined in the sampling object `S`. +If the required macros differ from a previous compilation (as stored in macros.txt), then recompile. + +# Returns +- `cflags::String`: The compiler flags as a string. +- `recompile::Bool`: A boolean indicating whether recompilation is needed. +- `clean::Bool`: A boolean indicating whether cleaning is needed. +"""""" +function compilerFlags(S::AbstractSampling) + recompile = false #! only recompile if need is found + clean = false #! only clean if need is found + cflags = ""-march=$(pcmm_globals.march_flag) -O3 -fomit-frame-pointer -fopenmp -m64 -std=c++11"" + if Sys.isapple() + if strip(read(`uname -s`, String)) == ""Darwin"" + cc_path = strip(read(`which $(pcmm_globals.physicell_compiler)`, String)) + var = strip(read(`file $cc_path`, String)) + add_mfpmath = split(var)[end] != ""arm64"" + end + else + add_mfpmath = true + end + if add_mfpmath + cflags *= "" -mfpmath=both"" + end + + macros_updated = addMacrosIfNeeded(S) + updated_macros = readMacrosFile(S) #! this will get all macros already in the macros file + + if macros_updated + recompile = true + clean = true + end + + for macro_flag in updated_macros + cflags *= "" -D $(macro_flag)"" + end + + if ""ADDON_ROADRUNNER"" in updated_macros + librr_dir = joinpath(physicellDir(), ""addons"", ""libRoadrunner"", ""roadrunner"") + cflags *= "" -I $(joinpath(librr_dir, ""include"", ""rr"", ""C""))"" + cflags *= "" -L $(joinpath(librr_dir, ""lib""))"" + cflags *= "" -l roadrunner_c_api"" + + prepareLibRoadRunner() + end + + recompile = recompile || !executableExists(S.inputs[:custom_code].folder) #! last chance to recompile: do so if the executable does not exist + + return cflags, recompile, clean +end + +"""""" + writePhysiCellCommitHash(S::AbstractSampling) + +Write the commit hash of the PhysiCell repository to a file associated with the custom code folder of the sampling object `S`. + +If the commit hash has changed since the last write, if the repository is in a dirty state, or if PhysiCell is downloaded (not cloned), recompile the custom code. +"""""" +function writePhysiCellCommitHash(S::AbstractSampling) + path_to_commit_hash = joinpath(locationPath(:custom_code, S), ""physicell_commit_hash.txt"") + physicell_commit_hash = physiCellCommitHash() + current_commit_hash = """" + if isfile(path_to_commit_hash) + current_commit_hash = readchomp(path_to_commit_hash) + end + recompile = true + if current_commit_hash != physicell_commit_hash + open(path_to_commit_hash, ""w"") do f + println(f, physicell_commit_hash) + end + elseif endswith(physicell_commit_hash, ""-dirty"") + println(""PhysiCell repo is dirty. Recompiling to be safe..."") + elseif endswith(physicell_commit_hash, ""-download"") + println(""PhysiCell repo is downloaded. Recompiling to be safe..."") + else + recompile = false + end + return recompile +end + +"""""" + executableExists(custom_code_folder::String) + +Check if the executable for the custom code folder exists. +"""""" +executableExists(custom_code_folder::String) = isfile(joinpath(locationPath(:custom_code, custom_code_folder), baseToExecutable(""project""))) + +"""""" + addMacrosIfNeeded(S::AbstractSampling) + +Check if the macros needed for the sampling object `S` are already present in the macros file. +"""""" +function addMacrosIfNeeded(S::AbstractSampling) + #! else get the macros neeeded + macros_updated = false + + #! julia's |= operator seems to evaluate the RHS even if the LHS is already true, but I don't trust that will always be the case + macros_updated = macros_updated || addPhysiECMIfNeeded(S) + macros_updated = macros_updated || addRoadRunnerIfNeeded(S) + + #! check others... + + return macros_updated +end + +"""""" + addMacro(S::AbstractSampling, macro_name::String) + +Add a macro to the macros file for the sampling object `S`. +"""""" +function addMacro(S::AbstractSampling, macro_name::String) + path_to_macros = joinpath(locationPath(:custom_code, S), ""macros.txt"") + open(path_to_macros, ""a"") do f + println(f, macro_name) + end +end + +"""""" + addPhysiECMIfNeeded(S::AbstractSampling) + +Check if the PhysiECM macro needs to be added for the sampling object `S`. + +The macro will need to be added if it is not present AND either 1) the `inputs` includes `ic_ecm` or 2) the configuration file has `ecm_setup` enabled. +"""""" +function addPhysiECMIfNeeded(S::AbstractSampling) + if ""ADDON_PHYSIECM"" in readMacrosFile(S) + #! if the custom codes folder for the sampling already has the macro, then we don't need to do anything + return false + end + if S.inputs[:ic_ecm].id != -1 + #! if this sampling is providing an ic file for ecm, then we need to add the macro + addMacro(S, ""ADDON_PHYSIECM"") + return true + end + #! check if ecm_setup element has enabled=""true"" in config files + prepareVariedInputFolder(:config, S) + if isPhysiECMInConfig(S) + #! if the base config file says that the ecm is enabled, then we need to add the macro + addMacro(M, ""ADDON_PHYSIECM"") + return true + end + return false +end + +"""""" + isPhysiECMInConfig(S::AbstractSampling) + +Check if any of the simulations in `S` have a configuration file with `ecm_setup` enabled. +"""""" +function isPhysiECMInConfig(M::AbstractMonad) + path_to_xml = joinpath(locationPath(:config, M), locationVariationsFolder(:config), ""config_variation_$(M.variation_id[:config]).xml"") + xml_doc = parse_file(path_to_xml) + xml_path = [""microenvironment_setup"", ""ecm_setup""] + ecm_setup_element = retrieveElement(xml_doc, xml_path; required=false) + physi_ecm_in_config = !isnothing(ecm_setup_element) && attribute(ecm_setup_element, ""enabled"") == ""true"" #! note: attribute returns nothing if the attribute does not exist + free(xml_doc) + return physi_ecm_in_config +end + +function isPhysiECMInConfig(sampling::Sampling) + #! otherwise, no previous sampling saying to use the macro, no ic file for ecm, and the base config file does not have ecm enabled, + #! now just check that the variation is not enabling the ecm + for monad in Monad.(constituentIDs(sampling)) + if isPhysiECMInConfig(monad) + return true + end + end + return false +end + +"""""" + addRoadRunnerIfNeeded(S::AbstractSampling) + +Check if the RoadRunner macro needs to be added for the sampling object `S`. + +The macro will need to be added if it is not present AND either 1) the `inputs` defines an `intracellular` file with `roadrunner` intracellulars or 2) the configuration file has `roadrunner` intracellulars defined. +"""""" +function addRoadRunnerIfNeeded(S::AbstractSampling) + if ""ADDON_ROADRUNNER"" in readMacrosFile(S) + #! if the custom codes folder for the sampling already has the macro, then we don't need to do anything + return false + end + + macros_updated = false + prepareVariedInputFolder(:config, S) + macros_updated = isRoadRunnerInInputs(S) || isRoadRunnerInConfig(S) + if macros_updated + addMacro(S, ""ADDON_ROADRUNNER"") + end + return macros_updated +end + +"""""" + isRoadRunnerInInputs(S::AbstractSampling) + +Check if the `inputs` for the sampling object `S` defines an `intracellular` file with `roadrunner` intracellulars. +"""""" +function isRoadRunnerInInputs(S::AbstractSampling) + if S.inputs[:intracellular].id == -1 + return false + end + path_to_xml = joinpath(locationPath(:intracellular, S), S.inputs[:intracellular].basename) + xml_doc = parse_file(path_to_xml) + is_nothing = retrieveElement(xml_doc, [""intracellulars""; ""intracellular:type:roadrunner""]) |> isnothing + free(xml_doc) + return !is_nothing +end + +"""""" + isRoadRunnerInConfig(S::AbstractSampling) + +Check if any of the simulations in `S` have a configuration file with `roadrunner` intracellulars defined. +"""""" +function isRoadRunnerInConfig(S::AbstractSampling) + path_to_xml = joinpath(locationPath(:config, S), ""PhysiCell_settings.xml"") + xml_doc = parse_file(path_to_xml) + cell_definitions_element = retrieveElement(xml_doc, [""cell_definitions""]) + ret_val = false + for child in child_elements(cell_definitions_element) + phenotype_element = find_element(child, ""phenotype"") + intracellular_element = find_element(phenotype_element, ""intracellular"") + if isnothing(intracellular_element) + continue + end + if attribute(intracellular_element, ""type"") == ""roadrunner"" + ret_val = true + break + end + end + free(xml_doc) + return ret_val +end + +"""""" + prepareLibRoadRunner() + +Prepare the libRoadRunner library for use with PhysiCell. +"""""" +function prepareLibRoadRunner() + #! this is how PhysiCell handles downloading libRoadrunner + println(""preparing libRoadrunner library for use with PhysiCell..."") + librr_base_dir = joinpath(physicellDir(), ""addons"", ""libRoadrunner"") + librr_dir = joinpath(librr_base_dir, ""roadrunner"") + librr_file = joinpath(librr_dir, ""include"", ""rr"", ""C"", ""rrc_api.h"") + if !isfile(librr_file) + python = Sys.iswindows() ? ""python"" : ""python3"" + cmd = `$(python) $(joinpath(""."", ""beta"", ""setup_libroadrunner.py""))` + cd(() -> quietRun(cmd), physicellDir()) + @assert isfile(librr_file) ""libRoadrunner was not downloaded properly."" + + #! remove the downloaded binary (I would think the script would handle this, but it does not) + files = readdir(librr_base_dir; join=true, sort=false) + for path_to_file in files + if isfile(path_to_file) && + ( + endswith(path_to_file, ""roadrunner_macos_arm64.tar.gz"") || + endswith(path_to_file, ""roadrunner-osx-10.9-cp36m.tar.gz"") || + endswith(path_to_file, ""roadrunner-win64-vs14-cp35m.zip"") || + endswith(path_to_file, ""cpplibroadrunner-1.3.0-linux_x86_64.tar.gz"") + ) + #! remove the downloaded binary + rm(path_to_file; force=true) + end + end + end + + if Sys.iswindows() + return + end + + env_var = Sys.isapple() ? ""DYLD_LIBRARY_PATH"" : ""LD_LIBRARY_PATH"" + env_file = (haskey(ENV, ""SHELL"") && contains(ENV[""SHELL""], ""zsh"")) ? "".zshenv"" : "".bashrc"" + path_to_env_file = ""~/$(env_file)"" + librr_lib_path = joinpath(librr_dir, ""lib"") + + if !haskey(ENV, env_var) || !libRoadRunnerOnPath(ENV[env_var], librr_lib_path) + println("""""" + Warning: Shell environment variable $(env_var) either not found or does not include the path to an installation of libRoadrunner. + For now, we will add this path to your ENV variable in this Julia session. + Run this command in your terminal to add it to your $(env_file) as a relative path and this should be resolved permanently: + + echo ""export $env_var=$env_var:./addons/libRoadrunner/roadrunner/lib"" > $(path_to_env_file) + + """""") + ENV[env_var] = "":./addons/libRoadrunner/roadrunner/lib"" #! at this point, we know this is not a Windows system + end +end + +"""""" + libRoadRunnerOnPath(env_var::String, librr_lib_path::String; working_dir::String=physicellDir()) + +Check if the libRoadRunner library path is included in the environment variable. + +The `librr_lib_path` must be an absolute path, and the function will resolve relative paths based on the `working_dir`. +Returns `true` if the path is found, otherwise `false`. +"""""" +function libRoadRunnerOnPath(env_var::String, librr_lib_path::String; working_dir::String=physicellDir()) + normalized_librr_lib_path = normpath(librr_lib_path) + @assert isabspath(normalized_librr_lib_path) ""The path to the libRoadRunner library must be absolute. Provided: $(normalized_librr_lib_path)"" + os_variable_separator = Sys.iswindows() ? "";"" : "":"" + paths = split(env_var, os_variable_separator) + for path in paths + resolved_path = isabspath(path) ? path : joinpath(working_dir, path) + if normpath(resolved_path) == normalized_librr_lib_path + return true + end + end + + return false +end + +"""""" + readMacrosFile(S::AbstractSampling) + +Read the macros file for the sampling object `S` into a vector of strings, one macro per entry. +"""""" +function readMacrosFile(S::AbstractSampling) + path_to_macros = joinpath(locationPath(:custom_code, S), ""macros.txt"") + if !isfile(path_to_macros) + return [] + end + return readlines(path_to_macros) +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/classes.jl",".jl","33393","768","using Dates + +export Simulation, Monad, Sampling, Trial, InputFolders + +"""""" + AbstractTrial + +Abstract type for the [`Simulation`](@ref), [`Monad`](@ref), [`Sampling`](@ref), and [`Trial`](@ref) types. + +There are no restrictions on inputs or variations for this type. +"""""" +abstract type AbstractTrial end + +"""""" + AbstractSampling <: AbstractTrial + +Abstract type for the [`Simulation`](@ref), [`Monad`](@ref), and [`Sampling`](@ref) types. + +All the inputs must be the same for all associated simulations. Variations can differ. +"""""" +abstract type AbstractSampling <: AbstractTrial end + +"""""" + trialType(T::AbstractTrial) + +Returns the type of the trial, which can be `Simulation`, `Monad`, `Sampling`, or `Trial`. +"""""" +trialType(T::AbstractTrial) = typeof(T) + +"""""" + trialID(T::AbstractTrial) + +Returns the ID of the [`AbstractTrial`](@ref) object, which is the ID of the simulation, monad, sampling, or trial. +"""""" +trialID(T::AbstractTrial) = T.id + +"""""" + AbstractMonad <: AbstractSampling + +Abstract type for the [`Simulation`](@ref) and [`Monad`](@ref) types. + +All the inputs and variations must be the same for all associated simulations. +"""""" +abstract type AbstractMonad <: AbstractSampling end + +Base.length(T::AbstractTrial) = simulationIDs(T) |> length + +########################################## +############ InputFolders ############ +########################################## + +"""""" + InputFolder + +Hold the information for a single input folder. + +Users should use the `InputFolders` to create and access individual `InputFolder` objects. + +# Fields +- `location::Symbol`: The location of the input folder, e.g. `:config`, `:custom_code`, etc. Options are defined in `data/inputs/inputs.toml`. +- `id::Int`: The ID of the input folder in the database. +- `folder::String`: The name of the input folder. It will be in `data/inputs/`. +- `basename::Union{String,Missing}`: The basename of the input file. This can be used to determine if the input file is varied. +- `required::Bool`: Whether the input folder is required. This is defined in `data/inputs/inputs.toml`. +- `varied::Bool`: Whether the input folder is varied. This is determined by the presence of a varied basename in the input folder. +- `path_from_inputs::String`: The path from the `data/inputs` directory to the input folder. This is defined in `data/inputs/inputs.toml`. +"""""" +struct InputFolder + location::Symbol + id::Int + folder::String + basename::Union{String,Missing} + required::Bool + varied::Bool + path_from_inputs::String + + function InputFolder(location::Symbol, id::Int, folder::String) + location_dict = inputsDict()[location] + required = location_dict[""required""] + if isempty(folder) + if required + error(""Folder for $location must be provided"") + end + return new(location, id, folder, missing, required, false, """") + end + path_from_inputs = joinpath(location_dict[""path_from_inputs""], folder) + basename = location_dict[""basename""] + varied = folderIsVaried(location, folder) + if basename isa Vector + possible_files = [joinpath(locationPath(location, folder), x) for x in basename] + basename_index = possible_files .|> isfile |> findfirst + if isnothing(basename_index) + error(""Neither of $possible_files exist"") + end + basename = basename[basename_index] + end + return new(location, id, folder, basename, required, varied, path_from_inputs) + end + + function InputFolder(location::Symbol, id::Int) + folder = inputFolderName(location, id) + return InputFolder(location, id, folder) + end + + function InputFolder(location::Symbol, folder::String) + id = inputFolderID(location, folder) + return InputFolder(location, id, folder) + end +end + +function Base.show(io::IO, input_folder::InputFolder) + println(io, ""InputFolder:"") + println(io, "" Location: $(input_folder.location)"") + println(io, "" ID: $(input_folder.id)"") + println(io, "" Folder: $(input_folder.folder)"") + println(io, "" Basename: $(input_folder.basename)"") + println(io, "" Required: $(input_folder.required)"") + println(io, "" Varied: $(input_folder.varied)"") +end + +"""""" + InputFolders + +Consolidate the folder information for a simulation/monad/sampling. + +Pass the folder names within the `inputs/` directory to create an `InputFolders` object. +The `path_from_inputs` is defined in the `data/inputs/inputs.toml` file for each. +It is possible to acces the [`InputFolder`](@ref) values using index notation, e.g. `input_folders[:config]`. + +Several constructors exist: +1. All folders passed as keyword arguments. Omitted folders are assumed to be \""\"", i.e. those inputs are unused. +```julia +InputFolders(; config=""default"", custom_codes=""default"", rulesets_collection=""default"") +``` +2. Pass in the required inputs as arguments and the optional inputs as keyword arguments. The required folders must be passed in alphabetical order. +Refer to the names defined in `data/inputs/inputs.toml` to see this order. Omitted optional folders are assumed to be \""\"", i.e. those inputs are unused. +```julia +config_folder = ""default"" +custom_code_folder = ""default"" +ic_cell_folder = ""cells_in_disc"" +InputFolders(config_folder, custom_code_folder; ic_cell=ic_cell_folder) +``` + +# Fields +- `input_folders::NamedTuple`: The input locations defined in `data/inputs/inputs.toml` define the keys. The values are [`InputFolder`](@ref)s. +"""""" +struct InputFolders + input_folders::NamedTuple + + function InputFolders(location_pairs::Vector{<:Pair{Symbol,<:Union{String,Int}}}) + locs_already_here = first.(location_pairs) + invalid_locations = setdiff(locs_already_here, projectLocations().all) + @assert isempty(invalid_locations) ""Invalid locations: $invalid_locations.\nPossible locations are: $(projectLocations()).all)"" + for loc in setdiff(projectLocations().all, locs_already_here) + push!(location_pairs, loc => """") + end + return new([loc => InputFolder(loc, val) for (loc, val) in location_pairs] |> NamedTuple) + end + + function InputFolders(; kwargs...) + return InputFolders([loc => val for (loc, val) in kwargs]) + end +end + +#! let the linter know that there will be a function like this after initialization +#! this is the function that takes in the required inputs as positional arguments and the optional inputs as keyword arguments +function InputFolders(args...; kwargs...) end + +function InputFolders(req_loc_folders::Vararg{String}; opt_loc_folders...) + assertInitialized() + req_locs = projectLocations().required + @assert length(req_loc_folders) == length(req_locs) ""Number of required location folders provided ($(length(req_loc_folders))) does not match number of required locations ($(length(req_locs))). Required locations are: $(req_locs)."" + + location_pairs = Vector{Pair{Symbol,Union{String,Int}}}() + for (loc, folder) in zip(req_locs, req_loc_folders) + push!(location_pairs, loc => folder) + end + for (loc, val) in pairs(opt_loc_folders) + push!(location_pairs, loc => val) + end + return InputFolders(location_pairs) +end + +Base.getindex(input_folders::InputFolders, loc::Symbol)::InputFolder = input_folders.input_folders[loc] + +function Base.show(io::IO, input_folders::InputFolders) + println(io, ""InputFolders:"") + printInputFolders(io, input_folders) +end + +"""""" + printInputFolders(io::IO, input_folders::InputFolders, n_indent::Int=1) + +Prints the folder information for each input folder in the InputFolders object. +"""""" +function printInputFolders(io::IO, input_folders::InputFolders, n_indent::Int=1) + if_nt = input_folders.input_folders #! InputFolders NamedTuple + used_locs = [loc for loc in keys(if_nt) if !isempty(if_nt[loc].folder)] + max_width = maximum(length(string(loc)) for loc in used_locs) + for loc in used_locs + input_folder = if_nt[loc] + println(io, "" ""^n_indent, ""$(rpad(""$loc:"", max_width + 1)) $(input_folder.folder)"") + end +end + +########################################## +############ Variation IDs ############ +########################################## + +"""""" + VariationID + +The variation IDs for any of the possibly varying inputs. + +For each input type that can be varied, a record of the current variation ID for that input type. +By convention, a values of `-1` indicates that the input is not being used (hence this is disallowed for a `required` input type). +A value of `0` indicates that the base file is being used, unvaried. +Hence, if the input type is sometimes varied (such as `ic_cell` with a `cells.csv` file), this value must be `0` in such conditions. +"""""" +struct VariationID + ids::NamedTuple + + function VariationID(inputs::InputFolders) + return new((loc => inputs[loc].id == -1 ? -1 : 0 for loc in projectLocations().varied) |> NamedTuple) + end + + function VariationID(x::Vector{Pair{Symbol,Int}}) + #! this is slightly dangerous since no checks are made that the locations are valid. + #! but it is called often enough internally that it is worth it to have this constructor without checks + #! if this is added to the public API, then checks should be added + return new(x |> NamedTuple) + end +end + +Base.getindex(variation_id::VariationID, loc::Symbol)::Int = variation_id.ids[loc] + +function Base.show(io::IO, variation_id::VariationID) + println(io, ""VariationID:"") + printVariationID(io, variation_id) +end + +"""""" + printVariationID(io::IO, variation_id::VariationID, n_indent::Int=1) + +Prints the variation ID information for each varied input in the VariationID object. +"""""" +function printVariationID(io::IO, variation_id::VariationID, n_indent::Int=1) + used_locs = [loc for loc in keys(variation_id.ids) if variation_id.ids[loc] != -1] + max_width = maximum(length(string(loc)) for loc in used_locs) + for loc in used_locs + id = variation_id.ids[loc] + println(io, "" ""^n_indent, ""$(rpad(""$loc:"", max_width + 1)) $id"") + end +end + +########################################## +############# Simulation ############# +########################################## + +"""""" + Simulation + +A simulation that represents a single run of the model. + +To create a new simulation, best practice is to use `createTrial` and supply it with the `InputFolders` and any number of single-valued DiscreteVariations: +```julia +inputs = InputFolders(config_folder, custom_code_folder) +simulation = createTrial(inputs) # uses the default config file as-is + +ev = DiscreteVariation(configPath(""max_time""), 1440) +simulation = createTrial(inputs, ev) # uses the config file with the specified variation +``` + +If there is a previously created simulation that you wish to access, you can use its ID to create a `Simulation` object: +```julia +simulation = Simulation(simulation_id) +``` + +Finally, a new `Simulation` object can be created from an existing `Monad` object. +This will not use a simulation already in the database, but will create a new one with the same inputs and variations: +```julia +simulation = Simulation(monad) +``` + +# Fields +- `id::Int`: integer uniquely identifying this simulation. Matches with the folder in `data/outputs/simulations/` +- `inputs::InputFolders`: contains the folder info for this simulation. +- `variation_id::VariationID`: contains the variation IDs for this simulation. +"""""" +struct Simulation <: AbstractMonad + id::Int #! integer uniquely identifying this simulation + inputs::InputFolders + variation_id::VariationID + + function Simulation(id::Int, inputs::InputFolders, variation_id::VariationID) + @assert id > 0 ""Simulation id must be positive. Got $id."" + for location in projectLocations().varied + if inputs[location].required + @assert variation_id[location] >= 0 ""$(location) variation id must be non-negative. Got $(variation_id[location])."" + elseif inputs[location].id == -1 + @assert variation_id[location] == -1 ""$(location) variation id must be -1 because there is no associated folder indicating $(location) is not in use. Got $(variation_id[location])."" + #! now we know this location is not required and it is in use + elseif !inputs[location].varied + #! this particular folder is not varying it, so make sure its variation id is 0, i.e. the base file in this folder + @assert variation_id[location] == 0 ""$(inputs[location].folder) in $(location) is not varying but the variation id is not 0. Got $(variation_id[location])."" + #! now we know that the folder is being varied, so just make sure the variation id is >=0 + else + @assert variation_id[location] >= 0 ""$(location) variation id must be non-negative as the folder $(inputs[location].folder) is varying. Got $(variation_id[location])."" + end + end + return new(id, inputs, variation_id) + end +end + +function Simulation(inputs::InputFolders, variation_id::VariationID=VariationID(inputs)) + simulation_id = DBInterface.execute(centralDB(), + """""" + INSERT INTO simulations (\ + physicell_version_id,\ + $(join(locationIDNames(), "","")),\ + $(join(locationVariationIDNames(), "","")),\ + status_code_id\ + ) \ + VALUES(\ + $(currentPhysiCellVersionID()),\ + $(join([inputs[loc].id for loc in projectLocations().all], "","")),\ + $(join([variation_id[loc] for loc in projectLocations().varied],"","")),\ + $(statusCodeID(""Not Started"")) + ) + RETURNING simulation_id; + """""" + ) |> DataFrame |> x -> x.simulation_id[1] + return Simulation(simulation_id, inputs, variation_id) +end + +function Simulation(simulation_id::Int) + assertInitialized() + df = constructSelectQuery(""simulations"", ""WHERE simulation_id=$(simulation_id);"") |> queryToDataFrame + if isempty(df) + error(""Simulation $(simulation_id) not in the database."") + end + inputs = [loc => df[1, locationIDName(loc)] for loc in projectLocations().all] |> InputFolders + variation_id = [loc => df[1, locationVariationIDName(loc)] for loc in projectLocations().varied] |> VariationID + + return Simulation(simulation_id, inputs, variation_id) +end + +Base.length(simulation::Simulation) = 1 + +function Base.show(io::IO, simulation::Simulation) + println(io, ""Simulation (ID=$(simulation.id)):"") + println(io, "" Inputs:"") + printInputFolders(io, simulation.inputs, 2) + println(io, "" Variation ID:"") + printVariationID(io, simulation.variation_id, 2) +end + +########################################## +############### Monad ################ +########################################## + +"""""" + Monad + +A group of simulations that are identical up to randomness. + +To create a new monad, best practice is to use `createTrial` and supply it with the `InputFolders` and any number of single-valued DiscreteVariations. +Set `n_replicates=0` to avoid adding new simulations to the database. This is useful for creating references for later use. +Otherwise, set `n_replicates` > 1 to create the simulations to go with this monad. +If `n_replicates` = 1, it will return a `Simulation` object. +```julia +inputs = InputFolders(config_folder, custom_code_folder) +monad = createTrial(inputs; n_replicates=0) # uses the default config file as-is + +ev = DiscreteVariation(configPath(""max_time""), 1440) +monad = createTrial(inputs, ev; n_replicates=10) # uses the config file with the specified variation + +monad = createTrial(inputs, ev; n_replicates=10, use_previous=false) # changes the default behavior and creates 10 new simulations for this monad +``` + +If there is a previously created monad that you wish to access, you can use its ID to create a `Monad` object: +```julia +monad = Monad(monad_id) +monad = Monad(monad_id; n_replicates=5) # ensures at least 5 simulations in the monad (using previous sims) +``` + +# Fields +- `id::Int`: integer uniquely identifying this monad. Matches with the folder in `data/outputs/monads/` +- `inputs::InputFolders`: contains the folder info for this monad. +- `variation_id::VariationID`: contains the variation IDs for this monad. +"""""" +struct Monad <: AbstractMonad + #! a monad is a group of simulation replicates, i.e. identical up to randomness + id::Int #! integer uniquely identifying this monad + inputs::InputFolders #! contains the folder names for the simulations in this monad + variation_id::VariationID #! contains the variation IDs for the simulations in this monad + + function Monad(inputs::InputFolders, variation_id::VariationID=VariationID(inputs); n_replicates::Integer=0, use_previous::Bool=true) + feature_str = """""" + (\ + physicell_version_id,\ + $(join(locationIDNames(), "","")),\ + $(join(locationVariationIDNames(), "",""))\ + ) \ + """""" + value_str = """""" + (\ + $(currentPhysiCellVersionID()),\ + $(join([inputs[loc].id for loc in projectLocations().all], "","")),\ + $(join([variation_id[loc] for loc in projectLocations().varied],"",""))\ + ) \ + """""" + monad_id = DBInterface.execute(centralDB(), + """""" + INSERT OR IGNORE INTO monads $feature_str VALUES $value_str RETURNING monad_id; + """""" + ) |> DataFrame |> x -> x.monad_id + if isempty(monad_id) + monad_id = constructSelectQuery( + ""monads"", + """""" + WHERE $feature_str=$value_str + """"""; + selection=""monad_id"" + ) |> queryToDataFrame |> x -> x.monad_id[1] #! get the monad_id + else + monad_id = monad_id[1] #! get the monad_id + end + return Monad(monad_id, inputs, variation_id, n_replicates, use_previous) + end + + function Monad(id::Int, inputs::InputFolders, variation_id::VariationID, n_replicates::Int, use_previous::Bool) + @assert id > 0 ""Monad id must be positive. Got $id."" + @assert n_replicates >= 0 ""Monad n_replicates must be non-negative. Got $n_replicates."" + + previous_simulation_ids = constituentIDs(Monad, id) + new_simulation_ids = Int[] + num_sims_to_add = n_replicates - (use_previous ? length(previous_simulation_ids) : 0) + if num_sims_to_add > 0 + for _ = 1:num_sims_to_add + simulation = Simulation(inputs, variation_id) #! create a new simulation + push!(new_simulation_ids, simulation.id) + end + recordConstituentIDs(Monad, id, [previous_simulation_ids; new_simulation_ids]) #! record the simulation ids in a .csv file + end + + return new(id, inputs, variation_id) + end + +end + +function Monad(monad_id::Integer; n_replicates::Integer=0, use_previous::Bool=true) + assertInitialized() + df = constructSelectQuery(""monads"", ""WHERE monad_id=$(monad_id);"") |> queryToDataFrame + if isempty(df) + error(""Monad $(monad_id) not in the database."") + end + inputs = [loc => df[1, locationIDName(loc)] for loc in projectLocations().all] |> InputFolders + variation_id = [loc => df[1, locationVariationIDName(loc)] for loc in projectLocations().varied] |> VariationID + return Monad(monad_id, inputs, variation_id, n_replicates, use_previous) +end + +function Monad(simulation::Simulation; n_replicates::Integer=0, use_previous::Bool=true) + monad = Monad(simulation.inputs, simulation.variation_id; n_replicates=n_replicates, use_previous=use_previous) + addSimulationID(monad, simulation.id) + return monad +end + +function Monad(monad::Monad; n_replicates::Integer=0, use_previous::Bool=true) + return Monad(monad.id, monad.inputs, monad.variation_id, n_replicates, use_previous) +end + +"""""" + addSimulationID(monad::Monad, simulation_id::Int) + +Adds a simulation ID to the monad's list of simulation IDs. +"""""" +function addSimulationID(monad::Monad, simulation_id::Int) + simulation_ids = simulationIDs(monad) + if simulation_id in simulation_ids + return + end + push!(simulation_ids, simulation_id) + recordConstituentIDs(monad, simulation_ids) + return +end + +Simulation(monad::Monad) = Simulation(monad.inputs, monad.variation_id) + +function Base.show(io::IO, monad::Monad) + println(io, ""Monad (ID=$(monad.id)):"") + println(io, "" Inputs:"") + printInputFolders(io, monad.inputs, 2) + println(io, "" Variation ID:"") + printVariationID(io, monad.variation_id, 2) + printSimulationIDs(io, monad) +end + +function printSimulationIDs(io::IO, T::AbstractTrial, n_indent::Int=1) + simulation_ids = simulationIDs(T) |> compressIDs + simulation_ids = join(simulation_ids[1], "", "") + simulation_ids = replace(simulation_ids, "":"" => ""-"") + println(io, "" ""^n_indent, ""Simulations: $simulation_ids"") +end + +########################################## +############## Sampling ############## +########################################## + +"""""" + Sampling + +A group of monads that have the same input folders, but differ in parameter values. + +To create a new sampling, best practice is to use `createTrial` and supply it with the `InputFolders` and any number of DiscreteVariations. +At least one should have multiple values to create a sampling. +```julia +inputs = InputFolders(config_folder, custom_code_folder) +ev = DiscreteVariation(configPath(""max_time""), [1440, 2880])) +sampling = createTrial(inputs, ev; n_replicates=3, use_previous=true) +``` + +If there is a previously created sampling that you wish to access, you can use its ID to create a `Sampling` object: +```julia +sampling = Sampling(sampling_id) +sampling = Sampling(sampling_id; n_replicates=5) # ensures at least 5 simulations in each monad (using previous sims) +sampling = Sampling(sampling_id; n_replicates=5, use_previous=false) # creates 5 new simulations in each monad +``` + +If you have a vector of `Monad` objects that you wish to group into a sampling, you can use the constructor: +```julia +sampling = Sampling(monads; n_replicates=0, use_previous=true) +``` +which will create a new `Sampling` object with the provided monads, ensuring each has at least `n_replicates` simulations per monad, using previous simulations if requested and available. + +# Fields +- `id::Int`: integer uniquely identifying this sampling. Matches with the folder in `data/outputs/samplings/` +- `inputs::InputFolders`: contains the folder info for this sampling. +- `monads::Vector{Monad}`: array of monads belonging to this sampling. +"""""" +struct Sampling <: AbstractSampling + #! sampling is a group of monads with parameters varied + id::Int #! integer uniquely identifying this sampling + inputs::InputFolders #! contains the folder names for this sampling + monads::Vector{Monad} #! contains the monads belonging to this sampling + + function Sampling(monads::AbstractVector{Monad}, inputs::InputFolders) + id = -1 + sampling_ids = constructSelectQuery( + ""samplings"", + """""" + WHERE (\ + physicell_version_id,\ + $(join(locationIDNames(), "",""))\ + )=\ + (\ + $(currentPhysiCellVersionID()),\ + $(join([inputs[loc].id for loc in projectLocations().all], "",""))\ + );\ + """"""; + selection=""sampling_id"" + ) |> queryToDataFrame |> x -> x.sampling_id + + monad_ids = [monad.id for monad in monads] + if !isempty(sampling_ids) #! if there are previous samplings with the same parameters + for sampling_id in sampling_ids #! check if the monad_ids are the same with any previous monad_ids + monad_ids_in_sampling = constituentIDs(Sampling, sampling_id) #! get the monad_ids belonging to this sampling + if symdiff(monad_ids_in_sampling, monad_ids) |> isempty #! if the monad_ids are the same + id = sampling_id #! use the existing sampling_id + break + end + end + end + + if id==-1 #! if no previous sampling was found matching these parameters + id = DBInterface.execute(centralDB(), + """""" + INSERT INTO samplings \ + (\ + physicell_version_id,\ + $(join(locationIDNames(), "",""))\ + ) \ + VALUES(\ + $(currentPhysiCellVersionID()),\ + $(join([inputs[loc].id for loc in projectLocations().all], "",""))\ + ) RETURNING sampling_id; + """""" + ) |> DataFrame |> x -> x.sampling_id[1] #! get the sampling_id + recordConstituentIDs(Sampling, id, monad_ids) #! record the monad ids in a .csv file + end + return Sampling(id, inputs, monads) + end + + function Sampling(id::Int, inputs::InputFolders, monads::Vector{Monad}) + @assert id > 0 ""Sampling id must be positive. Got $id."" + @assert !isempty(monads) ""At least one monad must be provided"" + for monad in monads + @assert monad.inputs == inputs ""All monads must have the same inputs. You can instead make these into a Trial. Got $(monad.inputs) and $(inputs)."" + end + @assert Set(constituentIDs(Sampling, id)) == Set([monad.id for monad in monads]) ""Monad ids do not match those in the database for Sampling $(id):\n$(Set(constituentIDs(Sampling, id)))\nvs\n$(Set([monad.id for monad in monads]))"" + return new(id, inputs, monads) + end +end + +function Sampling(inputs::InputFolders, variation_ids::AbstractArray{VariationID}; n_replicates::Integer=0, use_previous::Bool=true) + monads = [Monad(inputs, variation_id; n_replicates=n_replicates, use_previous=use_previous) for variation_id in variation_ids] + return Sampling(monads, inputs) +end + +function Sampling(inputs::InputFolders, + location_variation_ids::Dict{Symbol,<:Union{Integer,AbstractArray{<:Integer}}}; + n_replicates::Integer=0, + use_previous::Bool=true) + #! allow for passing in a single config_variation_id and/or rulesets_collection_variation_id + #! later, can support passing in (for example) a 3x6 config_variation_ids and a 3x1 rulesets_collection_variation_ids and expanding the rulesets_collection_variation_ids to 3x6, but that can get tricky fast + if all(x->x isa Integer, values(location_variation_ids)) + for (loc, loc_var_ids) in pairs(location_variation_ids) + location_variation_ids[loc] = [loc_var_ids] + end + else + ns = [length(x) for x in values(location_variation_ids) if !(x isa Integer)] + @assert all(x->x==ns[1], ns) ""location variation ids must have the same length if they are not integers. Got $(ns)."" + for (loc, loc_var_ids) in pairs(location_variation_ids) + if loc_var_ids isa Integer + location_variation_ids[loc] = fill(loc_var_ids, ns[1]) + end + end + end + n = location_variation_ids |> values |> first |> length + for loc in setdiff(projectLocations().varied, keys(location_variation_ids)) + location_variation_ids[loc] = fill(inputs[loc].id==-1 ? -1 : 0, n) + end + variation_ids = [([loc => loc_var_ids[i] for (loc, loc_var_ids) in pairs(location_variation_ids)] |> VariationID) for i in 1:n] + return Sampling(inputs, variation_ids; n_replicates=n_replicates, use_previous=use_previous) +end + +function Sampling(Ms::AbstractArray{<:AbstractMonad}; n_replicates::Integer=0, use_previous::Bool=true) + @assert !isempty(Ms) ""At least one monad must be provided"" + inputs = Ms[1].inputs + for M in Ms + @assert M.inputs == inputs ""All Ms must have the same inputs. You can instead make these into a Trial. Got $(M.inputs) and $(inputs)."" + end + monads = [Monad(M; n_replicates=n_replicates, use_previous=use_previous) for M in Ms] #! this step ensures that the monads all have the min number of replicates ready + return Sampling(monads, inputs) +end + +Sampling(M::AbstractMonad; kwargs...) = Sampling([M]; kwargs...) + +function Sampling(sampling_id::Int; n_replicates::Integer=0, use_previous::Bool=true) + assertInitialized() + df = constructSelectQuery(""samplings"", ""WHERE sampling_id=$(sampling_id);"") |> queryToDataFrame + if isempty(df) + error(""Sampling $(sampling_id) not in the database."") + end + monad_ids = constituentIDs(Sampling, sampling_id) + monads = Monad.(monad_ids; n_replicates=n_replicates, use_previous=use_previous) + inputs = monads[1].inputs #! constituentIDs() should be returning monads already associated with a Sampling and thus having the same inputs + return Sampling(sampling_id, inputs, monads) +end + +Sampling(sampling::Sampling; kwargs...) = Sampling(sampling.id; kwargs...) + +function Base.show(io::IO, sampling::Sampling) + println(io, ""Sampling (ID=$(sampling.id)):"") + printMonadIDs(io, sampling) + println(io, "" Inputs:"") + printInputFolders(io, sampling.inputs, 2) +end + +function printMonadIDs(io::IO, sampling::Sampling, n_indent::Int=1) + monad_ids = constituentIDs(sampling) |> compressIDs + monad_ids = join(monad_ids[1], "", "") + monad_ids = replace(monad_ids, "":"" => ""-"") + println(io, "" ""^n_indent, ""Monads: $(monad_ids)"") +end + +########################################## +############### Trial ################ +########################################## + +"""""" + Trial + +A group of samplings that can have different input folders. + +To create a new trial, best practice currently is to create a vector of `Sampling` objects and passing them to `Trial`. +```julia +inputs_1 = InputFolders(config_folder_1, custom_code_folder_1) +inputs_2 = InputFolders(config_folder_2, custom_code_folder_2) +ev = DiscreteVariation(configPath(""max_time""), [1440, 2880])) +sampling_1 = createTrial(inputs_1, ev; n_replicates=3, use_previous=true) +sampling_2 = createTrial(inputs_2, ev; n_replicates=3, use_previous=true) +trial = Trial([sampling_1, sampling_2]) +``` + +If there is a previous trial that you wish to access, you can use its ID to create a `Trial` object: +```julia +trial = Trial(trial_id) +trial = Trial(trial_id; n_replicates=5) # ensures at least 5 simulations in each monad (using previous sims) +trial = Trial(trial_id; n_replicates=5, use_previous=false) # creates 5 new simulations in each monad +``` + +# Fields +- `id::Int`: integer uniquely identifying this trial. Matches with the folder in `data/outputs/trials/` +- `inputs::Vector{InputFolders}`: contains the folder info for each sampling in this trial. +- `variation_ids::Vector{Vector{VariationID}}`: contains the variation IDs for each monad in each sampling in this trial. +"""""" +struct Trial <: AbstractTrial + #! trial is a group of samplings with different ICs, custom codes, rulesets, and/or intracellulars + id::Int #! integer uniquely identifying this trial + samplings::Vector{Sampling} #! contains the samplings belonging to this trial + + function Trial(id::Integer, samplings::Vector{Sampling}) + @assert id > 0 ""Trial id must be positive. Got $id."" + @assert Set(constituentIDs(Trial, id)) == Set([sampling.id for sampling in samplings]) ""Samplings do not match the samplings in the database."" + return new(id, samplings) + end +end + +function Trial(Ss::AbstractArray{<:AbstractSampling}; n_replicates::Integer=0, use_previous::Bool=true) + samplings = Sampling.(Ss; n_replicates=n_replicates, use_previous=use_previous) + id = trialID(samplings) + return Trial(id, samplings) +end + +function Trial(trial_id::Int; n_replicates::Integer=0, use_previous::Bool=true) + assertInitialized() + df = constructSelectQuery(""trials"", ""WHERE trial_id=$(trial_id);"") |> queryToDataFrame + @assert !isempty(df) ""Trial $(trial_id) not in the database."" + samplings = Sampling.(constituentIDs(Trial, trial_id); n_replicates=n_replicates, use_previous=use_previous) + @assert !isempty(samplings) ""No samplings found for trial_id=$trial_id. This trial has not been created."" + return Trial(trial_id, samplings) +end + +"""""" + trialID(samplings::Vector{Sampling}) + +Get the trial ID for a vector of samplings or create a new trial if one does not exist. +"""""" +function trialID(samplings::Vector{Sampling}) + sampling_ids = [sampling.id for sampling in samplings] + id = -1 + trial_ids = constructSelectQuery(""trials""; selection=""trial_id"") |> queryToDataFrame |> x -> x.trial_id + if !isempty(trial_ids) #! if there are previous trials + for trial_id in trial_ids #! check if the sampling_ids are the same with any previous sampling_ids + sampling_ids_in_db = constituentIDs(Trial, trial_id) #! get the sampling_ids belonging to this trial + if symdiff(sampling_ids_in_db, sampling_ids) |> isempty #! if the sampling_ids are the same + id = trial_id #! use the existing trial_id + break + end + end + end + + if id==-1 #! if no previous trial was found matching these parameters + id = DBInterface.execute(centralDB(), ""INSERT INTO trials (datetime) VALUES($(Dates.format(now(),""yymmddHHMM""))) RETURNING trial_id;"") |> DataFrame |> x -> x.trial_id[1] #! get the trial_id + recordConstituentIDs(Trial, id, sampling_ids) #! record the sampling ids in a .csv file + end + + return id +end + +function Base.show(io::IO, trial::Trial) + println(io, ""Trial (ID=$(trial.id)):"") + for sampling in trial.samplings + println(io, "" Sampling (ID=$(sampling.id)):"") + printMonadIDs(io, sampling, 2) + end +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/creation.jl",".jl","20172","453","using Downloads, JSON3, CSV, PhysiCellCellCreator + +export createProject + +"""""" + createProject(project_dir::String="".""; clone_physicell::Bool=true, template_as_default::Bool=true, terse::Bool=false) + +Create a new PhysiCellModelManager.jl project structure. + +Creates a new project directory at `project_dir` with the following structure: +``` +project_dir +├── data +├── PhysiCell # The latest release from https://github.com/drbergman/PhysiCell +└── scripts +``` +`data` is populated with the standard structure. `PhysiCell` is a copy of PhysiCell. `scripts` contains a generated `GenerateData.jl` file. + +# Arguments +- `project_dir::String="".""`: The directory in which to create the project. Relative paths are resolved from the current working directory where Julia was launched. +- `clone_physicell::Bool=true`: Whether to clone the PhysiCell repository. If `false`, the latest release will be downloaded. Recommended to set to `true` so PhysiCellModelManager.jl will be able to track changes to the PhysiCell repository. +- `template_as_default::Bool=true`: Whether to set up the project with the template files as the default. If `false`, the project will be set up with an empty structure. +- `terse::Bool=false`: Whether to generate a terse `GenerateData.jl` file. If `true`, the file will be generated without comments and explanations. + +# Note +The names of the `data` and `PhysiCell` directories are fixed and cannot be changed. Their relative locations should not be changed without updating the `GenerateData.jl` file and other scripts accordingly. +The name of the `scripts` folder and the `GenerateData.jl` are just by convention and can be changed. +"""""" +function createProject(project_dir::String="".""; clone_physicell::Bool=true, template_as_default::Bool=true, terse::Bool=false) + global pcmm_globals + pcmm_globals.initialized = false #! in case the user is creating a project in an already-initialized directory + mkpath(project_dir) + physicell_dir = setUpPhysiCell(project_dir, clone_physicell) + data_dir = joinpath(project_dir, ""data"") + + setUpInputs(data_dir, physicell_dir, template_as_default) + setUpComponents(data_dir, physicell_dir) + setUpScripts(project_dir, physicell_dir, data_dir, template_as_default, terse) + createDefaultGitIgnore(project_dir) + initializeModelManager(physicell_dir, data_dir) + project_dir_norm = normpath(abspath(project_dir)) + msg = """""" + + PhysiCellModelManager.jl project created at $(project_dir_norm)! A couple notes: + 1. We got you started this time (see output above). Next time, just do: + + shell> cd $project_dir_norm + julia> using PhysiCellModelManager + + 2. Check out the sample script in `$(joinpath(project_dir_norm, ""scripts""))` to get started with running simulations. + 3. A .gitignore file has been created in the data directory. + 4. If you want to track changes to this project, you can initialize a git repository: + + cd $project_dir_norm + git init + git submodule add https://github.com/drbergman/PhysiCell + + 5. Take a look at the best practices for PCMM: https://drbergman-lab.github.io/PhysiCellModelManager.jl/stable/man/best_practices/ + + Happy modeling! + """""" + println(msg) +end + +"""""" + latestReleaseTag(repo_url::String) + +Get the latest release tag from a GitHub repository. +"""""" +function latestReleaseTag(repo_url::String) + api_url = replace(repo_url, ""github.com"" => ""api.github.com/repos"") * ""/releases/latest"" + #! include this header for CI testing to not exceed request limit (I think?): macos for some reason raised a `RequestError: HTTP/2 403`; users should not need to set this ENV variable + headers = requestHeaders() + response = Downloads.download(api_url; headers=headers) + release_info = JSON3.read(response, Dict{String, Any}) + return release_info[""tag_name""] +end + +"""""" + requestHeaders() + +Get the request headers for GitHub API requests. +This allows the GitHub actions to use a token if provided in the `PCMM_PUBLIC_REPO_AUTH` environment variable to avoid rate limiting. +"""""" +function requestHeaders() + if haskey(ENV, ""PCMM_PUBLIC_REPO_AUTH"") + println(""Using GitHub token from PCMM_PUBLIC_REPO_AUTH environment variable for API requests."") + return Dict(""Authorization"" => ""token $(ENV[""PCMM_PUBLIC_REPO_AUTH""])"") + end + return Pair{String,String}[] +end + +"""""" + setUpPhysiCell(project_dir::String, clone_physicell::Bool) + +Set up the PhysiCell directory in the project directory. + +If the directory already exists, it will not be created again. +If `clone_physicell` is `true`, the latest release of the PhysiCell repository will be cloned. +"""""" +function setUpPhysiCell(project_dir::String, clone_physicell::Bool) + physicell_dir = joinpath(project_dir, ""PhysiCell"") + if isdir(physicell_dir) + println(""PhysiCell directory already exists ($(physicell_dir)). Hopefully it's the PhysiCellModelManager.jl-compatible version!"") + return physicell_dir + end + is_git_repo = isdir(joinpath(project_dir, "".git"")) + if clone_physicell + latest_tag = latestReleaseTag(""https://github.com/drbergman/PhysiCell"") + if is_git_repo + println(""Cloning PhysiCell repository as submodule"") + quietRun(`git submodule add https://github.com/drbergman/PhysiCell $(physicell_dir)`) + quietRun(`git submodule update --init --recursive --depth 1`) + quietRun(`git -C $physicell_dir checkout $latest_tag`) + else + println(""Cloning PhysiCell repository"") + quietRun(`git clone --branch $latest_tag --depth 1 https://github.com/drbergman/PhysiCell $(physicell_dir)`) + end + else + #! download drbergman/PhysiCell main branch + println(""Downloading PhysiCell repository"") + url = ""https://api.github.com/repos/drbergman/PhysiCell/releases/latest"" + headers = requestHeaders() + response = Downloads.download(url; headers=headers) + release_data = JSON3.read(response) + zipball_url = release_data[""zipball_url""] + zip_path = joinpath(project_dir, ""PhysiCell.zip"") + Downloads.download(zipball_url, zip_path) + extract_path = joinpath(project_dir, ""PhysiCell_extract"") + quietRun(`unzip $zip_path -d $extract_path`) + rm(zip_path) + @assert (readdir(extract_path) |> length) == 1 + path_to_extracted_physicell = readdir(extract_path; join=true)[1] + mv(path_to_extracted_physicell, physicell_dir) + rm(extract_path; recursive=false) + end + return physicell_dir +end + +"""""" + setUpComponents(data_dir::String, physicell_dir::String) + +Set up the components directory in the data directory and populate it with the `\""Toy_Metabolic_Model.xml\""` file. +"""""" +function setUpComponents(data_dir::String, physicell_dir::String) + components_dir = joinpath(data_dir, ""components"") + mkpath(components_dir) + + #! make sbml roadrunner components and populate with an example sbml for a roadrunner model + roadrunner_components_dir = joinpath(components_dir, ""roadrunner"") + mkpath(roadrunner_components_dir) + cp(joinpath(physicell_dir, ""sample_projects_intracellular"", ""ode"", ""ode_energy"", ""config"", ""Toy_Metabolic_Model.xml""), joinpath(roadrunner_components_dir, ""Toy_Metabolic_Model.xml""); force=true) +end + +"""""" + setUpInputs(data_dir::String, physicell_dir::String, template_as_default::Bool) + +Set up the inputs directory in the data directory, if the data directory does not already exist. +"""""" +function setUpInputs(data_dir::String, physicell_dir::String, template_as_default::Bool) + if isdir(data_dir) + println(""Data directory already exists ($(data_dir)). Skipping setup of data directory."") + return + end + + inputs_dir = joinpath(data_dir, ""inputs"") + mkpath(inputs_dir) + createInputsTOMLTemplate(joinpath(inputs_dir, ""inputs.toml"")) + + mkpath(joinpath(inputs_dir, ""configs"")) + mkpath(joinpath(inputs_dir, ""custom_codes"")) + for ic in [""cells"", ""substrates"", ""ecms"", ""dcs""] + mkpath(joinpath(inputs_dir, ""ics"", ic)) + end + mkpath(joinpath(inputs_dir, ""rulesets_collections"")) + mkpath(joinpath(inputs_dir, ""intracellulars"")) + + if template_as_default + setUpTemplate(physicell_dir, inputs_dir) + end +end + +"""""" + setUpRequiredFolders(path_to_template::String, inputs_dir::String, folder::String) + +Set up the required folders in the inputs directory. +"""""" +function setUpRequiredFolders(path_to_template::String, inputs_dir::String, folder::String) + config_folder = joinpath(inputs_dir, ""configs"", folder) + mkpath(config_folder) + cp(joinpath(path_to_template, ""config"", ""PhysiCell_settings.xml""), joinpath(config_folder, ""PhysiCell_settings.xml"")) + + custom_codes_folder = joinpath(inputs_dir, ""custom_codes"", folder) + mkpath(custom_codes_folder) + cp(joinpath(path_to_template, ""custom_modules""), joinpath(custom_codes_folder, ""custom_modules"")) + cp(joinpath(path_to_template, ""main.cpp""), joinpath(custom_codes_folder, ""main.cpp"")) + cp(joinpath(path_to_template, ""Makefile""), joinpath(custom_codes_folder, ""Makefile"")) +end + +"""""" + icFilename(table_name::String) + +Get the filename for the given IC type for setting up the IC folder. +"""""" +function icFilename(table_name::String) + if table_name == ""cells"" + return ""cells.csv"" + elseif table_name == ""substrates"" + return ""substrates.csv"" + elseif table_name == ""ecms"" + return ""ecm.csv"" + elseif table_name == ""dcs"" + return ""dcs.csv"" + else + throw(ArgumentError(""table_name must be 'cells', 'substrates', 'ecms', or `dcs`."")) + end +end + +"""""" + setUpICFolder(path_to_template::String, inputs_dir::String, ic_name::String, folder::String) + +Set up the IC folder in the inputs directory for the given IC type. +"""""" +function setUpICFolder(path_to_template::String, inputs_dir::String, ic_name::String, folder::String) + ic_folder = joinpath(inputs_dir, ""ics"", ic_name, folder) + mkpath(ic_folder) + filename = icFilename(ic_name) + cp(joinpath(path_to_template, ""config"", filename), joinpath(ic_folder, filename)) +end + +"""""" + setUpTemplate(physicell_dir::String, inputs_dir::String) + +Set up the template project in the inputs directory. +"""""" +function setUpTemplate(physicell_dir::String, inputs_dir::String) + path_to_template = joinpath(physicell_dir, ""sample_projects"", ""template"") + + setUpRequiredFolders(path_to_template, inputs_dir, ""0_template"") + + rulesets_collection_folder = joinpath(inputs_dir, ""rulesets_collections"", ""0_template"") + mkpath(rulesets_collection_folder) + open(joinpath(rulesets_collection_folder, ""base_rulesets.csv""), ""w"") do f + write(f, ""default,pressure,decreases,cycle entry,0.0,0.5,4,0"") #! actually add a rule for example's sake + end + + setUpICFolder(path_to_template, inputs_dir, ""cells"", ""0_template"") + setUpICFolder(path_to_template, inputs_dir, ""substrates"", ""0_template"") + + #! also set up a ic cell folder using the xml-based version + PhysiCellModelManager.createICCellXMLTemplate(joinpath(inputs_dir, ""ics"", ""cells"", ""1_xml"")) +end + +"""""" + setUpScripts(project_dir::String, physicell_dir::String, data_dir::String, template_as_default::Bool, terse::Bool) + +Set up the scripts directory in the project directory. +"""""" +function setUpScripts(project_dir::String, physicell_dir::String, data_dir::String, template_as_default::Bool, terse::Bool) + path_to_scripts = joinpath(project_dir, ""scripts"") + mkpath(path_to_scripts) + + path_to_generate_data = joinpath(path_to_scripts, ""GenerateData.jl"") + if isfile(path_to_generate_data) + println(""GenerateData.jl already exists ($(joinpath(path_to_scripts,""GenerateData.jl""))). Skipping creation of this starter file."") + return + end + path_to_configs = joinpath(data_dir, ""inputs"", ""configs"") + config_folder = template_as_default ? ""\""0_template\"" # this folder is located at $(path_to_configs)"" : ""\""default\"" # add this folder with config file to $(path_to_configs)"" + + path_to_rulesets_collections = joinpath(data_dir, ""inputs"", ""rulesets_collections"") + rulesets_collection_folder = template_as_default ? ""\""0_template\"" # this folder is located at $(path_to_rulesets_collections); a rule has been added for the sake of the example"" : ""\""\"" # optionally add this folder with base_rulesets.csv to $(path_to_rulesets_collections)"" + + path_to_custom_codes = joinpath(data_dir, ""inputs"", ""custom_codes"") + custom_code_folder = template_as_default ? ""\""0_template\"" # this folder is located at $(path_to_custom_codes)"" : ""\""default\"" # add this folder with main.cpp, Makefile, and custom_modules to $(path_to_custom_codes)"" + + path_to_ics = joinpath(data_dir, ""inputs"", ""ics"") + path_to_ic_cells = joinpath(path_to_ics, ""cells"") + ic_cell_folder = template_as_default ? ""\""0_template\"" # this folder is located at $(path_to_ic_cells)"" : ""\""\"" # optionally add this folder with cells.csv to $(path_to_ic_cells)"" + + tersify(s::String) = (terse ? """" : s) + generate_data_lines = """""" + using PhysiCellModelManager + + # if you launch the script from the project directory, you don't need this next line explicitly calling initializeModelManager + # initializeModelManager(\""$(normpath(abspath(project_dir)))\"") + + ############ set up ############ + + config_folder = $(config_folder) + custom_code_folder = $(custom_code_folder) + rulesets_collection_folder = $(rulesets_collection_folder) + intracellular_folder = \""\"" # optionally add this folder with intracellular.xml to $(joinpath(path_to_ics, ""intracellulars"")) + + ic_cell_folder = $(ic_cell_folder) + ic_substrate_folder = \""\"" # optionally add this folder with substrates.csv to $(joinpath(path_to_ics, ""substrates"")) + ic_ecm_folder = \""\"" # optionally add this folder with ecms.csv to $(joinpath(path_to_ics, ""ecms"")) + ic_dc_folder = \""\"" # optionally add this folder with dcs.csv to $(joinpath(path_to_ics, ""dcs"")) + + $(tersify("""""" + # package them all together into a single object + """"""))\ + inputs = InputFolders(config_folder, custom_code_folder; + rulesets_collection=rulesets_collection_folder, + intracellular=intracellular_folder, + ic_cell=ic_cell_folder, + ic_substrate=ic_substrate_folder, + ic_ecm=ic_ecm_folder, + ic_dc=ic_dc_folder) + + ############ make the simulations short ############ + + $(tersify("""""" + # We will set the default simulations to have a lower max time. + # This will serve as a reference for the following simulations. + """"""))\ + xml_path = [\""overall\""; \""max_time\""] + value = 60.0 + dv_max_time = DiscreteVariation(xml_path, value) + reference = createTrial(inputs, dv_max_time; n_replicates=0) # since we don't want to run this, set the n_replicates to 0 + + ############ set up variables to control running simulations ############ + + $(tersify("""""" + # you can force the recompilation, but it is usually only necesary if you change core code + # if you change custom code, it is recommended you make a new custom codes folder in $(path_to_custom_codes)... + # ...especially if the database already has simulations run with that custom code + """"""))\ + force_recompile = false + + $(tersify("""""" + # PhysiCellModelManager.jl records which simulations all use the same parameter vector... + # ...to reuse them (unless the user opts out) + """"""))\ + use_previous = true # if true, will attempt to reuse simulations with the same parameters; otherwise run new simulations + + $(tersify("""""" + # a monad refers to a single collection of identical simulations... + # except for randomness (could be do to the initial seed or stochasticity introduced by omp threading) + # n_replicates is the number of replicates to run for each parameter vector... + # ...PhysiCellModelManager.jl records which simulations all use the same parameter vector... + # ...and will attempt to reuse these (unless the user opts out)... + # ...so this parameter is the _min_ because there may already be many sims with the same parameters + """"""))\ + n_replicates = 1 + + ############ set up parameter variations ############ + + $(tersify("""""" + # assume you have the template project with \""default\"" as a cell type... + # ...let's vary their cycle durations and apoptosis rates + + # get the xml path to duration of phase 0 of the default cell type + # this is a list of strings in which each string is either... + # \t1) the name of a tag in the xml file OR + # \t2) the name of a tag along with the value of one attribute (name:attribute_name:attribute_value) + """"""))\ + xml_path = PhysiCellModelManager.cyclePath(\""default\"", \""phase_durations\"", \""duration:index:0\"") + vals = [200.0, 300.0, 400.0] # choose 3 discrete values to vary the duration of phase 0 + dv_phase_0_duration = DiscreteVariation(xml_path, vals) + + $(tersify("""""" + # now do the same, but for the apoptosis rate + """"""))\ + xml_path = PhysiCellModelManager.apoptosisPath(\""default\"", \""death_rate\"") + vals = [4.31667e-05, 5.31667e-05, 6.31667e-05] # choose 3 discrete values to vary the apoptosis rate + dv_apoptosis_rate = DiscreteVariation(xml_path, vals) + + $(tersify("""""" + # now combine them into a list: + """"""))\ + discrete_variations = [dv_phase_0_duration, dv_apoptosis_rate] + + ############ run the sampling ############ + + $(tersify("""""" + # now create the sampling (varied parameter values) with these parameters + # we will give it a reference to the monad with the short max time + """"""))\ + sampling = createTrial(reference, discrete_variations; n_replicates=n_replicates, use_previous=use_previous) + + $(tersify("""""" + # at this point, we have only added the sampling to the database... + # ...along with the monads and simulations that make it up + # before running, we will set the number of parallel simulations to run. + # note: this will only be used when running locally, i.e., not on an HPC + # by default, PhysiCellModelManager.jl will run the simulations serially, i.e., 1 in \""parallel\"". + # change this by calling: + """"""))\ + setNumberOfParallelSims(4) # for example, to run 4 simulations in parallel + + $(tersify("""""" + # you can change this default behavior on your machine by setting an environment variable... + # called PCMM_NUM_PARALLEL_SIMS + # this is read during `initializeModelManager`... + # meaning subsequent calls to `setNumberOfParallelSims` will overwrite the value + # A simple way to use this when running the script is to run in your shell: + # `PCMM_NUM_PARALLEL_SIMS=4 julia $(path_to_generate_data)` + """"""))\ + + $(tersify("""""" + # now run the sampling + """"""))\ + out = run(sampling; force_recompile=force_recompile) + + $(tersify("""""" + # If you are running on an SLURM-based HPC, PhysiCellModelManager.jl will detect this and calls to `sbatch`... + # ...to parallelize the simulations, batching out each simulation to its own job. + """"""))\ + """""" + + open(path_to_generate_data, ""w"") do f + write(f, generate_data_lines) + end +end + +"""""" + createDefaultGitIgnore(project_dir::String) + +Create a default `.gitignore` file for the data directory. +The following are ignored: +- all databases +- all variations folders (folders containing modified versions of the base files) +- compile-time-generated files +- all outputs +"""""" +function createDefaultGitIgnore(project_dir::String) + data_gitignore_path = joinpath(project_dir, ""data"", "".gitignore"") + mode = isfile(data_gitignore_path) ? ""a"" : ""w"" # append if file exists, otherwise write + open(data_gitignore_path, mode) do f + write( + f, + """""" + # PCMM + + ## databases + *.db + + ## variations folders + $(locationVariationsFolder(""*""))/ + + ## custom codes + compilation* + macros.txt + physicell_commit_hash.txt + project* + + ## outputs + /outputs/ + """""" + ) + end +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/configuration.jl",".jl","60503","1347","using PhysiCellXMLRules, PhysiCellCellCreator, PhysiCellECMCreator, LightXML + +export configPath, rulePath, icCellsPath, icECMPath + +@compat public domainPath, timePath, fullSavePath, svgSavePath, substratePath, + cellDefinitionPath, phenotypePath, cyclePath, + apoptosisPath, necrosisPath, volumePath, mechanicsPath, + motilityPath, secretionPath, cellInteractionsPath, + phagocytosisPath, attackRatePath, fusionPath, + transformationPath, integrityPath, customDataPath, + initialParameterDistributionPath, userParameterPath + +################## XML Functions ################## + +"""""" + getChildByAttribute(parent_element::XMLElement, path_element_split::Vector{<:AbstractString}) + +Get the child element of `parent_element` that matches the given tag and attribute. +"""""" +function getChildByAttribute(parent_element::XMLElement, path_element_split::Vector{<:AbstractString}) + path_element_name, attribute_name, attribute_value = path_element_split + candidate_elements = get_elements_by_tagname(parent_element, path_element_name) + for ce in candidate_elements + if attribute(ce, attribute_name) == attribute_value + return ce + end + end + return nothing +end + +"""""" + getChildByChildContent(current_element::XMLElement, path_element::AbstractString) + +Get the child element of `current_element` that matches the given tag and child content. +"""""" +function getChildByChildContent(current_element::XMLElement, path_element::AbstractString) + tag, child_scheme = split(path_element, ""::"") + tokens = split(child_scheme, "":"") + @assert length(tokens) == 2 ""Invalid child scheme for $(path_element). Expected format: :::"" + child_tag, child_content = tokens + candidate_elements = get_elements_by_tagname(current_element, tag) + for ce in candidate_elements + child_element = find_element(ce, child_tag) + if !isnothing(child_element) && content(child_element) == child_content + return ce, true + end + end + return current_element, false +end + +"""""" + retrieveElement(xml_doc::XMLDocument, xml_path::Vector{<:AbstractString}; required::Bool=true) + +Retrieve the element in the XML document that matches the given path. + +If `required` is `true`, an error is thrown if the element is not found. +Otherwise, `nothing` is returned if the element is not found. +"""""" +function retrieveElement(xml_doc::XMLDocument, xml_path::Vector{<:AbstractString}; required::Bool=true) + current_element = root(xml_doc) + for path_element in xml_path + if contains(path_element, ""::"") + current_element, success = getChildByChildContent(current_element, path_element) + if !success + current_element = nothing + end + else + current_element = contains(path_element, "":"") ? + getChildByAttribute(current_element, split(path_element, "":""; limit=3)) : + find_element(current_element, path_element) + end + + if isnothing(current_element) + required ? retrieveElementError(xml_path, path_element) : return nothing + end + end + return current_element +end + +"""""" + retrieveElementError(xml_path::Vector{<:AbstractString}, path_element::String) + +Throw an error if the element defined by `xml_path` is not found in the XML document, including the path element that caused the error. +"""""" +function retrieveElementError(xml_path::Vector{<:AbstractString}, path_element::String) + error_msg = ""Element not found: $(join(xml_path, "" -> ""))"" + error_msg *= ""\n\tFailed at: $(path_element)"" + throw(ArgumentError(error_msg)) +end + +"""""" + getSimpleContent(xml_doc::XMLDocument, xml_path::Vector{<:AbstractString}; required::Bool=true) + +Get the content of the element in the XML document that matches the given path. See [`retrieveElement`](@ref). + +Validates that the element is terminal (has no child elements) and contains non-empty text content. +Throws AssertionError if either condition is not met. +"""""" +function getSimpleContent(xml_doc::XMLDocument, xml_path::Vector{<:AbstractString}; required::Bool=true) + e = retrieveElement(xml_doc, xml_path; required=required) + @assert elementIsTerminal(e) ""Element at path $(join(xml_path, "" -> "")) has child elements and cannot have simple content extracted."" + ret_val = content(e) + @assert !isempty(ret_val) ""Element at path $(join(xml_path, "" -> "")) has no text content."" + return ret_val +end + +"""""" + elementIsTerminal(e::XMLElement) + +Check if an XML element is terminal (i.e., has no child elements). +Returns `true` if the element has no children, `false` otherwise. +"""""" +elementIsTerminal(e::XMLElement) = isempty(child_elements(e)) + +"""""" + setSimpleContent(xml_doc::XMLDocument, xml_path::Vector{<:AbstractString}, new_value::Union{Int,Real,String}) + +Update the content of the element in the XML document that matches the given path with the new value. See [`retrieveElement`](@ref). + +Update the content of the element in the XML document that matches the given path with the new value. +Validates that the element is terminal (has no child elements) before setting content. Throws AssertionError if the element has child elements. +"""""" +function setSimpleContent(xml_doc::XMLDocument, xml_path::Vector{<:AbstractString}, new_value::Union{Int,Real,String}) + e = retrieveElement(xml_doc, xml_path; required=true) + @assert elementIsTerminal(e) ""Element at path $(join(xml_path, "" -> "")) is not a terminal element and has child elements. Cannot set content."" + set_content(e, string(new_value)) + return nothing +end + +"""""" + columnName(xml_path) + +Return the column name corresponding to the given XML path. + +Works on a vector of strings, an [`XMLPath`](@ref) object, or a [`ElementaryVariation`](@ref) object. +Inverse of [`columnNameToXMLPath`](@ref). +"""""" +columnName(xml_path::Vector{<:AbstractString}) = join(xml_path, ""/"") + +"""""" + columnNameToXMLPath(column_name::String) + +Return the XML path corresponding to the given column name. + +Inverse of [`columnName`](@ref). +"""""" +columnNameToXMLPath(column_name::String) = split(column_name, ""/"") + +"""""" + makeXMLPath(current_element::XMLElement, xml_path::AbstractVector{<:AbstractString}) + +Create (if it does not exist) and return the XML element relative to the given XML element. + +Similar functionality to the shell command `mkdir -p`, but for XML elements. + +# Arguments +- `current_element::XMLElement`: The current XML element to start from. +- `xml_path::AbstractVector{<:AbstractString}`: The path to the XML element to create or retrieve. Can be a string representing a child of the current element. +"""""" +function makeXMLPath(current_element::XMLElement, xml_path::AbstractVector{<:AbstractString}) + for path_element in xml_path + if contains(path_element, ""::"") + current_element, success = getChildByChildContent(current_element, path_element) + if !success + current_element = new_child(current_element, tag) + child_element = new_child(current_element, child_tag) + set_content(child_element, child_content) + end + elseif !contains(path_element, "":"") + child_element = find_element(current_element, path_element) + if isnothing(child_element) + current_element = new_child(current_element, path_element) + else + current_element = child_element + end + else + #! Deal with checking attributes + path_element_split = split(path_element, "":""; limit=3) + child_element = getChildByAttribute(current_element, path_element_split) + if isnothing(child_element) + path_element_name, attribute_name, attribute_value = path_element_split + child_element = new_child(current_element, path_element_name) + set_attribute(child_element, attribute_name, attribute_value) + end + current_element = child_element + end + end + return current_element +end + +"""""" + makeXMLPath(xml_doc::XMLDocument, xml_path::AbstractVector{<:AbstractString}) + +Create (if it does not exist) and return the XML element relative to the root of the given XML document. + +# Arguments +- `xml_doc::XMLDocument`: The XML document to start from. +- `xml_path::AbstractVector{<:AbstractString}`: The path to the XML element to create or retrieve. Can be a string representing a child of the root element. +"""""" +function makeXMLPath(xml_doc::XMLDocument, xml_path::AbstractVector{<:AbstractString}) + current_element = root(xml_doc) + return makeXMLPath(current_element, xml_path) +end + +makeXMLPath(x, xml_path::AbstractString) = makeXMLPath(x, [xml_path]) + +################## Configuration Functions ################## + +"""""" + createXMLFile(location::Symbol, M::AbstractMonad) + +Create XML file for the given location and variation_id in the given monad. + +The file is placed in `$(PhysiCellModelManager.locationVariationsFolder(""\$(location)""))` and can be accessed from there to run the simulation(s). +"""""" +function createXMLFile(location::Symbol, M::AbstractMonad) + path_to_folder = locationPath(location, M) + path_to_xml = joinpath(path_to_folder, locationVariationsFolder(location), ""$(location)_variation_$(M.variation_id[location]).xml"") + if isfile(path_to_xml) + return path_to_xml + end + mkpath(dirname(path_to_xml)) + + path_to_base_xml = prepareBaseFile(M.inputs[location]) + @assert endswith(path_to_base_xml, "".xml"") ""Base XML file for $(location) must end with .xml. Got $(path_to_base_xml)"" + @assert isfile(path_to_base_xml) ""Base XML file not found: $(path_to_base_xml)"" + + xml_doc = parse_file(path_to_base_xml) + if M.variation_id[location] != 0 #! only update if not using the base variation for the location + query = constructSelectQuery(locationVariationsTableName(location), ""WHERE $(locationVariationIDName(location))=$(M.variation_id[location])"") + variation_row = queryToDataFrame(query; db=locationVariationsDatabase(location, M), is_row=true) + for column_name in names(variation_row) + if column_name == locationVariationIDName(location) || column_name == ""par_key"" + continue + end + xml_path = columnNameToXMLPath(column_name) + setSimpleContent(xml_doc, xml_path, variation_row[1, column_name]) + end + end + save_file(xml_doc, path_to_xml) + free(xml_doc) + postVariationXMLProcessing(location, path_to_xml) + return path_to_xml +end + +"""""" + prepareBaseFile(input_folder::InputFolder) + +Return the path to the base XML file for the given input folder. +"""""" +function prepareBaseFile(input_folder::InputFolder) + if input_folder.location == :rulesets_collection + return prepareBaseRulesetsCollectionFile(input_folder) + end + return joinpath(locationPath(input_folder), input_folder.basename) +end + +"""""" + prepareBaseRulesetsCollectionFile(input_folder::InputFolder) + +Return the path to the base XML file for the given input folder. +"""""" +function prepareBaseRulesetsCollectionFile(input_folder::InputFolder) + path_to_rulesets_collection_folder = locationPath(:rulesets_collection, input_folder.folder) + path_to_base_xml = joinpath(path_to_rulesets_collection_folder, ""base_rulesets.xml"") + if !isfile(path_to_base_xml) + #! this could happen if the rules are not being varied (so no call to addRulesetsVariationsColumns) and then a sim runs without the base_rulesets.xml being created yet + writeXMLRules(path_to_base_xml, joinpath(path_to_rulesets_collection_folder, ""base_rulesets.csv"")) + end + return path_to_base_xml +end + +"""""" + postVariationXMLProcessing(location::Symbol, path_to_xml::String) + +Perform any post-processing needed after creating the XML file for the given location. +"""""" +function postVariationXMLProcessing(location::Symbol, path_to_xml::String) + if location == :intracellular + #! split back out the intracellular SBMLs to avoid PhysiCell doing it concurrently across multiple runs + disassembleIntracellular(path_to_xml) + end + return +end + +"""""" + prepareVariedInputFolder(location::Symbol, M::AbstractMonad) + +Create the XML file for the location in the monad. +"""""" +function prepareVariedInputFolder(location::Symbol, M::AbstractMonad) + if !M.inputs[location].varied #! this input is not being varied (either unused or static) + return + end + createXMLFile(location, M) +end + +"""""" + prepareVariedInputFolder(location::Symbol, sampling::Sampling) + +Create the XML file for each monad in the sampling for the given location. +"""""" +function prepareVariedInputFolder(location::Symbol, sampling::Sampling) + if !sampling.inputs[location].varied #! this input is not being varied (either unused or static) + return + end + for monad in Monad.(constituentIDs(sampling)) + prepareVariedInputFolder(location, monad) + end +end + +"""""" + pathToICCell(simulation::Simulation) + +Return the path to the IC cell file for the given simulation, creating it if it needs to be generated from an XML file. +"""""" +function pathToICCell(simulation::Simulation) + @assert simulation.inputs[:ic_cell].id != -1 ""No IC cell variation being used"" #! we should have already checked this before calling this function + path_to_ic_cell_folder = locationPath(:ic_cell, simulation) + if isfile(joinpath(path_to_ic_cell_folder, ""cells.csv"")) #! ic already given by cells.csv + return joinpath(path_to_ic_cell_folder, ""cells.csv"") + end + path_to_config_xml = joinpath(locationPath(:config, simulation), locationVariationsFolder(:config), ""config_variation_$(simulation.variation_id[:config]).xml"") + xml_doc = parse_file(path_to_config_xml) + domain_dict = Dict{String,Float64}() + for d in [""x"", ""y"", ""z""] + for side in [""min"", ""max""] + key = ""$(d)_$(side)"" + xml_path = [""domain""; key] + domain_dict[key] = getSimpleContent(xml_doc, xml_path) |> x -> parse(Float64, x) + end + end + free(xml_doc) + path_to_ic_cell_variations = joinpath(path_to_ic_cell_folder, locationVariationsFolder(:ic_cell)) + path_to_ic_cell_xml = joinpath(path_to_ic_cell_variations, ""ic_cell_variation_$(simulation.variation_id[:ic_cell]).xml"") + path_to_ic_cell_file = joinpath(path_to_ic_cell_variations, ""ic_cell_variation_$(simulation.variation_id[:ic_cell])_s$(simulation.id).csv"") + generateICCell(path_to_ic_cell_xml, path_to_ic_cell_file, domain_dict) + return path_to_ic_cell_file +end + +"""""" + pathToICECM(simulation::Simulation) + +Return the path to the IC ECM file for the given simulation, creating it if it needs to be generated from an XML file. +"""""" +function pathToICECM(simulation::Simulation) + @assert simulation.inputs[:ic_ecm].id != -1 ""No IC ecm variation being used"" #! we should have already checked this before calling this function + path_to_ic_ecm_folder = locationPath(:ic_ecm, simulation) + if isfile(joinpath(path_to_ic_ecm_folder, ""ecm.csv"")) #! ic already given by ecm.csv + return joinpath(path_to_ic_ecm_folder, ""ecm.csv"") + end + path_to_config_xml = joinpath(locationPath(:config, simulation), locationVariationsFolder(:config), ""config_variation_$(simulation.variation_id[:config]).xml"") + xml_doc = parse_file(path_to_config_xml) + config_dict = Dict{String,Float64}() + for d in [""x"", ""y""] #! does not (yet?) support 3D + for side in [""min"", ""max""] + key = ""$(d)_$(side)"" + xml_path = [""domain""; key] + config_dict[key] = getSimpleContent(xml_doc, xml_path) |> x -> parse(Float64, x) + end + key = ""d$(d)"" #! d$(d) looks funny but it's just dx and dy + xml_path = [""domain""; key] + config_dict[key] = getSimpleContent(xml_doc, xml_path) |> x -> parse(Float64, x) + end + free(xml_doc) + path_to_ic_ecm_variations = joinpath(path_to_ic_ecm_folder, locationVariationsFolder(:ic_ecm)) + path_to_ic_ecm_xml = joinpath(path_to_ic_ecm_variations, ""ic_ecm_variation_$(simulation.variation_id[:ic_ecm]).xml"") + path_to_ic_ecm_file = joinpath(path_to_ic_ecm_variations, ""ic_ecm_variation_$(simulation.variation_id[:ic_ecm])_s$(simulation.id).csv"") + generateICECM(path_to_ic_ecm_xml, path_to_ic_ecm_file, config_dict) + return path_to_ic_ecm_file +end + +################## XML Path Helper Functions ################## + +"""""" + configPath(tokens::Vararg{Union{AbstractString,Integer}}) + +Return the XML path to the configuration for the given tokens, inferring the path based on the tokens. + +This function works by calling the explicit path functions for the given tokens: +[`domainPath`](@ref), [`timePath`](@ref), [`fullSavePath`](@ref), [`svgSavePath`](@ref), [`substratePath`](@ref), [`cyclePath`](@ref), [`apoptosisPath`](@ref), [`necrosisPath`](@ref), [`volumePath`](@ref), [`mechanicsPath`](@ref), [`motilityPath`](@ref), [`secretionPath`](@ref), [`cellInteractionsPath`](@ref), [`phagocytosisPath`](@ref), [`attackRatePath`](@ref), [`fusionPath`](@ref), [`transformationPath`](@ref), [`integrityPath`](@ref), [`customDataPath`](@ref), [`initialParameterDistributionPath`](@ref), and [`userParameterPath`](@ref). + +This is an experimental feature that can perhaps standardize ways to access the configuration XML path with (hopefully) minimal referencing of the XML file. +Take a guess at what you think the inputs should be. +Depending on the number of tokens passed in, the function will try to infer the path or throw an error if it cannot. +The error message will include the possible tokens that can be used for the given number of tokens as well as the more explicit function that has specific documentation. +"""""" +function configPath(tokens::Vararg{Union{AbstractString,Integer}}) + @assert length(tokens) > 0 ""At least one token is required"" + if length(tokens) == 1 + token = tokens[1] + if token ∈ [""x_min"", ""x_max"", ""y_min"", ""y_max"", ""z_min"", ""z_max"", ""dx"", ""dy"", ""dz"", ""use_2D""] + return domainPath(token) + elseif token ∈ [""max_time"", ""dt_intracellular"", ""dt_diffusion"", ""dt_mechanics"", ""dt_phenotype""] + return timePath(token) + elseif contains(token, ""full"") && contains(token, ""data"") + return fullSavePath() + elseif contains(lowercase(token), ""svg"") && contains(token, ""save"") + return svgSavePath() + else + msg = """""" + Unrecognized singular token for configPath: $(token) + Possible singular tokens include: + - ""x_min"", ""x_max"", ""y_min"", ""y_max"", ""z_min"", ""z_max"", ""dx"", ""dy"", ""dz"", ""use_2D"" (see `domainPath`) + - ""max_time"", ""dt_intracellular"", ""dt_diffusion"", ""dt_mechanics"", ""dt_phenotype"" (see `timePath`) + - ""full_data_interval"" (see `fullSavePath`) + - ""SVG_save_interval"" (see `svgSavePath`) + + If this is a user parameter, use two tokens instead: + configPath(""user_parameter"", $(token)) # see `userParameterPath` + """""" + throw(ArgumentError(msg)) + end + elseif length(tokens) == 2 + token1, token2 = tokens + if token2 ∈ [""diffusion_coefficient"", ""decay_rate""] + return substratePath(token1, ""physical_parameter_set"", token2) + elseif token2 ∈ [""initial_condition"", ""Dirichlet_boundary_condition""] + return substratePath(token1, token2) + elseif token2 ∈ [""xmin"", ""xmax"", ""ymin"", ""ymax"", ""zmin"", ""zmax""] + return substratePath(token1, ""Dirichlet_options"", ""boundary_value:ID:$(token2)"") + elseif token2 ∈ [""total"", ""fluid_fraction"", ""nuclear"", ""fluid_change_rate"", ""cytoplasmic_biomass_change_rate"", ""nuclear_biomass_change_rate"", ""calcified_fraction"", ""calcification_rate"", ""relative_rupture_volume""] + return volumePath(token1, token2) + elseif token2 ∈ [""cell_cell_adhesion_strength"", ""cell_cell_repulsion_strength"", ""relative_maximum_adhesion_distance"", ""attachment_elastic_constant"", ""attachment_rate"", ""detachment_rate"", ""maximum_number_of_attachments""] + return mechanicsPath(token1, token2) + elseif token2 ∈ [""set_relative_equilibrium_distance"", ""set_absolute_equilibrium_distance""] + return mechanicsPath(token1, ""options"", token2) + elseif token2 ∈ [""speed"", ""persistence_time"", ""migration_bias""] + return motilityPath(token1, token2) + elseif token2 ∈ [""apoptotic_phagocytosis_rate"", ""necrotic_phagocytosis_rate"", ""other_dead_phagocytosis_rate"", ""attack_damage_rate"", ""attack_duration""] + return cellInteractionsPath(token1, token2) + elseif token2 ∈ [""damage_rate"", ""damage_repair_rate""] + return integrityPath(token1, token2) + elseif startswith(token2, ""custom"") + new_token2 = token2[8:end] |> lstrip #! remove ""custom:"", ""custom "", or ""custom: "" from the token + return customDataPath(token1, new_token2) + elseif token1 == ""save"" && lowercase(token2) ∈ [""full"", ""svg""] + if lowercase(token2) == ""full"" + return fullSavePath() + end + return svgSavePath() + elseif token1 ∈ [""user_parameter"", ""user_parameters""] + return userParameterPath(token2) + else + msg = """""" + Unrecognized tokens for configPath: $(tokens) + Possible second tokens include: + - ""diffusion_coefficient"", ""decay_rate"" (see `substratePath`) + - ""initial_condition"", ""Dirichlet_boundary_condition"" (see `substratePath`) + - ""xmin"", ""xmax"", ""ymin"", ""ymax"", ""zmin"", ""zmax"" (see `substratePath`) + - ""total"", ""fluid_fraction"", ""nuclear"", ""fluid_change_rate"", ""cytoplasmic_biomass_change_rate"", ""nuclear_biomass_change_rate"", ""calcified_fraction"", ""calcification_rate"", ""relative_rupture_volume"" (see `volumePath`) + - ""cell_cell_adhesion_strength"", ""cell_cell_repulsion_strength"", ""relative_maximum_adhesion_distance"", ""attachment_elastic_constant"", ""attachment_rate"", ""detachment_rate"", ""maximum_number_of_attachments"" (see `mechanicsPath`) + - ""set_relative_equilibrium_distance"", ""set_absolute_equilibrium_distance"" (see `mechanicsPath`) + - ""speed"", ""persistence_time"", ""migration_bias"" (see `motilityPath`) + - ""apoptotic_phagocytosis_rate"", ""necrotic_phagocytosis_rate"", ""other_dead_phagocytosis_rate"", ""attack_damage_rate"", ""attack_duration"" (see `cellInteractionsPath`) + - ""damage_rate"", ""damage_repair_rate"" (see `integrityPath`) + - ""custom:"" (see `customDataPath`) + + Alternatively, if this is a user parameter, make sure it is of the form: + configPath(""user_parameter"", ) + + Or if this is a save interval, use: + configPath(""save"", ""full"") or configPath(""save"", ""svg"") + """""" + throw(ArgumentError(msg)) + end + elseif length(tokens) == 3 + token1, token2, token3 = tokens + if token2 == ""Dirichlet_options"" + return substratePath(token1, token2, ""boundary_value:ID:$(token3)"") + elseif contains(token2, ""cycle"") && contains(token2, ""rate"") && (token3 isa Integer || all(c -> isdigit(c), token3)) + return cyclePath(token1, ""phase_transition_rates"", ""rate:start_index:$(token3)"") + elseif contains(token2, ""cycle"") && contains(token2, ""duration"") && (token3 isa Integer || all(c -> isdigit(c), token3)) + return cyclePath(token1, ""phase_durations"", ""duration:index:$(token3)"") + elseif token2 == ""apoptosis"" + return inferDeathModelPath(:apoptosis, token1, token3) + elseif token2 == ""necrosis"" + return inferDeathModelPath(:necrosis, token1, token3) + elseif token2 ∈ [""adhesion"", ""adhesion_affinity"", ""adhesion_affinities"", ""cell_adhesion"", ""cell_adhesion_affinity"", ""cell_adhesion_affinities""] + return mechanicsPath(token1, ""cell_adhesion_affinities"", ""cell_adhesion_affinity:name:$(token3)"") + elseif token2 == ""motility"" + return motilityPath(token1, ""options"", token3) + elseif token2 == ""chemotaxis"" + return motilityPath(token1, ""options"", ""chemotaxis"", token3) + elseif contains(token2, ""chemotaxis"") && contains(token2, ""advanced"") + if token3 ∈ [""enabled"", ""normalize_each_gradient""] + return motilityPath(token1, ""options"", ""advanced_chemotaxis"", token3) + else + return motilityPath(token1, ""options"", ""advanced_chemotaxis"", ""chemotactic_sensitivities"", ""chemotactic_sensitivity:substrate:$(token3)"") + end + elseif token3 ∈ [""secretion_rate"", ""secretion_target"", ""uptake_rate"", ""net_export_rate""] + return secretionPath(token1, token2, token3) + elseif token2 ∈ [""phagocytosis"", ""phagocytose""] + if token3 ∈ [""apoptotic"", ""necrotic"", ""other_dead""] + return phagocytosisPath(token1, Symbol(token3)) + else + return phagocytosisPath(token1, token3) + end + elseif token2 ∈ [""fusion"", ""fuse to""] + return fusionPath(token1, token3) + elseif token2 ∈ [""transformation"", ""transform to""] + return transformationPath(token1, token3) + elseif token2 ∈ [""attack"", ""attack_rate""] + return attackRatePath(token1, token3) + elseif token2 == ""custom"" + return customDataPath(token1, token3) + else + msg = """""" + Unrecognized triple of tokens for configPath: $(tokens) + Possible triple tokens include: + - `configPath(, ""Dirichlet_options"", )` (see `substratePath`) + - `configPath(, ""cycle_rate"", )` (see `cyclePath`) + - `configPath(, ""cycle_duration"", )` (see `cyclePath`) + - `configPath(, ""apoptosis"", )` (see `apoptosisPath`) + - `configPath(, ""necrosis"", )` (see `necrosisPath`) + - `configPath(, ""adhesion"", )` (see `mechanicsPath`) + - `configPath(, ""motility"", )` (see `motilityPath`) + - `configPath(, ""chemotaxis"", )` (see `motilityPath`) + - `configPath(, ""advanced_chemotaxis"", )` (see `motilityPath`) + - `configPath(, ""advanced_chemotaxis"", )` (see `motilityPath`) + - `configPath(, , )` (see `secretionPath`) + - `configPath(, , )` (`` is one of ""phagocytosis"", ""fusion"", ""transformation"", ""attack_rate"") (see `cellInteractionsPath`) + - `configPath(, ""custom"", )` (see `customDataPath`) + """""" + throw(ArgumentError(msg)) + end + elseif length(tokens) == 4 + token1, token2, token3, token4 = tokens + recognized_duration_tokens = [""duration""] + recognized_rate_tokens = [""rate"", ""transition_rate"", ""phase_transition_rate""] + if token2 == ""cycle"" && (token3 ∈ recognized_duration_tokens || token3 ∈ recognized_rate_tokens) + if token3 ∈ recognized_duration_tokens + return cyclePath(token1, ""phase_durations"", ""duration:index:$(token4)"") + else + return cyclePath(token1, ""phase_transition_rates"", ""rate:start_index:$(token4)"") + end + elseif token2 == ""necrosis"" + @assert token3 ∈ [""duration"", ""transition_rate""] ""Unrecognized third token for necrosis with four tokens passed in to configPath: $(token3). Needs to be either \""duration\"" or \""transition_rate\"""" + return inferDeathModelPath(:necrosis, token1, ""$(token3)_$(token4)"") + elseif contains(token2, ""initial"") && contains(token2, ""parameter"") && contains(token2, ""distribution"") + return initialParameterDistributionPath(token1, token3, token4) + else + msg = """""" + Unrecognized four tokens for configPath: $(tokens) + Possible four tokens include: + - `configPath(, ""cycle"", ""duration"", )` (see `cyclePath`) + - `configPath(, ""cycle"", ""rate"", )` (see `cyclePath`) + - `configPath(, ""necrosis"", ""duration"", )` (see `necrosisPath`) + - `configPath(, ""necrosis"", ""transition_rate"", )` (see `necrosisPath`) + - `configPath(, ""initial_parameter_distribution"", , )` (see `initialParameterDistributionPath`) + """""" + throw(ArgumentError(msg)) + end + else + throw(ArgumentError(""configPath only supports 1, 2, 3, or 4 tokens. Got $(length(tokens)) tokens."")) + end +end + +"""""" + inferDeathModelPath(death_model::Symbol, token1::AbstractString, token3::AbstractString) + +Helper function to infer the death model path based on the death model and the third token passed in to [`configPath`](@ref). +"""""" +function inferDeathModelPath(death_model::Symbol, token1::AbstractString, token3::AbstractString) + path_fn = death_model == :apoptosis ? apoptosisPath : necrosisPath + if token3 ∈ [""unlysed_fluid_change_rate"", ""lysed_fluid_change_rate"", ""cytoplasmic_biomass_change_rate"", ""nuclear_biomass_change_rate"", ""calcification_rate"", ""relative_rupture_volume""] + return path_fn(token1, ""parameters"", token3) + elseif token3 == ""rate"" || (contains(token3, ""death"") && contains(token3, ""rate"")) + return path_fn(token1, ""death_rate"") + elseif token3 ∈ [""duration"", ""duration_0""] + return path_fn(token1, ""phase_durations"", ""duration:index:0"") + elseif token3 == ""duration_1"" + return path_fn(token1, ""phase_durations"", ""duration:index:1"") + elseif token3 ∈ [""transition_rate"", ""transition_rate_0""] + return path_fn(token1, ""phase_transition_rates"", ""rate:start_index:0"") + elseif token3 == ""transition_rate_1"" + return path_fn(token1, ""phase_transition_rates"", ""rate:start_index:1"") + else + msg = """""" + Unrecognized third token for configPath when second token is ""$(death_model)"": $(token3) + Possible third tokens include: + - ""unlysed_fluid_change_rate"", ""lysed_fluid_change_rate"", ""cytoplasmic_biomass_change_rate"", ""nuclear_biomass_change_rate"", ""calcification_rate"", ""relative_rupture_volume"" + - ""death_rate"" + """""" + if death_model == :apoptosis + msg *= """""" + - ""duration"", ""transition_rate"" + """""" + else + msg *= """""" + - ""duration_0"", ""transition_rate_0"", ""duration_1"", ""transition_rate_1"" + """""" + end + throw(ArgumentError(msg)) + end +end + +"""""" + domainPath(tag::AbstractString) + +Return the XML path to the domain for the given tag. + +Possible `tag`s include: +- `""x_min""` +- `""x_max""` +- `""y_min""` +- `""y_max""` +- `""z_min""` +- `""z_max""` +- `""dx""` +- `""dy""` +- `""dz""` +- `""use_2D""` (value is `""true""`or `""false""`) +"""""" +domainPath(tag::AbstractString) = [""domain""; tag] + +"""""" + timePath(tag::AbstractString) + +Return the XML path to the time for the given tag. + +Possible `tag`s include: +- `""max_time""` +- `""dt_intracellular""` +- `""dt_diffusion""` +- `""dt_mechanics""` +- `""dt_phenotype""` +"""""" +timePath(tag::AbstractString) = [""overall""; tag] + +"""""" + fullSavePath() + +Return the XML path to the interval for full data saves. +"""""" +fullSavePath() = [""save""; ""full_data""; ""interval""] + +"""""" + svgSavePath() + +Return the XML path to the interval for SVG data saves. +"""""" +svgSavePath() = [""save""; ""SVG""; ""interval""] + +"""""" + substratePath(substrate_name::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the substrate for the given name (or deeper if more path elements are given). + +Possible `path_elements` include: +- `substratePath(, ""physical_parameter_set"", )` with `` one of + - `""diffusion_coefficient""` + - `""decay_rate""` +- `substratePath(, )` with `` one of + - `""initial_condition""` + - `""Dirichlet_boundary_condition""` +- `substratePath(, ""Dirichlet_options"", ""boundary_value:ID:"")` where `` is one of + - `""xmin""` + - `""xmax""` + - `""ymin""` + - `""ymax""` + - `""zmin""` + - `""zmax""` +"""""" +substratePath(substrate_name::AbstractString, path_elements::Vararg{AbstractString}) = [""microenvironment_setup""; ""variable:name:$(substrate_name)""; path_elements...] + +"""""" + cellDefinitionPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the cell definition or deeper if more path elements are given. +"""""" +function cellDefinitionPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + return [""cell_definitions""; ""cell_definition:name:$(cell_definition)""; path_elements...] +end + +"""""" + phenotypePath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the phenotype for the given cell type (or deeper if more path elements are given). +"""""" +function phenotypePath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + return cellDefinitionPath(cell_definition, ""phenotype"", path_elements...) +end + +"""""" + cyclePath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the cycle for the given cell type (or deeper if more path elements are given). + +Possible `path_elements` include: +- `cyclePath(, ""phase_durations"", ""duration:index:0"")` # replace 0 with the index of the phase +- `cyclePath(, ""phase_transition_rates"", ""rate:start_index:0"")` # replace 0 with the start index of the phase +"""""" +cyclePath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) = phenotypePath(cell_definition, ""cycle"", path_elements...) + +"""""" + deathPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the death for the given cell type (or deeper if more path elements are given). +Users are encouraged to use the [`apoptosisPath`](@ref) or [`necrosisPath`](@ref) functions. +"""""" +deathPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) = phenotypePath(cell_definition, ""death"", path_elements...) + +"""""" + apoptosisPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the apoptosis for the given cell type (or deeper if more path elements are given). + +Possible `path_elements` include: +- `apoptosisPath(, ""death_rate"")` +- `apoptosisPath(, ""phase_durations"", ""duration:index:0"")` # apoptosis only has one phase, so index is always 0 +- `apoptosisPath(, ""phase_transition_rates"", ""rate:start_index:0"")` # apoptosis only has one phase, so start index is always 0 +- `apoptosisPath(, ""parameters"", )` with `` one of + - `unlysed_fluid_change_rate` + - `lysed_fluid_change_rate` + - `cytoplasmic_biomass_change_rate` + - `nuclear_biomass_change_rate` + - `calcification_rate` + - `relative_rupture_volume` +"""""" +apoptosisPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) = deathPath(cell_definition, ""model:code:100"", path_elements...) + +"""""" + necrosisPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the necrosis for the given cell type (or deeper if more path elements are given). + +Possible `path_elements` are identical to those for [`apoptosisPath`](@ref) with one exception: Necrosis has two phases so the phase index can be either 0 or 1. +They include: +- `necrosisPath(, ""death_rate"")` +- `necrosisPath(, ""phase_durations"", ""duration:index:0"")` # necrosis has two phases, so index is either 0 or 1 +- `necrosisPath(, ""phase_transition_rates"", ""rate:start_index:0"")` # necrosis has two phases, so start index is either 0 or 1 +- `necrosisPath(, ""parameters"", )` with `` one of + - `unlysed_fluid_change_rate` + - `lysed_fluid_change_rate` + - `cytoplasmic_biomass_change_rate` + - `nuclear_biomass_change_rate` + - `calcification_rate` + - `relative_rupture_volume` +"""""" +necrosisPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) = deathPath(cell_definition, ""model:code:101"", path_elements...) + +"""""" + volumePath(cell_definition::AbstractString, tag::AbstractString) + +Return the XML path to the volume for the given cell type (or deeper if more path elements are given). + +Possible `tag`s include: +- `""total""` +- `""fluid_fraction""` +- `""nuclear""` +- `""fluid_change_rate""` +- `""cytoplasmic_biomass_change_rate""` +- `""nuclear_biomass_change_rate""` +- `""calcified_fraction""` +- `""calcification_rate""` +- `""relative_rupture_volume""` +"""""" +volumePath(cell_definition::AbstractString, tag::AbstractString) = phenotypePath(cell_definition, ""volume"", tag) + +"""""" + mechanicsPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the mechanics for the given cell type (or deeper if more path elements are given). + +Possible `path_elements` include: +- `mechanicsPath(, )` with `` one of + - `""cell_cell_adhesion_strength""` + - `""cell_cell_repulsion_strength""` + - `""relative_maximum_adhesion_distance""` + - `""attachment_elastic_constant""` + - `""attachment_rate""` + - `""detachment_rate""` + - `""maximum_number_of_attachments""` +- `mechanicsPath(, ""cell_adhesion_affinities"", ""cell_adhesion_affinity:name:"")` + - `` is a string of the model cell type +- `mechanicsPath(, ""options"", )` with `` one of + - `""set_relative_equilibrium_distance""` + - `""set_absolute_equilibrium_distance""` +"""""" +mechanicsPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) = phenotypePath(cell_definition, ""mechanics"", path_elements...) + +"""""" + motilityPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the motility for the given cell type (or deeper if more path elements are given). + +Possible `path_elements` include: +- `motilityPath(, )` with `` one of + - `""speed""` + - `""persistence_time""` + - `""migration_bias""` +- `motilityPath(, ""options"", )` with `` one of + - `""enabled""` (value is `""true""`or `""false""`) + - `""use_2D""` (value is `""true""`or `""false""`) +- `motilityPath(, ""options"", ""chemotaxis"", )` with `` one of + - `""enabled""` (value is `""true""`or `""false""`) + - `""substrate""` (value is string of the model substrate) + - `""direction""` (value is -1 or 1) +- `motilityPath(, ""options"", ""advanced_chemotaxis"", )` + - `""enabled""` (value is `""true""`or `""false""`) + - `""normalize_each_gradient""` (value is `""true""`or `""false""`) +- `motilityPath(, ""options"", ""advanced_chemotaxis"", ""chemotactic_sensitivities"", ""chemotactic_sensitivity:substrate:"")` + - `` is a string of the model substrate +"""""" +motilityPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) = phenotypePath(cell_definition, ""motility"", path_elements...) + +"""""" + secretionPath(cell_definition::AbstractString, substrate_name::AbstractString, tag::AbstractString) + +Return the XML path to the secretion tag of the given substrate for the given cell type. + +Possible `tag`s include: +- `""secretion_rate""` +- `""secretion_target""` +- `""uptake_rate""` +- `""net_export_rate""` +"""""" +secretionPath(cell_definition::AbstractString, substrate_name::AbstractString, tag::AbstractString) = phenotypePath(cell_definition, ""secretion"", ""substrate:name:$(substrate_name)"", tag) + +"""""" + cellInteractionsPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the cell interactions for the given cell type (or deeper if more path elements are given). + +Possible `path_elements` include: +- `cellInteractionsPath(, )` with `` one of + - `""apoptotic_phagocytosis_rate""` + - `""necrotic_phagocytosis_rate""` + - `""other_dead_phagocytosis_rate""` + - `""attack_damage_rate""` + - `""attack_duration""` +For other elements in ``, use [`phagocytosisPath`](@ref), [`attackRatePath`](@ref), or [`fusionPath`](@ref) as needed. +"""""" +cellInteractionsPath(cell_definition::AbstractString, path_elements::Vararg{AbstractString}) = phenotypePath(cell_definition, ""cell_interactions"", path_elements...) + +"""""" + phagocytosisPath(cell_definition::AbstractString, target_cell_definition::AbstractString) + phagocytosisPath(cell_definition::AbstractString, death_process::Symbol) + +Return the XML path to the phagocytosis element for the given cell type. +If a string is supplied, it is treated as a cell type. +If a symbol is supplied, it specifies a death model and must be one of `:apoptosis`, `:necrosis`, or `:other_dead`. + +# Examples +```jldoctest +julia> PhysiCellModelManager.phagocytosisPath(""M1"", ""cancer"") +6-element Vector{String}: + ""cell_definitions"" + ""cell_definition:name:M1"" + ""phenotype"" + ""cell_interactions"" + ""live_phagocytosis_rates"" + ""phagocytosis_rate:name:cancer"" +``` +```jldoctest +julia> PhysiCellModelManager.phagocytosisPath(""M1"", :apoptotic) +5-element Vector{String}: + ""cell_definitions"" + ""cell_definition:name:M1"" + ""phenotype"" + ""cell_interactions"" + ""apoptotic_phagocytosis_rate"" +``` +"""""" +phagocytosisPath(cell_definition::AbstractString, target_cell_definition::AbstractString) = cellInteractionsPath(cell_definition, ""live_phagocytosis_rates"", ""phagocytosis_rate:name:$(target_cell_definition)"") + +function phagocytosisPath(cell_definition::AbstractString, death_process::Symbol) + tag = begin + if death_process in [:apoptosis, :apoptotic] + ""apoptotic_phagocytosis_rate"" + elseif death_process in [:necrosis, :necrotic] + ""necrotic_phagocytosis_rate"" + elseif death_process == :other_dead + ""other_dead_phagocytosis_rate"" + else + msg = """""" + The `death_process` symbol passed in to `phagocytosisPath` must be one of... + :apoptosis, :necrosis, or :other_dead. + + Got: $(death_process) + """""" + throw(ArgumentError(msg)) + end + end + return cellInteractionsPath(cell_definition, tag) +end + +"""""" + attackRatePath(cell_definition::AbstractString, target_cell_definition::AbstractString) + +Return the XML path to the attack rate of the first cell type attacking the second cell type. +[`attackPath`](@ref) and [`attackRatesPath`](@ref) are synonyms for this function. + +# Examples +```jldoctest +julia> PhysiCellModelManager.attackRatePath(""cd8"", ""cancer"") +6-element Vector{String}: + ""cell_definitions"" + ""cell_definition:name:cd8"" + ""phenotype"" + ""cell_interactions"" + ""attack_rates"" + ""attack_rate:name:cancer"" +``` +"""""" +attackRatePath(cell_definition::AbstractString, target_cell_definition::AbstractString) = cellInteractionsPath(cell_definition, ""attack_rates"", ""attack_rate:name:$(target_cell_definition)"") + +"""""" + attackPath(cell_definition::AbstractString, target_cell_definition::AbstractString) + +Alias for [`attackRatePath`](@ref). +"""""" +attackPath = attackRatePath + +"""""" + attackRatesPath(cell_definition::AbstractString, target_cell_definition::AbstractString) + +Alias for [`attackRatePath`](@ref). +"""""" +attackRatesPath = attackRatePath + +"""""" + fusionPath(cell_definition::AbstractString, target_cell_definition::AbstractString) + +Return the XML path to the fusion rate of the first cell type fusing to the second cell type. + +# Examples +```jldoctest +julia> PhysiCellModelManager.fusionPath(""epi"", ""epi"") +6-element Vector{String}: + ""cell_definitions"" + ""cell_definition:name:epi"" + ""phenotype"" + ""cell_interactions"" + ""fusion_rates"" + ""fusion_rate:name:epi"" +``` +"""""" +fusionPath(cell_definition::AbstractString, target_cell_definition::AbstractString) = cellInteractionsPath(cell_definition, ""fusion_rates"", ""fusion_rate:name:$(target_cell_definition)"") + +"""""" + transformationPath(from_cell_definition::AbstractString, to_cell_definition::AbstractString) + +Return the XML path to the transformation rates for the first cell definition to the second cell definition. + +# Examples +```jldoctest +julia> PhysiCellModelManager.transformationPath(""M1"", ""M2"") +6-element Vector{String}: + ""cell_definitions"" + ""cell_definition:name:M1"" + ""phenotype"" + ""cell_transformations"" + ""transformation_rates"" + ""transformation_rate:name:M2"" +``` +"""""" +function transformationPath(from_cell_definition::AbstractString, to_cell_definition::AbstractString) + return phenotypePath(from_cell_definition, ""cell_transformations"", ""transformation_rates"", ""transformation_rate:name:$(to_cell_definition)"") +end + +"""""" + integrityPath(cell_definition::AbstractString, tag::AbstractString) + +Return the XML path to the cell integrity tag for the given cell type. + +Possible `tag`s include: +- `""damage_rate""` +- `""damage_repair_rate""` +"""""" +integrityPath(cell_definition::AbstractString, tag::AbstractString) = phenotypePath(cell_definition, ""cell_integrity"", tag) + +"""""" + customDataPath(cell_definition::AbstractString, tag::AbstractString) + +Return the XML path to the custom data tag for the given cell type. +"""""" +customDataPath(cell_definition::AbstractString, tag::AbstractString) = cellDefinitionPath(cell_definition, ""custom_data"", tag) + +"""""" + initialParameterDistributionPath(cell_definition::AbstractString, behavior::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the initial parameter distribution of the behavior for the given cell type. + +Possible `path_elements` depend on the `type` of the distribution: +- `type=""Uniform""` : `min`, `max` +- `type=""LogUniform""` : `min`, `max` +- `type=""Normal""` : `mu`, `sigma`, `lower_bound`, `upper_bound` +- `type=""LogNormal""` : `mu`, `sigma`, `lower_bound`, `upper_bound` +- `type=""Log10Normal""`: `mu`, `sigma`, `lower_bound`, `upper_bound` +"""""" +function initialParameterDistributionPath(cell_definition::AbstractString, behavior::AbstractString, path_elements::Vararg{AbstractString}) + return cellDefinitionPath(cell_definition, ""initial_parameter_distributions"", ""distribution::behavior:$(behavior)"", path_elements...) +end + +"""""" + userParameterPath(tag::AbstractString) + +Return the XML path to the user parameter for the given field name. [`userParametersPath`](@ref) is a synonym for this function. +"""""" +userParameterPath(tag::AbstractString) = [""user_parameters""; tag] + +"""""" + userParametersPath(tag::AbstractString) + +Alias for [`userParameterPath`](@ref). +"""""" +userParametersPath = userParameterPath + +############# XML Path Helper Functions (non-config) ############# + +"""""" + rulePath(cell_definition::AbstractString, behavior::AbstractString, path_elements::Vararg{AbstractString}) + +Return the XML path to the rule for the given cell type and behavior. + +Optionally, add more path_elements to the path as extra arguments. + +# Example +```jldoctest +julia> rulePath(""T cell"", ""attack rate"") +2-element Vector{String}: + ""behavior_ruleset:name:T cell"" + ""behavior:name:attack rate"" +``` +```jldoctest +julia> rulePath(""cancer"", ""cycle entry"", ""increasing_signals"", ""signal:name:oxygen"", ""half_max"") +5-element Vector{String}: + ""behavior_ruleset:name:cancer"" + ""behavior:name:cycle entry"" + ""increasing_signals"" + ""signal:name:oxygen"" + ""half_max"" +``` +"""""" +function rulePath(cell_definition::AbstractString, behavior::AbstractString, path_elements::Vararg{AbstractString}) + return [""behavior_ruleset:name:$(cell_definition)""; ""behavior:name:$(behavior)""; path_elements...] +end + +"""""" + icCellsPath(cell_definition::AbstractString, patch_type::AbstractString, patch_id, path_elements::Vararg{Union{Integer,AbstractString}}) + +Return the XML path to the IC cell patch for the given cell type, patch type, and patch ID. +The remaining arguments are either just the tag for the patch parameter or the carveout patch type, ID, and tag. + +# Examples +```jldoctest +julia> icCellsPath(""default"", ""disc"", 1, ""x0"") +4-element Vector{String}: + ""cell_patches:name:default"" + ""patch_collection:type:disc"" + ""patch:ID:1"" + ""x0"" +``` +```jldoctest +julia> icCellsPath(""default"", ""annulus"", 1, ""rectangle"", 1, ""width"") +7-element Vector{String}: + ""cell_patches:name:default"" + ""patch_collection:type:annulus"" + ""patch:ID:1"" + ""carveout_patches"" + ""patch_collection:type:rectangle"" + ""patch:ID:1"" + ""width"" +``` +"""""" +function icCellsPath(cell_definition::AbstractString, patch_type::AbstractString, patch_id, path_elements::Vararg{Union{Integer,AbstractString}}) + supported_patch_types = PhysiCellCellCreator.supportedPatchTypes() + @assert patch_type in supported_patch_types ""IC Cell patch_type must be one of the available patch types, i.e., in $(supported_patch_types). Got $(patch_type)"" + xml_path = [""cell_patches:name:$(cell_definition)""; ""patch_collection:type:$(patch_type)""; ""patch:ID:$(patch_id)""] + if length(path_elements) == 1 + #! then this is a tag of the patch + @assert path_elements[1] in PhysiCellCellCreator.supportedPatchTextElements(patch_type) ""IC Cell patch_type $(patch_type) does not support the tag $(path_elements[1]). Supported tags are: $(PhysiCellCellCreator.supportedPatchTextElements(patch_type))"" + return [xml_path; path_elements[1]] + end + @assert length(path_elements) == 3 ""After the patch ID, either one (for a patch parameter) or three (for a carveout parameter) additional path elements must be provided. Got $(length(path_elements)) elements."" + carveout_patch_type, carveout_patch_id, carveout_patch_tag = path_elements + @assert carveout_patch_type in PhysiCellCellCreator.supportedCarveoutTypes() ""IC Cell carveout type must be one of the available carveout patch types, i.e., in $(PhysiCellCellCreator.supportedCarveoutTypes()). Got $(carveout_patch_type)"" + return [xml_path; ""carveout_patches""; ""patch_collection:type:$(carveout_patch_type)""; ""patch:ID:$(carveout_patch_id)""; carveout_patch_tag] +end + +"""""" + icECMPath(layer_id::Int, patch_type::AbstractString, patch_id, path_elements::Vararg{AbstractString}) + +Return the XML path to the IC ECM patch for the given layer_id, patch_type, and patch_id. +Optionally, add more path_elements to the path as extra arguments. + +# Examples +```jldoctest +julia> icECMPath(2, ""ellipse"", 1, ""a"") +4-element Vector{String}: + ""layer:ID:2"" + ""patch_collection:type:ellipse"" + ""patch:ID:1"" + ""a"" +``` +```jldoctest +julia> icECMPath(2, ""elliptical_disc"", 1, ""density"") +4-element Vector{String}: + ""layer:ID:2"" + ""patch_collection:type:elliptical_disc"" + ""patch:ID:1"" + ""density"" +``` +```jldoctest +julia> icECMPath(2, ""ellipse_with_shell"", 1, ""interior"", ""density"") +5-element Vector{String}: + ""layer:ID:2"" + ""patch_collection:type:ellipse_with_shell"" + ""patch:ID:1"" + ""interior"" + ""density"" +``` +"""""" +function icECMPath(layer_id, patch_type::AbstractString, patch_id, path_elements::Vararg{AbstractString}) + supported_patch_types = PhysiCellECMCreator.supportedPatchTypes() + @assert patch_type in supported_patch_types ""IC ECM patch_type must be one of the available patch types, i.e., in $(supported_patch_types). Got $(patch_type)"" + xml_path = [""layer:ID:$(layer_id)""; ""patch_collection:type:$(patch_type)""; ""patch:ID:$(patch_id)""] + if length(path_elements) == 1 + #! then this is a tag of the patch + @assert path_elements[1] in PhysiCellECMCreator.supportedPatchTextElements(patch_type) ""IC ECM patch_type $(patch_type) does not support the tag $(path_elements[1]). Supported tags are: $(PhysiCellECMCreator.supportedPatchTextElements(patch_type))"" + return [xml_path; path_elements[1]] + end + @assert patch_type == ""ellipse_with_shell"" && length(path_elements) == 2 ""After the patch ID, either one (for a patch parameter) or two (for an ellipse_with_shell parameter) additional path elements must be provided. Got $(length(path_elements)) elements."" + subpatch, tag = path_elements + @assert subpatch ∈ [""interior"", ""shell"", ""exterior""] ""For the ellipse_with_shell patch type, the first argument after the patch ID must be either 'interior', 'shell', or 'exterior'. Got $(subpatch)"" + @assert tag ∈ [""density"", ""anisotropy"", ""orientation""] ""For the ellipse_with_shell patch type, the second argument after the patch ID must be either 'density', 'anisotropy', or 'orientation'. Got $(tag)"" + return [""layer:ID:$(layer_id)""; ""patch_collection:type:$(patch_type)""; ""patch:ID:$(patch_id)""; subpatch; tag] +end + +################## Simplify Name Functions ################## + +"""""" + shortLocationVariationID(fieldname) + +Return the short location variation ID name used in creating a DataFrame summary table. + +# Arguments +- `fieldname`: The field name to get the short location variation ID for. This can be a symbol or a string. +"""""" +function shortLocationVariationID(fieldname::Symbol) + if fieldname == :config + return :ConfigVarID + elseif fieldname == :rulesets_collection + return :RulesVarID + elseif fieldname == :intracellular + return :IntraVarID + elseif fieldname == :ic_cell + return :ICCellVarID + elseif fieldname == :ic_ecm + return :ICECMVarID + else + throw(ArgumentError(""Got fieldname $(fieldname). However, it must be 'config', 'rulesets_collection', 'intracellular', 'ic_cell', or 'ic_ecm'."")) + end +end + +shortLocationVariationID(fieldname::String) = shortLocationVariationID(Symbol(fieldname)) + +"""""" + shortLocationVariationID(type::Type, fieldname::Union{String, Symbol}) + +Return (as a `type`) the short location variation ID name used in creating a DataFrame summary table. +"""""" +function shortLocationVariationID(type::Type, fieldname::Union{String, Symbol}) + return type(shortLocationVariationID(fieldname)) +end + +"""""" + shortVariationName(location::Symbol, name::String) + +Return the short name of the varied parameter for the given location and name used in creating a DataFrame summary table. +"""""" +function shortVariationName(location::Symbol, name::String) + if location == :config + return shortConfigVariationName(name) + elseif location == :rulesets_collection + return shortRulesetsVariationName(name) + elseif location == :intracellular + return shortIntracellularVariationName(name) + elseif location == :ic_cell + return shortICCellVariationName(name) + elseif location == :ic_ecm + return shortICECMVariationName(name) + else + throw(ArgumentError(""location must be 'config', 'rulesets_collection', 'intracellular', 'ic_cell', or 'ic_ecm'."")) + end +end + +"""""" + shortConfigVariationName(name::String) + +Return the short name of the varied parameter in the configuration file for the given name used in creating a DataFrame summary table. +"""""" +function shortConfigVariationName(name::String) + if name == ""config_variation_id"" + return shortLocationVariationID(String, ""config"") + elseif name == ""overall/max_time"" + return ""Max Time"" + elseif name == ""save/full_data/interval"" + return ""Full Save Interval"" + elseif name == ""save/SVG/interval"" + return ""SVG Save Interval"" + elseif startswith(name, ""cell_definitions"") + return cellParameterName(name) + else + return name + end +end + +"""""" + shortRulesetsVariationName(name::String) + +Return the short name of the varied parameter in the rulesets collection file for the given name used in creating a DataFrame summary table. +"""""" +function shortRulesetsVariationName(name::String) + if name == ""rulesets_collection_variation_id"" + return shortLocationVariationID(String, ""rulesets_collection"") + else + return ruleParameterName(name) + end +end + +"""""" + shortIntracellularVariationName(name::String) + +Return the short name of the varied parameter in the intracellular file for the given name used in creating a DataFrame summary table. +"""""" +function shortIntracellularVariationName(name::String) + if name == ""intracellular_variation_id"" + return shortLocationVariationID(String, ""intracellular"") + else + return name + end +end + +"""""" + shortICCellVariationName(name::String) + +Return the short name of the varied parameter in the IC cell file for the given name used in creating a DataFrame summary table. +"""""" +function shortICCellVariationName(name::String) + if name == ""ic_cell_variation_id"" + return shortLocationVariationID(String, ""ic_cell"") + else + return icCellParameterName(name) + end +end + +"""""" + shortICECMVariationName(name::String) + +Return the short name of the varied parameter in the ECM file for the given name used in creating a DataFrame summary table. +"""""" +function shortICECMVariationName(name::String) + if name == ""ic_ecm_variation_id"" + return shortLocationVariationID(String, ""ic_ecm"") + else + return icECMParameterName(name) + end +end + +"""""" + cellParameterName(column_name::String) + +Return the short name of the varied parameter associated with a cell definition for the given column name used in creating a DataFrame summary table. +"""""" +function cellParameterName(column_name::String) + xml_path = columnNameToXMLPath(column_name) + cell_type = split(xml_path[2], "":""; limit=3) |> last + target_name = """" + for component in xml_path[3:end] + if contains(component, ""::"") + #! something like ""distribution::behavior:oxygen uptake"" for initial parameter distributions + target_name = split(component, ""::""; limit=2) |> last + target_name = split(target_name, "":""; limit=2) |> last + elseif contains(component, "":name:"") + target_name = split(component, "":""; limit=3) |> last + break + elseif contains(component, "":code:"") + target_code = split(component, "":""; limit=3) |> last + @assert target_code in [""100"", ""101""] ""Unknown code in xml path: $(target_code)"" + if target_code == ""100"" + target_name = ""apop"" + else + target_name = ""necr"" + end + break + end + end + suffix = xml_path[end] + if target_name != """" + suffix = ""$(target_name) $(suffix)"" + end + return replace(""$(cell_type): $(suffix)"", '_' => ' ') +end + +"""""" + ruleParameterName(name::String) + +Return the short name of the varied parameter associated with a ruleset for the given name used in creating a DataFrame summary table. +"""""" +function ruleParameterName(name::String) + @assert startswith(name, ""behavior_ruleset"") ""'name' for a rulesets variation name must start with 'behavior_ruleset'. Got $(name)"" + xml_path = columnNameToXMLPath(name) + cell_type = split(xml_path[1], "":""; limit=3) |> last + behavior = split(xml_path[2], "":""; limit=3) |> last + is_decreasing = xml_path[3] == ""decreasing_signals"" + if xml_path[4] == ""max_response"" + ret_val = ""$(cell_type): $(behavior) $(is_decreasing ? ""min"" : ""max"")"" + else + response = is_decreasing ? ""decreases"" : ""increases"" + signal = split(xml_path[4], "":""; limit=3) |> last + ret_val = ""$(cell_type): $(signal) $(response) $(behavior) $(xml_path[5])"" + end + return ret_val |> x->replace(x, '_' => ' ') +end + +"""""" + icCellParameterName(name::String) + +Return the short name of the varied parameter associated with a cell patch for the given name used in creating a DataFrame summary table. +"""""" +function icCellParameterName(name::String) + @assert startswith(name, ""cell_patches"") ""'name' for a cell variation name must start with 'cell_patches'. Got $(name)"" + xml_path = columnNameToXMLPath(name) + cell_type = split(xml_path[1], "":""; limit=3) |> last + patch_type = split(xml_path[2], "":""; limit=3) |> last + id = split(xml_path[3], "":""; limit=3) |> last + parameter = xml_path[4] + return ""$(cell_type) IC: $(patch_type)[$(id)] $(parameter)"" |> x->replace(x, '_' => ' ') +end + +"""""" + icECMParameterName(name::String) + +Return the short name of the varied parameter associated with a ECM patch for the given name used in creating a DataFrame summary table. +"""""" +function icECMParameterName(name::String) + @assert startswith(name, ""layer"") ""'name' for a ecm variation name must start with 'layer'. Got $(name)"" + xml_path = columnNameToXMLPath(name) + layer_id = split(xml_path[1], "":""; limit=3) |> last + patch_type = split(xml_path[2], "":""; limit=3) |> last + patch_id = split(xml_path[3], "":""; limit=3) |> last + parameter = join(xml_path[4:end], ""-"") + return ""L$(layer_id)-$(patch_type)-P$(patch_id): $(parameter)"" |> x->replace(x, '_' => ' ') +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/import_classes.jl",".jl","7132","158",""""""" + CopyOrMove + +An enum to indicate whether a source file or folder should be copied or moved during the import process. +Possible values are `_copy_` and `_move_`. +"""""" +@enum CopyOrMove _copy_ _move_ + +"""""" + ImportSource + +A struct to hold the information about a source file or folder to be imported into the PhysiCellModelManager.jl structure. + +Used internally in the [`importProject`](@ref) function to manage the import of files and folders from a user project into the PhysiCellModelManager.jl structure. + +# Fields +- `src_key::Symbol`: The key in the source dictionary. +- `input_folder_key::Symbol`: The key in the destination dictionary. +- `path_from_project::AbstractString`: The path to the source file or folder relative to the project. +- `pcmm_name::AbstractString`: The name of the file or folder in the PhysiCellModelManager.jl structure. +- `type::AbstractString`: The type of the source (e.g., file or folder). +- `required::Bool`: Indicates if the source is required for the project. +- `found::Bool`: Indicates if the source was found during import. +- `copy_or_move::CopyOrMove`: Indicates if the source should be copied or moved to the destination folder. See [`CopyOrMove`](@ref). +"""""" +mutable struct ImportSource + src_key::Symbol + input_folder_key::Symbol + path_from_project::AbstractString + pcmm_name::AbstractString + type::AbstractString + required::Bool + found::Bool + copy_or_move::CopyOrMove + + function ImportSource(src::Dict, key::AbstractString, path_from_project_base::AbstractString, default::String, type::AbstractString, required::Bool; input_folder_key::Symbol=Symbol(key), pcmm_name::String=default, copy_or_move::CopyOrMove=_copy_) + is_key = haskey(src, key) + path_from_project = joinpath(path_from_project_base, is_key ? src[key] : default) + required |= is_key + found = false + return new(Symbol(key), input_folder_key, path_from_project, pcmm_name, type, required, found, copy_or_move) + end +end + +"""""" + ImportSources + +A struct to hold the information about the sources to be imported into the PhysiCellModelManager.jl structure. + +Used internally in the [`importProject`](@ref) function to manage the import of files and folders from a user project into the PhysiCellModelManager.jl structure. + +# Fields +- `config::ImportSource`: The config file to be imported. +- `main::ImportSource`: The main.cpp file to be imported. +- `makefile::ImportSource`: The Makefile to be imported. +- `custom_modules::ImportSource`: The custom modules folder to be imported. +- `rulesets_collection::ImportSource`: The rulesets collection to be imported. +- `intracellular::ImportSource`: The intracellular components to be imported. +- `ic_cell::ImportSource`: The cell definitions to be imported. +- `ic_substrate::ImportSource`: The substrate definitions to be imported. +- `ic_ecm::ImportSource`: The extracellular matrix definitions to be imported. +- `ic_dc::ImportSource`: The DC definitions to be imported. +"""""" +struct ImportSources + config::ImportSource + main::ImportSource + makefile::ImportSource + custom_modules::ImportSource + rulesets_collection::ImportSource + intracellular::ImportSource + ic_cell::ImportSource + ic_substrate::ImportSource + ic_ecm::ImportSource + ic_dc::ImportSource + + function ImportSources(src::Dict, path_to_project::AbstractString) + if haskey(src, ""rules"") + src[""rulesets_collection""] = src[""rules""] + end + + required = true + config = ImportSource(src, ""config"", ""config"", ""PhysiCell_settings.xml"", ""file"", required) + main = ImportSource(src, ""main"", """", ""main.cpp"", ""file"", required; input_folder_key = :custom_code) + makefile = ImportSource(src, ""makefile"", """", ""Makefile"", ""file"", required; input_folder_key = :custom_code) + custom_modules = ImportSource(src, ""custom_modules"", """", ""custom_modules"", ""folder"", required; input_folder_key = :custom_code) + + required = false + rules = prepareRulesetsCollectionImport(src, path_to_project) + intracellular = prepareIntracellularImport(src, config, path_to_project) #! config here could contain the element which would inform this import + ic_cell = ImportSource(src, ""ic_cell"", ""config"", ""cells.csv"", ""file"", required) + ic_substrate = ImportSource(src, ""ic_substrate"", ""config"", ""substrates.csv"", ""file"", required) + ic_ecm = ImportSource(src, ""ic_ecm"", ""config"", ""ecm.csv"", ""file"", required) + ic_dc = ImportSource(src, ""ic_dc"", ""config"", ""dcs.csv"", ""file"", required) + return new(config, main, makefile, custom_modules, rules, intracellular, ic_cell, ic_substrate, ic_ecm, ic_dc) + end +end + +"""""" + ImportDestFolder + +A struct to hold the information about a destination folder to be created in the PhysiCellModelManager.jl structure. + +Used internally in the [`importProject`](@ref) function to manage the creation of folders in the PhysiCellModelManager.jl structure. + +# Fields +- `path_from_inputs::AbstractString`: The path to the destination folder relative to the inputs folder. +- `created::Bool`: Indicates if the folder was created during the import process. +- `description::AbstractString`: A description of the folder. +"""""" +mutable struct ImportDestFolder + path_from_inputs::AbstractString + created::Bool + description::AbstractString + + function ImportDestFolder(location::Symbol, folder::AbstractString, description::AbstractString) + location_dict = inputsDict()[location] + path_from_inputs = joinpath(location_dict[""path_from_inputs""], folder) + created = false + return new(path_from_inputs, created, description) + end +end + +"""""" + ImportDestFolders + +A struct to hold the information about the destination folders to be created in the PhysiCellModelManager.jl structure. + +Used internally in the [`importProject`](@ref) function to manage the creation of folders in the PhysiCellModelManager.jl structure. + +# Fields +- `import_dest_folders::NamedTuple`: A named tuple containing the destination folders. The keys are the project locations and the values are [`ImportDestFolder`](@ref) instances. +"""""" +struct ImportDestFolders + import_dest_folders::NamedTuple + + function ImportDestFolders(path_to_project::AbstractString, dest::Union{AbstractString,Dict}) + default_name = splitpath(path_to_project)[end] + + if dest isa Dict && haskey(dest, ""rules"") + dest[""rulesets_collection""] = dest[""rules""] + end + + locs = projectLocations().all + + loc_name_pairs = dest isa AbstractString ? + [loc => dest for loc in locs] : + [loc => haskey(dest, String(loc)) ? dest[String(loc)] : default_name for loc in locs] + + description = ""Imported from project at $(path_to_project)."" + + loc_folder_pairs = [loc => ImportDestFolder(loc, name, description) for (loc, name) in loc_name_pairs] + + return new(NamedTuple(loc_folder_pairs)) + end +end + +Base.getindex(import_dest_folders::ImportDestFolders, loc::Symbol)::ImportDestFolder = import_dest_folders.import_dest_folders[loc] +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/PhysiCellModelManager.jl",".jl","15614","418","module PhysiCellModelManager + +using SQLite, DataFrames, LightXML, Dates, CSV, Tables, Distributions, Statistics, Random, QuasiMonteCarlo, Sobol, Compat +using PhysiCellXMLRules, PhysiCellCellCreator + +export initializeModelManager, simulationIDs, setNumberOfParallelSims, monadIDs +export getSimulationIDs, getMonadIDs #! deprecated aliases + +#! put these first as they define classes the rest rely on +include(""utilities.jl"") +include(""classes.jl"") +include(""project_configuration.jl"") +include(""hpc.jl"") +include(""globals.jl"") +include(""pruner.jl"") +include(""variations.jl"") + +include(""compilation.jl"") +include(""configuration.jl"") +include(""creation.jl"") +include(""database.jl"") +include(""deletion.jl"") +include(""ic_cell.jl"") +include(""ic_ecm.jl"") +include(""runner.jl"") +include(""recorder.jl"") +include(""up.jl"") +include(""pcmm_version.jl"") +include(""physicell_version.jl"") +include(""components.jl"") + +include(""user_api.jl"") + +include(""loader.jl"") + +include(""analysis/analysis.jl"") +include(""sensitivity.jl"") +include(""import.jl"") +include(""movie.jl"") + +include(""physicell_studio.jl"") +include(""export.jl"") + +"""""" + baseToExecutable(s::String) + +Convert a string to an executable name based on the operating system. +If the operating system is Windows, append "".exe"" to the string. +"""""" +function baseToExecutable end +if Sys.iswindows() + baseToExecutable(s::String) = ""$(s).exe"" +else + baseToExecutable(s::String) = s +end + +"""""" + PCMMMissingProject + +An exception type for when a PhysiCellModelManager.jl project cannot be found during initialization. + +# Fields +- `msg::String`: The error message. +"""""" +struct PCMMMissingProject <: Exception + msg::String +end + +function __init__() + pcmm_globals.physicell_compiler = haskey(ENV, ""PHYSICELL_CPP"") ? ENV[""PHYSICELL_CPP""] : ""g++"" + + pcmm_globals.max_number_of_parallel_simulations = haskey(ENV, ""PCMM_NUM_PARALLEL_SIMS"") ? parse(Int, ENV[""PCMM_NUM_PARALLEL_SIMS""]) : 1 + + pcmm_globals.path_to_python = haskey(ENV, ""PCMM_PYTHON_PATH"") ? ENV[""PCMM_PYTHON_PATH""] : missing + pcmm_globals.path_to_studio = haskey(ENV, ""PCMM_STUDIO_PATH"") ? ENV[""PCMM_STUDIO_PATH""] : missing + pcmm_globals.path_to_magick = haskey(ENV, ""PCMM_IMAGEMAGICK_PATH"") ? ENV[""PCMM_IMAGEMAGICK_PATH""] : (Sys.iswindows() ? missing : ""/opt/homebrew/bin"") + pcmm_globals.path_to_ffmpeg = haskey(ENV, ""PCMM_FFMPEG_PATH"") ? ENV[""PCMM_FFMPEG_PATH""] : (Sys.iswindows() ? missing : ""/opt/homebrew/bin"") + + try + initializeModelManager() + catch e + if !(e isa PCMMMissingProject) + rethrow(e) + end + @info """""" + PhysiCellModelManager: Could not find a project to initialize in $(pwd()). Do the following to begin: + 1) (Optional) Create a new project with `createProject()` or `createProject(""path/to/project"")`. + 2) Run `initializeModelManager(""path/to/project"")` or `initializeModelManager(""path/to/physicell"", ""path/to/data"")`. + """""" + end +end + +################## Initialization Functions ################## + +"""""" + pcmmLogo() + +Return a string representation of the awesome PhysiCellModelManager.jl logo. +"""""" +function pcmmLogo() + return """""" + \n + ▐▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▌ + ▐~~███████████~~~~█████████~~██████~~~██████~██████~~~██████~▌ + ▐~░░███░░░░░███~~███░░░░░███░░██████~██████~░░██████~██████~~▌ + ▐~~░███~~~~░███~███~~~~~░░░~~░███░█████░███~~░███░█████░███~~▌ + ▐~~░██████████~░███~~~~~~~~~~░███░░███~░███~~░███░░███~░███~~▌ + ▐~~░███░░░░░░~~░███~~~~~~~~~~░███~░░░~~░███~~░███~░░░~~░███~~▌ + ▐~~░███~~~~~~~~░░███~~~~~███~░███~~~~~~░███~~░███~~~~~~░███~~▌ + ▐~~█████~~~~~~~~░░█████████~~█████~~~~~█████~█████~~~~~█████~▌ + ▐~░░░░░~~~~~~~~~~░░░░░░░░░~~░░░░░~~~~~░░░░░~░░░░░~~~~~░░░░░~~▌ + ▐▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄��▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▌ + \n + """""" +end + +"""""" + initializeModelManager() + initializeModelManager(path_to_project_dir::AbstractString) + initializeModelManager(path_to_physicell::AbstractString, path_to_data::AbstractString) + +Initialize the PhysiCellModelManager.jl project model manager, identifying the data folder, PhysiCell folder, and loading the central database. + +If no arguments are provided, it assumes that the PhysiCell and data directories are in the current working directory. + +# Arguments +- `path_to_project_dir::AbstractString`: Path to the project directory as either an absolute or relative path. This folder must contain the `PhysiCell` and `data` directories. +- `path_to_physicell::AbstractString`: Path to the PhysiCell directory as either an absolute or relative path. +- `path_to_data::AbstractString`: Path to the data directory as either an absolute or relative path. +"""""" +function initializeModelManager(path_to_physicell::AbstractString, path_to_data::AbstractString; auto_upgrade::Bool=false) + global pcmm_globals + path_to_physicell, path_to_data = (path_to_physicell, path_to_data) .|> abspath .|> normpath + + if !isdir(path_to_physicell) || !isdir(path_to_data) + throw(PCMMMissingProject(""Could not find PhysiCell and/or data directories. Looked for them in: $path_to_physicell, $path_to_data"")) + end + + #! print big logo of PhysiCellModelManager.jl here + println(pcmmLogo()) + pcmm_globals.physicell_dir = path_to_physicell + pcmm_globals.data_dir = path_to_data + findCentralDB() + #! start with PhysiCellModelManager.jl version info + if !resolvePCMMVersion(auto_upgrade) + println(""Could not successfully upgrade database. Please check the logs for more information."") + return false + end + s = ""PhysiCellModelManager.jl v$(string(pcmmVersion()))"" + println(s) + println(""-""^length(s)) + println(rpad(""Path to PhysiCell:"", 25, ' ') * physicellDir()) + println(rpad(""Path to data:"", 25, ' ') * dataDir()) + println(rpad(""Path to database:"", 25, ' ') * centralDB().file) + println(rpad(""Path to inputs.toml:"", 25, ' ') * pathToInputsConfig()) + if !parseProjectInputsConfigurationFile() + println(""Project configuration file parsing failed."") + return false + end + initializeDatabase() + if !isInitialized() + pcmm_globals.db = SQLite.DB() + println(""Database initialization failed."") + return false + end + println(rpad(""PhysiCell version:"", 25, ' ') * physicellInfo()) + println(rpad(""Compiler:"", 25, ' ') * pcmm_globals.physicell_compiler) + println(rpad(""Running on HPC:"", 25, ' ') * string(pcmm_globals.run_on_hpc)) + println(rpad(""Max parallel sims:"", 25, ' ') * string(pcmm_globals.max_number_of_parallel_simulations)) + flush(stdout) + + try + databaseDiagnostics() + catch e + """""" + Database diagnostics failed during initialization with error: $(e). + PCMM was not able to check the integrity of the database. + This is unexpected behavior; please report this issue on the PhysiCellModelManager.jl GitHub page. + """""" |> println + end + + return isInitialized() +end + +function initializeModelManager(path_to_project::AbstractString; kwargs...) + path_to_physicell, path_to_data = (joinpath(path_to_project, folder) for folder in (""PhysiCell"", ""data"")) + return initializeModelManager(path_to_physicell, path_to_data; kwargs...) +end + +initializeModelManager(; kwargs...) = initializeModelManager(""PhysiCell"", ""data""; kwargs...) + +################## Selection Functions ################## + +"""""" + constituentType(T::Type{<:AbstractTrial}) + constituentType(T::AbstractTrial) + +Return the type of the constituents of `T`. Used in the [`constituentIDs`](@ref) function. +"""""" +constituentType(::Type{Simulation}) = throw(ArgumentError(""Type Simulation does not have constituents."")) +constituentType(::Type{Monad}) = Simulation +constituentType(::Type{Sampling}) = Monad +constituentType(::Type{Trial}) = Sampling + +constituentType(T::AbstractTrial) = constituentType(typeof(T)) + +"""""" + constituentTypeFilename(T::Type{<:AbstractTrial}) + constituentTypeFilename(T::AbstractTrial) + +Return the filename of the constituents of `T`. Used in the [`constituentIDs`](@ref) function. +"""""" +constituentTypeFilename(T) = ""$(T |> constituentType |> lowerClassString)s.csv"" + +"""""" + constituentIDs(T::AbstractTrial) + constituentIDs(::Type{T}, id::Int) where {T<:AbstractTrial} + +Read a CSV file containing constituent IDs from `T` and return them as a vector of integers. + +For a trial, this is the sampling IDs. +For a sampling, this is the monad IDs. +For a monad, this is the simulation IDs. + +# Examples +```julia +ids = constituentIDs(Sampling(1)) # read the IDs of the monads in sampling 1 +ids = constituentIDs(Sampling, 1) # identical to above but does not need to create the Sampling object + +ids = constituentIDs(Monad, 1) # read the IDs of the simulations in monad 1 +ids = constituentIDs(Trial, 1) # read the IDs of the samplings in trial 1 +``` +"""""" +function constituentIDs(path_to_csv::String) + if !isfile(path_to_csv) + return Int[] + end + df = CSV.read(path_to_csv, DataFrame; header=false, silencewarnings=true, types=String, delim="","") + ids = Int[] + for i in axes(df,1) + s = df.Column1[i] + I = split(s,"":"") .|> x->parse(Int,x) + if length(I)==1 + push!(ids,I[1]) + else + append!(ids,I[1]:I[2]) + end + end + return ids +end + +constituentIDs(T::AbstractTrial) = constituentIDs(joinpath(trialFolder(T), constituentTypeFilename(T))) +constituentIDs(::Type{T}, id::Int) where {T<:AbstractTrial} = constituentIDs(joinpath(trialFolder(T, id), constituentTypeFilename(T))) + +"""""" + samplingSimulationIDs(sampling_id::Int) + +Internal function to get the simulation IDs for a given sampling ID. Users should use [`simulationIDs`](@ref) instead. +"""""" +function samplingSimulationIDs(sampling_id::Int) + monad_ids = constituentIDs(Sampling, sampling_id) + return vcat([constituentIDs(Monad, monad_id) for monad_id in monad_ids]...) +end + +"""""" + trialSimulationIDs(trial_id::Int) + +Internal function to get the simulation IDs for a given trial ID. Users should use [`simulationIDs`](@ref) instead. +"""""" +function trialSimulationIDs(trial_id::Int) + sampling_ids = constituentIDs(Trial, trial_id) + return vcat([samplingSimulationIDs(sampling_id) for sampling_id in sampling_ids]...) +end + +"""""" + simulationIDs() + +Return a vector of all simulation IDs in the database. + +Alternate forms take a simulation, monad, sampling, or trial object (or an array of any combination of them) and return the corresponding simulation IDs. + +# Examples +```julia +simulationIDs() # all simulation IDs in the database +simulationIDs(simulation) # just a vector with the simulation ID, i.e. [simulation.id] +simulationIDs(monad) # all simulation IDs in a monad +simulationIDs(sampling) # all simulation IDs in a sampling +simulationIDs(trial) # all simulation IDs in a trial +simulationIDs([trial1, trial2]) # all simulation IDs between trial1 and trial2 +``` +"""""" +simulationIDs() = constructSelectQuery(""simulations""; selection=""simulation_id"") |> queryToDataFrame |> x -> x.simulation_id +simulationIDs(simulation::Simulation) = [simulation.id] +simulationIDs(monad::Monad) = constituentIDs(monad) +simulationIDs(sampling::Sampling) = samplingSimulationIDs(sampling.id) +simulationIDs(trial::Trial) = trialSimulationIDs(trial.id) +simulationIDs(Ts::AbstractArray{<:AbstractTrial}) = reduce(vcat, simulationIDs.(Ts)) + +"""""" + getSimulationIDs(args...) + +Deprecated alias for [`simulationIDs`](@ref). Use `simulationIDs` instead. +"""""" +function getSimulationIDs(args...) + Base.depwarn(""`getSimulationIDs` is deprecated. Use `simulationIDs` instead."", :getSimulationIDs; force=true) + return simulationIDs(args...) +end + +"""""" + trialMonads(trial_id::Int) + +Internal function to get the monad IDs for a given trial ID. Users should use [`monadIDs`](@ref) instead. +"""""" +function trialMonads(trial_id::Int) + sampling_ids = constituentIDs(Trial, trial_id) + return vcat([constituentIDs(Sampling, sampling_id) for sampling_id in sampling_ids]...) +end + +"""""" + monadIDs() + +Return a vector of all monad IDs in the database. + +Alternate forms take a monad, sampling, or trial object (or an array of any combination of them) and return the corresponding monad IDs. + +# Examples +```julia +monadIDs() # all monad IDs in the database +monadIDs(monad) # just a vector with the monad ID, i.e. [monad.id] +monadIDs(sampling) # all monad IDs in a sampling +monadIDs(trial) # all monad IDs in a trial +monadIDs([trial1, trial2]) # all monad IDs between trial1 and trial2 +``` +"""""" +monadIDs() = constructSelectQuery(""monads""; selection=""monad_id"") |> queryToDataFrame |> x -> x.monad_id +monadIDs(monad::Monad) = [monad.id] +monadIDs(sampling::Sampling) = constituentIDs(sampling) +monadIDs(trial::Trial) = trialMonads(trial.id) +monadIDs(Ts::AbstractArray{<:AbstractTrial}) = reduce(vcat, monadIDs.(Ts)) + +"""""" + getMonadIDs(args...) + +Deprecated alias for [`monadIDs`](@ref). Use `monadIDs` instead. +"""""" +function getMonadIDs(args...) + Base.depwarn(""`getMonadIDs` is deprecated. Use `monadIDs` instead."", :getMonadIDs; force=true) + return monadIDs(args...) +end + +################## Miscellaneous Functions ################## + +"""""" + trialFolder(T::Type{<:AbstractTrial}, id::Int) + +Return the path to the folder for a given subtype of [`AbstractTrial`](@ref) and ID. + +# Examples +```julia +trialFolder(Simulation, 1) +# output +""abs/path/to/data/outputs/simulations/1"" +``` +"""""" +trialFolder(T::Type{<:AbstractTrial}, id::Int) = joinpath(dataDir(), ""outputs"", ""$(lowerClassString(T))s"", string(id)) + +"""""" + trialFolder(T::Type{<:AbstractTrial}) + +Return the path to the folder for the [`AbstractTrial`](@ref) object, `T`. + +# Examples +```julia +simulation = Simulation(1) +trialFolder(Simulation) +# output +""abs/path/to/data/outputs/simulations/1"" +``` +"""""" +trialFolder(T::AbstractTrial) = trialFolder(typeof(T), T.id) + +"""""" + lowerClassString(T::AbstractTrial) + lowerClassString(T::Type{<:AbstractTrial}) + +Return the lowercase string representation of the type of `T`, excluding the module name. Without this, it may return, e.g., Main.PhysiCellModelManager.Sampling. + +# Examples +```julia +lowerClassString(Simulation) # ""simulation"" +lowerClassString(Simulation(1)) # ""simulation"" +``` +"""""" +function lowerClassString(::Type{T}) where {T<:AbstractTrial} + return nameof(T) |> String |> lowercase +end + +lowerClassString(T::AbstractTrial) = lowerClassString(typeof(T)) + +"""""" + setMarchFlag(flag::String) + +Set the march flag to `flag`. Used for compiling the PhysiCell code. +"""""" +function setMarchFlag(flag::String) + pcmm_globals.march_flag = flag +end + +"""""" + setNumberOfParallelSims(n::Int) + +Set the maximum number of parallel simulations to `n`. +"""""" +function setNumberOfParallelSims(n::Int) + pcmm_globals.max_number_of_parallel_simulations = n +end + +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/physicell_studio.jl",".jl","6066","140","using CSV, DataFrames + +export runStudio + +"""""" + runStudio(simulation_id::Int; python_path::Union{Missing,String}=pcmm_globals.path_to_python, studio_path::Union{Missing,String}=pcmm_globals.path_to_studio) + +Launch PhysiCell Studio for a given simulation. + +Creates temporary config and rules files to avoid overwriting the original files in the output folder. +The intent of this function is to allow users to visualize the results of a simulation with Studio, rather than to modify the simulation itself. + +The path to the python executable and the Studio folder must be set. +When calling `using PhysiCellModelManager`, shell environment variables `PCMM_PYTHON_PATH` and `PCMM_STUDIO_PATH` will be used to set the path to the python executable and the Studio folder, respectively. +**Note**: these should match how you would run PhysiCell Studio from the command line, e.g.: `export PCMM_PYTHON_PATH=python`. + +If the paths are not set in the environment, they can be passed as the keyword arguments `python_path` and `studio_path` to this function. +In this case, the paths will be set as global variables for the duration of the Julia session and do not need to be passed again. +"""""" +function runStudio(simulation_id::Int; python_path::Union{Missing,String}=pcmm_globals.path_to_python, studio_path::Union{Missing,String}=pcmm_globals.path_to_studio) + assertInitialized() + resolveStudioGlobals(python_path, studio_path) + path_to_temp_xml, path_to_input_rules = setUpStudioInputs(simulation_id) + out = executeStudio(path_to_temp_xml) + cleanUpStudioInputs(path_to_temp_xml, path_to_input_rules) + if out isa Exception + throw(out) + end +end + +runStudio(simulation::Simulation; kwargs...) = runStudio(simulation.id; kwargs...) + +runStudio(pcmm_output::PCMMOutput{Simulation}; kwargs...) = runStudio(pcmm_output.trial; kwargs...) + +"""""" + resolveStudioGlobals(python_path::Union{Missing,String}, studio_path::Union{Missing,String}) + +Set the global variables `path_to_python` and `path_to_studio` to the given paths. + +They are required to not be `missing` so that the function `runStudio` works. +"""""" +function resolveStudioGlobals(python_path::Union{Missing,String}, studio_path::Union{Missing,String}) + if ismissing(python_path) + throw(ArgumentError(""Path to python not set. Please set the PCMM_PYTHON_PATH environment variable or pass the path as an argument."")) + else + pcmm_globals.path_to_python = python_path + end + if ismissing(studio_path) + throw(ArgumentError(""Path to studio not set. Please set the PCMM_STUDIO_PATH environment variable or pass the path as an argument."")) + else + pcmm_globals.path_to_studio = studio_path + end +end + +"""""" + setUpStudioInputs(simulation_id::Int) + +Set up the inputs for PhysiCell Studio. +Creates a temporary XML file and a temporary rules file (if applicable) in the output folder of the simulation. +"""""" +function setUpStudioInputs(simulation_id::Int) + path_to_output = pathToOutputFolder(simulation_id) + + physicell_version = physicellVersion(Simulation(simulation_id)) + upstream_version = split(physicell_version, ""-"")[1] |> VersionNumber + + rules_header = [""cell_type"", ""signal"", ""response"", ""behavior"", ""base_response"", ""max_response"", ""half_max"", ""hill_power"", ""applies_to_dead""] + if upstream_version < v""1.14.0"" + output_rules_file = ""cell_rules.csv"" + else #! starting in PhysiCell v1.14.1, export the v3 rules to cell_rules_parsed.csv + output_rules_file = ""cell_rules_parsed.csv"" + filter!(h -> h != ""base_response"", rules_header) + end + + path_to_xml = joinpath(path_to_output, ""PhysiCell_settings.xml"") + @assert isfile(path_to_xml) ""The file $path_to_xml does not exist. Please check the simulation ID and try again."" + xml_doc = parse_file(path_to_xml) + save_folder_element = makeXMLPath(xml_doc, [""save"", ""folder""]) + set_content(save_folder_element, path_to_output) + if isfile(joinpath(path_to_output, output_rules_file)) + rules_df = CSV.read(joinpath(path_to_output, output_rules_file), DataFrame; header=rules_header, silencewarnings=true) + if ""base_response"" in rules_header + select!(rules_df, Not(:base_response)) + end + + input_rules_file = ""cell_rules_temp.csv"" + path_to_input_rules = joinpath(path_to_output, input_rules_file) + CSV.write(path_to_input_rules, rules_df, header=false) + + enabled_ruleset_element = makeXMLPath(xml_doc, [""cell_rules"", ""rulesets"", ""ruleset:enabled:true""]) + folder_element = makeXMLPath(enabled_ruleset_element, ""folder"") + filename_element = makeXMLPath(enabled_ruleset_element, ""filename"") + + set_content(folder_element, path_to_output) + set_content(filename_element, input_rules_file) + else + path_to_input_rules = nothing + end + + path_to_temp_xml = joinpath(path_to_output, ""PhysiCell_settings_temp.xml"") + save_file(xml_doc, path_to_temp_xml) + free(xml_doc) + + return path_to_temp_xml, path_to_input_rules +end + +"""""" + executeStudio(path_to_temp_xml::String) + +Run PhysiCell Studio with the given temporary XML file. +"""""" +function executeStudio(path_to_temp_xml::String) + cmd = `$(pcmm_globals.path_to_python) $(joinpath(pcmm_globals.path_to_studio, ""bin"", ""studio.py"")) -c $(path_to_temp_xml)` + try + quietRun(cmd) + catch e + msg = """""" + Error running PhysiCell Studio. Please check the paths and ensure that PhysiCell Studio is installed correctly. + The command that was run was: + $(cmd) + + The error message was: + $(sprint(showerror, e)) + """""" + + return Base.IOError(msg, e.code) + end +end + +"""""" + cleanUpStudioInputs(path_to_temp_xml::String, path_to_input_rules::Union{Nothing,String}) + +Clean up the temporary files created for PhysiCell Studio. +"""""" +function cleanUpStudioInputs(path_to_temp_xml::String, path_to_input_rules::Union{Nothing,String}) + rm(path_to_temp_xml, force=true) + if !isnothing(path_to_input_rules) + rm(path_to_input_rules, force=true) + end +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/pcmm_version.jl",".jl","3461","91","using Pkg + +"""""" + pcmmVersion() + +Returns the version of the PhysiCellModelManager.jl package. +"""""" +function pcmmVersion() + proj = Pkg.project() + version = if proj.name == ""PhysiCellModelManager"" + proj.version + else + deps = Pkg.dependencies() + pcmm_uuid = findfirst(dep -> dep.name == ""PhysiCellModelManager"", deps) + isnothing(pcmm_uuid) && throw(ArgumentError(""PhysiCellModelManager is not a dependency of the current project. How are you even running this?"")) + deps[pcmm_uuid].version + end + return version +end + +"""""" + pcmmDBVersion() + +Returns the version of the PhysiCellModelManager.jl database. If the database does not exist, it creates a new one with the current PhysiCellModelManager.jl version. +"""""" +function pcmmDBVersion() + #! check if versions table exists + pcmm_version = versionFromTable(""pcmm_version"") + if !isnothing(pcmm_version) + return pcmm_version + end + #! if not, try looking for the old version table + pcvct_version = versionFromTable(""pcvct_version"") + if !isnothing(pcvct_version) + return pcvct_version + end + #! if neither exists, create a new version table with the current pcmm version + pcmm_version = pcmmVersion() + DBInterface.execute(centralDB(), ""CREATE TABLE IF NOT EXISTS pcmm_version (version TEXT PRIMARY KEY);"") + DBInterface.execute(centralDB(), ""INSERT INTO pcmm_version (version) VALUES ('$(pcmm_version)');"") + + return pcmm_version +end + +"""""" + versionFromTable(table_name::String; kwargs...) + +Returns the version from the specified table if it exists, otherwise returns nothing. +The `kwargs...` are passed to the `tableExists` function to check if the table exists. +"""""" +function versionFromTable(table_name::String; kwargs...) + if !tableExists(table_name; kwargs...) #! important for helping upgrade to pcvct_version -> pcmm_version in db (can be removed at v0.2.0 or whenever we drop support for <0.30.0) + return nothing + end + + return queryToDataFrame(""SELECT * FROM $(table_name);"") |> x -> x.version[1] |> VersionNumber +end + +"""""" + resolvePCMMVersion(auto_upgrade::Bool) + +Resolve differences between the PhysiCellModelManager.jl version and the database version. +If the PhysiCellModelManager.jl version is lower than the database version, it returns false (upgrade your version of PhysiCellModelManager.jl to match what was already used for the database). +If the PhysiCellModelManager.jl version is equal to the database version, it returns true. +If the PhysiCellModelManager.jl version is higher than the database version, it upgrades the database to the current PhysiCellModelManager.jl version and returns true. +"""""" +function resolvePCMMVersion(auto_upgrade::Bool) + pcmm_version = pcmmVersion() + pcmm_db_version = pcmmDBVersion() + + if pcmm_version < pcmm_db_version + msg = """""" + The PhysiCellModelManager.jl version is $(pcmm_version) but the database version is $(pcmm_db_version). \ + Upgrade your PhysiCellModelManager.jl version to $(pcmm_db_version) or higher: + pkg> registry add https://github.com/drbergman-lab/BergmanLabRegistry + pkg> registry up BergmanLabRegistry + """""" + println(msg) + success = false + return success + end + + if pcmm_version == pcmm_db_version + success = true + return success + end + + success = upgradePCMM(pcmm_db_version, pcmm_version, auto_upgrade) + return success +end +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/ic_cell.jl",".jl","2441","49","using PhysiCellCellCreator + +@compat public createICCellXMLTemplate + +"""""" + createICCellXMLTemplate(folder::String) + +Create folder with a template XML file for IC cells. + +See the [PhysiCellCellCreator.jl](https://github.com/drbergman-lab/PhysiCellCellCreator.jl) documentation for more information on IC cells and how this function works outside of PhysiCellModelManager.jl. +This PhysiCellModelManager.jl function runs the `createICCellXMLTemplate` function from PhysiCellCellCreator.jl and then updates the database. +Furthermore, the folder can be passed in just as the name of the folder located in `data/inputs/ics/cells/` rather than the full path. + +This functionality is run outside of a PhysiCell runtime. +It will not work in PhysiCell! +This function creates a template XML file for IC cells, showing all the current functionality of this initialization scheme. +It uses the cell type \""default\"". +Create ICs for more cell types by copying the `cell_patches` element. +The `ID` attribute in `patch` elements is there exactly to allow variations to target specific patches. +Manually maintain these or you will not be able to vary specific patches effectively. + +Each time a simulation is run that is using a cells.xml file, a new CSV file will be created, drawing randomly from the patches defined in the XML file. +These will all be stored with `data/inputs/ics/cells/folder/$(PhysiCellModelManager.locationVariationsFolder(:ic_cell))` as `ic_cell_variation_#_s#.csv` where the first `#` is the variation ID associated with variation on the XML file and the second `#` is the simulation ID. +Importantly, no two simulations will use the same CSV file. +"""""" +function createICCellXMLTemplate(folder::String) + if length(splitpath(folder)) == 1 + @assert isInitialized() ""Must supply a full path to the folder if the database is not initialized."" + #! then the folder is just the name of the ics/cells/folder folder + path_to_folder = locationPath(:ic_cell, folder) + else + path_to_folder = folder + folder = splitpath(folder)[end] + end + + if isfile(joinpath(path_to_folder, ""cells.xml"")) + println(""cells.xml already exists in $path_to_folder. Skipping."") + return folder + end + + PhysiCellCellCreator.createICCellXMLTemplate(path_to_folder) + + #! finish by adding this folder to the database + if isInitialized() + insertFolder(:ic_cell, folder) + end + + return folder +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/project_configuration.jl",".jl","10063","294","using TOML + +"""""" + ProjectLocations + +A struct that contains information about the locations of input files in the project. + +The global instance of this struct is `project_locations` in `pcmm_globals` (the sole instance of [`PCMMGlobals`](@ref)) and is created by reading the `inputs.toml` file in the data directory. +It is instantiated with the [`parseProjectInputsConfigurationFile`](@ref) function. + +# Fields +- `all::NTuple{L,Symbol}`: A tuple of all locations in the project. +- `required::NTuple{M,Symbol}`: A tuple of required locations in the project. +- `varied::NTuple{N,Symbol}`: A tuple of varied locations in the project. +"""""" +struct ProjectLocations{L,M,N} + all::NTuple{L,Symbol} + required::NTuple{M,Symbol} + varied::NTuple{N,Symbol} + + function ProjectLocations(d::Dict{Symbol,Any}) + all_locations = (location for location in keys(d)) |> collect |> sort |> Tuple + required = (location for (location, location_dict) in pairs(d) if location_dict[""required""]) |> collect |> sort |> Tuple + varied_locations = (location for (location, location_dict) in pairs(d) if any(location_dict[""varied""])) |> collect |> sort |> Tuple + return new{length(all_locations),length(required),length(varied_locations)}(all_locations, required, varied_locations) + end + + ProjectLocations() = ProjectLocations(pcmm_globals.inputs_dict) +end + +"""""" + sanitizePathElement(path_elements::String) + +Disallow certain path elements to prevent security issues. +"""""" +function sanitizePathElement(path_element::String) + #! Disallow `..` to prevent directory traversal + if path_element == "".."" + throw(ArgumentError(""Path element '..' is not allowed"")) + end + + #! Disallow absolute paths + if isabspath(path_element) + throw(ArgumentError(""Absolute paths are not allowed"")) + end + + #! Disallow special characters or sequences (e.g., `~`, `*`, etc.) + if contains(path_element, r""[~*?<>|:]"") + throw(ArgumentError(""Path element contains invalid characters"")) + end + return path_element +end + +"""""" + parseProjectInputsConfigurationFile() + +Parse the `inputs.toml` file in the data directory and create a global [`ProjectLocations`](@ref) object. +"""""" +function parseProjectInputsConfigurationFile() + inputs_dict_temp = Dict{String,Any}() + try + inputs_dict_temp = pathToInputsConfig() |> TOML.parsefile + catch e + println(""Error parsing project configuration file: "", e) + return false + end + for (location, location_dict) in pairs(inputs_dict_temp) + @assert haskey(location_dict, ""required"") ""inputs.toml: $(location): required must be defined."" + @assert haskey(location_dict, ""varied"") ""inputs.toml: $(location): varied must be defined."" + if !(""path_from_inputs"" in keys(location_dict)) + location_dict[""path_from_inputs""] = locationFolder(location) + else + location_dict[""path_from_inputs""] = location_dict[""path_from_inputs""] .|> sanitizePathElement |> joinpath + end + if !(""basename"" in keys(location_dict)) + @assert location_dict[""varied""] isa Bool && (!location_dict[""varied""]) ""inputs.toml: $(location): basename must be defined if varied is true."" + location_dict[""basename""] = missing + elseif location_dict[""varied""] isa Vector + @assert location_dict[""basename""] isa Vector && length(location_dict[""varied""]) == length(location_dict[""basename""]) ""inputs.toml: $(location): varied must be a Bool or a Vector of the same length as basename."" + end + end + pcmm_globals.inputs_dict = [Symbol(location) => location_dict for (location, location_dict) in pairs(inputs_dict_temp)] |> Dict{Symbol,Any} + pcmm_globals.project_locations = ProjectLocations() + return true +end + +"""""" + locationIDName(location) + +Return the name of the ID column for the location (as either a String or Symbol). + +# Examples +```jldoctest +julia> PhysiCellModelManager.locationIDName(:config) +""config_id"" +``` +"""""" +locationIDName(location::Union{String,Symbol}) = tableIDName(String(location); strip_s=false) + +"""""" + locationVariationIDName(location) + +Return the name of the variation ID column for the location (as either a String or Symbol). + +# Examples +```jldoctest +julia> PhysiCellModelManager.locationVariationIDName(:config) +""config_variation_id"" +``` +"""""" +locationVariationIDName(location::Union{String,Symbol}) = ""$(location)_variation_id"" + +"""""" + locationIDNames() + +Return the names of the ID columns for all locations. +"""""" +locationIDNames() = (locationIDName(loc) for loc in projectLocations().all) + +"""""" + locationVariationIDNames() + +Return the names of the variation ID columns for all varied locations. +"""""" +locationVariationIDNames() = (locationVariationIDName(loc) for loc in projectLocations().varied) + +"""""" + locationTableName(location) + +Return the name of the table for the location (as either a String or Symbol). +This table stores the folder names and their IDs for the location. + +# Examples +```jldoctest +julia> PhysiCellModelManager.locationTableName(:config) +""configs"" +``` +"""""" +locationTableName(location::Union{String,Symbol}) = ""$(location)s"" + +"""""" + locationFolder(location::Union{String,Symbol}) + +Return the name of the folder for the location (as either a String or Symbol). +This is the folder where the directories with the input files for the location are stored. +"""""" +locationFolder(location::Union{String,Symbol}) = locationTableName(location) + +"""""" + locationVariationsTableName(location) + +Return the name of the variations table for the location (as either a String or Symbol). +This table stores the variations of the folder it is located in. +"""""" +locationVariationsTableName(location::Union{String,Symbol}) = ""$(location)_variations"" + +"""""" + locationVariationsFolder(location) + +Return the name of the variations folder for the location (as either a String or Symbol). +"""""" +locationVariationsFolder(location::Union{String,Symbol}) = locationVariationsTableName(location) + +"""""" + locationVariationsDBName(location::Union{String,Symbol}) + +Return the name of the variations database for the location (as either a String or Symbol). +"""""" +locationVariationsDBName(location::Union{String,Symbol}) = ""$(locationVariationsTableName(location)).db"" + +"""""" + locationPath(location::Symbol, folder=missing) + +Return the path to the location folder in the `inputs` directory. + +If `folder` is not specified, the path to the location folder is returned. +"""""" +function locationPath(location::Symbol, folder=missing) + location_dict = inputsDict()[Symbol(location)] + path_to_locations = joinpath(dataDir(), ""inputs"", location_dict[""path_from_inputs""]) + return ismissing(folder) ? path_to_locations : joinpath(path_to_locations, folder) +end + +"""""" + locationPath(input_folder::InputFolder) + +Return the path to the location folder in the `inputs` directory for the [`InputFolder`](@ref) object. +"""""" +function locationPath(input_folder::InputFolder) + return locationPath(input_folder.location, input_folder.folder) +end + +"""""" + locationPath(location::Symbol, S::AbstractSampling) + +Return the path to the location folder in the `inputs` directory for the [`AbstractSampling`](@ref) object. +"""""" +function locationPath(location::Symbol, S::AbstractSampling) + return locationPath(location, S.inputs[location].folder) +end + +"""""" + folderIsVaried(location::Symbol, folder::String) + +Return `true` if the location folder allows for varying the input files, `false` otherwise. +"""""" +function folderIsVaried(location::Symbol, folder::String) + location_dict = inputsDict()[location] + varieds = location_dict[""varied""] + if !any(varieds) + return false #! if none of the basenames are declared to be varied, then the folder is not varied + end + basenames = location_dict[""basename""] + basenames = basenames isa Vector ? basenames : [basenames] + @assert varieds isa Bool || length(varieds) == length(basenames) ""varied must be a Bool or a Vector of the same length as basename"" + varieds = varieds isa Vector ? varieds : fill(varieds, length(basenames)) + + #! look for the first basename in the folder. if that one is varied, then this is a potential target for varying + path_to_folder = locationPath(location, folder) + for (basename, varied) in zip(basenames, varieds) + path_to_file = joinpath(path_to_folder, basename) + if isfile(path_to_file) + return varied + end + end + throw(ErrorException(""No basename files found in folder $(path_to_folder). Must be one of $(basenames)"")) +end + +"""""" + pathToInputsConfig() + +Return the path to the `inputs.toml` file in the `inputs` directory. +"""""" +pathToInputsConfig() = joinpath(dataDir(), ""inputs"", ""inputs.toml"") + +"""""" + createInputsTOMLTemplate(path_to_toml::String) + +Create a template TOML file for the inputs configuration at the specified path. + +This is something users should not be changing. +It is something in the codebase to hopefully facilitate extending this framework to other ABM frameworks. +"""""" +function createInputsTOMLTemplate(path_to_toml::String) + s = """""" + [config] + required = true + varied = true + basename = ""PhysiCell_settings.xml"" + + [custom_code] + required = true + varied = false + + [rulesets_collection] + required = false + varied = true + basename = [""base_rulesets.csv"", ""base_rulesets.xml""] + + [intracellular] + required = false + varied = true + basename = ""intracellular.xml"" + + [ic_cell] + path_from_inputs = [""ics"", ""cells""] + required = false + varied = [false, true] + basename = [""cells.csv"", ""cells.xml""] + + [ic_substrate] + path_from_inputs = [""ics"", ""substrates""] + required = false + varied = false + basename = ""substrates.csv"" + + [ic_ecm] + path_from_inputs = [""ics"", ""ecms""] + required = false + varied = [false, true] + basename = [""ecm.csv"", ""ecm.xml""] + + [ic_dc] + path_from_inputs = [""ics"", ""dcs""] + required = false + varied = false + basename = ""dcs.csv"" + """""" + open(path_to_toml, ""w"") do f + write(f, s) + end + return +end +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/up.jl",".jl","28795","531","using PhysiCellXMLRules + +const pcmm_milestones = [v""0.0.1"", v""0.0.3"", v""0.0.10"", v""0.0.11"", v""0.0.13"", v""0.0.15"", v""0.0.16"", v""0.0.25"", v""0.0.29"", v""0.0.30"", v""0.1.3"", v""0.2.0""] +const upgrade_fns = Dict{VersionNumber, Function}() + +macro up_fns() + pairs_exprs = Expr[] + for version in pcmm_milestones + fn_name = Symbol(""upgradeToV$(replace(string(version), ""."" => ""_""))"") + push!(pairs_exprs, :( upgrade_fns[$(version)] = $(fn_name) )) + end + quote + $(pairs_exprs...) + end +end + +"""""" + upgradePCMM(from_version::VersionNumber, to_version::VersionNumber, auto_upgrade::Bool) + +Upgrade the PhysiCellModelManager.jl database from one version to another. + +The upgrade process is done in steps, where each step corresponds to a milestone version. +The function will apply all necessary upgrades until the target version is reached. +If `auto_upgrade` is true, the function will automatically apply all upgrades without prompting. +Otherwise, it will prompt the user for confirmation before large upgrades. +"""""" +function upgradePCMM(from_version::VersionNumber, to_version::VersionNumber, auto_upgrade::Bool) + println(""Upgrading PhysiCellModelManager.jl from version $(from_version) to $(to_version)..."") + @assert issorted(pcmm_milestones) ""Milestone versions must be sorted in ascending order. Got $(pcmm_milestones)."" + next_milestone_inds = findall(x -> from_version < x, pcmm_milestones) #! this could be simplified to take advantage of this list being sorted, but who cares? It's already so fast + next_milestones = pcmm_milestones[next_milestone_inds] + success = true + for next_milestone in next_milestones + up_fn = get(upgrade_fns, next_milestone, nothing) + @assert !isnothing(up_fn) ""No upgrade function found for version $(next_milestone)."" + success = up_fn(auto_upgrade) + if !success + break + else + DBInterface.execute(centralDB(), ""UPDATE $(pcmmVersionTableName(next_milestone)) SET version='$(next_milestone)';"") + end + end + if success && to_version > pcmm_milestones[end] + println(""\t- Upgrading to version $(to_version)..."") + DBInterface.execute(centralDB(), ""UPDATE $(pcmmVersionTableName(to_version)) SET version='$(to_version)';"") + end + return success +end + +"""""" + populateTableOnFeatureSubset(db::SQLite.DB, source_table::String, target_table::String; column_mapping::Dict{String, String}=Dict{String,String}()) + +Populate a target table with data from a source table, using a column mapping if provided. +"""""" +function populateTableOnFeatureSubset(db::SQLite.DB, source_table::String, target_table::String; column_mapping::Dict{String,String}=Dict{String,String}()) + @assert tableExists(source_table; db=db) ""Source table $(source_table) does not exist in the database."" + @assert tableExists(target_table; db=db) ""Target table $(target_table) does not exist in the database."" + source_columns = tableColumns(source_table; db=db) + target_columns = [haskey(column_mapping, c) ? column_mapping[c] : c for c in source_columns] + @assert columnsExist(target_columns, target_table; db=db) ""One or more target columns do not exist in the target table."" + insert_into_cols = ""("" * join(target_columns, "","") * "")"" + select_cols = join(source_columns, "","") + query = ""INSERT INTO $(target_table) $(insert_into_cols) SELECT $(select_cols) FROM $(source_table);"" + DBInterface.execute(db, query) +end + +"""""" + pcmmVersionTableName(version::VersionNumber) + +Returns the name of the version table based on the given version number. +Before version 0.0.30, the table name is ""pcvct_version"". Version 0.0.30 and later use ""pcmm_version"". +"""""" +pcmmVersionTableName(version::VersionNumber) = version < v""0.0.30"" ? ""pcvct_version"" : ""pcmm_version"" + +"""""" + upgradeToX_Y_Z(auto_upgrade::Bool) + +Upgrade the database to PhysiCellModelManager.jl version X.Y.Z. Each milestone version has its own upgrade function. +"""""" +function upgradeToVX_Y_Z end + +function continueMilestoneUpgrade(version::VersionNumber, auto_upgrade::Bool) + warning_msg = """""" + \t- Upgrading to version $(version)... + + WARNING: Upgrading to version $(version) will change the database schema. + See info at https://drbergman-lab.github.io/PhysiCellModelManager.jl/stable/misc/database_upgrades/ + + ------IF ANOTHER INSTANCE OF PhysiCellModelManager.jl IS USING THIS DATABASE, PLEASE CLOSE IT BEFORE PROCEEDING.------ + + Continue upgrading to version $(version)? (y/n): + """""" + println(warning_msg) + response = auto_upgrade ? ""y"" : readline() + if response != ""y"" + println(""Upgrade to version $(version) aborted."") + return false + end + println(""\t- Upgrading to version $(version)..."") + return true +end + +function upgradeToV0_0_1(::Bool) + println(""\t- Upgrading to version 0.0.1..."") + data_dir_contents = readdir(joinpath(dataDir(), ""inputs""); sort=false) + if ""rulesets_collections"" in data_dir_contents + rulesets_collection_folders = readdir(locationPath(:rulesets_collection); sort=false) |> filter(x -> isdir(locationPath(:rulesets_collection, x))) + for rulesets_collection_folder in rulesets_collection_folders + path_to_rulesets_collection_folder = locationPath(:rulesets_collection, rulesets_collection_folder) + path_to_rulesets_variations_db = joinpath(path_to_rulesets_collection_folder, ""rulesets_variations.db"") + if !isfile(joinpath(path_to_rulesets_variations_db)) + continue + end + db_rulesets_variations = SQLite.DB(path_to_rulesets_variations_db) + df = DBInterface.execute(db_rulesets_variations, ""INSERT OR IGNORE INTO rulesets_variations (rulesets_collection_variation_id) VALUES(0) RETURNING rulesets_collection_variation_id;"") |> DataFrame + if isempty(df) + continue + end + column_names = tableColumns(""rulesets_variations""; db=db_rulesets_variations) + filter!(x -> x != ""rulesets_collection_variation_id"", column_names) + path_to_xml = joinpath(path_to_rulesets_collection_folder, ""base_rulesets.xml"") + if !isfile(path_to_xml) + writeXMLRules(path_to_xml, joinpath(path_to_rulesets_collection_folder, ""base_rulesets.csv"")) + end + xml_doc = parse_file(path_to_xml) + for column_name in column_names + xml_path = columnNameToXMLPath(column_name) + base_value = getSimpleContent(xml_doc, xml_path) + stmt = SQLite.Stmt(db_rulesets_variations, ""UPDATE rulesets_variations SET '$(column_name)'=(:base_value) WHERE rulesets_collection_variation_id=0;"") + DBInterface.execute(stmt, (base_value,)) + end + free(xml_doc) + end + end + return true +end + +function upgradeToV0_0_3(auto_upgrade::Bool) + if !continueMilestoneUpgrade(v""0.0.3"", auto_upgrade) + return false + end + #! first get vct.db right changing simulations and monads tables + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('simulations') WHERE name='config_variation_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE simulations RENAME COLUMN variation_id TO config_variation_id;"") + end + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('monads') WHERE name='config_variation_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE monads RENAME COLUMN variation_id TO config_variation_id;"") + end + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('simulations') WHERE name='ic_cell_variation_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE simulations ADD COLUMN ic_cell_variation_id INTEGER;"") + DBInterface.execute(centralDB(), ""UPDATE simulations SET ic_cell_variation_id=CASE WHEN ic_cell_id=-1 THEN -1 ELSE 0 END;"") + end + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('monads') WHERE name='ic_cell_variation_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE monads ADD COLUMN ic_cell_variation_id INTEGER;"") + DBInterface.execute(centralDB(), ""CREATE TABLE monads_temp AS SELECT * FROM monads;"") + DBInterface.execute(centralDB(), ""UPDATE monads_temp SET ic_cell_variation_id=CASE WHEN ic_cell_id=-1 THEN -1 ELSE 0 END;"") + DBInterface.execute(centralDB(), ""DROP TABLE monads;"") + createPCMMTable(""monads"", monadsSchema()) + #! drop the previous unique constraint on monads + #! insert from monads_temp all values except ic_cell_variation_id (set that to -1 if ic_cell_id is -1 and to 0 if ic_cell_id is not -1) + populateTableOnFeatureSubset(centralDB(), ""monads_temp"", ""monads"") + DBInterface.execute(centralDB(), ""DROP TABLE monads_temp;"") + end + + #! now get the config_variations.db's right + config_folders = queryToDataFrame(constructSelectQuery(""configs""; selection=""folder_name"")) |> x -> x.folder_name + for config_folder in config_folders + path_to_config_folder = locationPath(:config, config_folder) + if !isfile(joinpath(path_to_config_folder, ""variations.db"")) + continue + end + #! rename all ""variation"" to ""config_variation"" in filenames and in databases + old_db_file = joinpath(path_to_config_folder, ""variations.db"") + db_file = joinpath(path_to_config_folder, ""config_variations.db"") + if isfile(old_db_file) + mv(old_db_file, db_file) + end + db_config_variations = db_file |> SQLite.DB + #! check if variations is a table name in the database + if tableExists(""variations""; db=db_config_variations) + DBInterface.execute(db_config_variations, ""ALTER TABLE variations RENAME TO config_variations;"") + end + if DBInterface.execute(db_config_variations, ""SELECT 1 FROM pragma_table_info('config_variations') WHERE name='config_variation_id';"") |> DataFrame |> isempty + DBInterface.execute(db_config_variations, ""ALTER TABLE config_variations RENAME COLUMN variation_id TO config_variation_id;"") + end + index_df = DBInterface.execute(db_config_variations, ""SELECT type,name,tbl_name,sql FROM sqlite_master WHERE type = 'index';"") |> DataFrame + variations_index = index_df[!, :name] .== ""variations_index"" + if any(variations_index) + variations_sql = index_df[variations_index, :sql][1] + cols = split(variations_sql, ""("")[2] + cols = split(cols, "")"")[1] + cols = split(cols, "","") .|> string .|> x -> strip(x, '""') + SQLite.createindex!(db_config_variations, ""config_variations"", ""config_variations_index"", cols; unique=true, ifnotexists=false) + SQLite.dropindex!(db_config_variations, ""variations_index"") + end + old_folder = joinpath(path_to_config_folder, ""variations"") + new_folder = joinpath(path_to_config_folder, ""config_variations"") + if isdir(old_folder) + mv(old_folder, new_folder) + for file in readdir(new_folder) + mv(joinpath(new_folder, file), joinpath(new_folder, ""config_$(file)"")) + end + end + end + return true +end + +function upgradeToV0_0_10(auto_upgrade::Bool) + if !continueMilestoneUpgrade(v""0.0.10"", auto_upgrade) + return false + end + + createPCMMTable(""physicell_versions"", physicellVersionsSchema()) + pcmm_globals.current_physicell_version_id = resolvePhysiCellVersionID() + + println(""\t\tPhysiCell version: $(physicellInfo())"") + println(""\n\t\tAssuming all output has been generated with this version..."") + + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('simulations') WHERE name='physicell_version_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE simulations ADD COLUMN physicell_version_id INTEGER;"") + DBInterface.execute(centralDB(), ""UPDATE simulations SET physicell_version_id=$(currentPhysiCellVersionID());"") + end + + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('monads') WHERE name='physicell_version_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE monads ADD COLUMN physicell_version_id INTEGER;"") + DBInterface.execute(centralDB(), ""CREATE TABLE monads_temp AS SELECT * FROM monads;"") + DBInterface.execute(centralDB(), ""UPDATE monads_temp SET physicell_version_id=$(currentPhysiCellVersionID());"") + DBInterface.execute(centralDB(), ""DROP TABLE monads;"") + createPCMMTable(""monads"", monadsSchema()) + populateTableOnFeatureSubset(centralDB(), ""monads_temp"", ""monads"") + DBInterface.execute(centralDB(), ""DROP TABLE monads_temp;"") + end + + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('samplings') WHERE name='physicell_version_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE samplings ADD COLUMN physicell_version_id INTEGER;"") + DBInterface.execute(centralDB(), ""UPDATE samplings SET physicell_version_id=$(currentPhysiCellVersionID());"") + end + return true +end + +function upgradeToV0_0_11(::Bool) + println(""\t- Upgrading to version 0.0.11..."") + query = constructSelectQuery(""samplings"") + samplings_df = queryToDataFrame(query) + for row in eachrow(samplings_df) + if !ismissing(row.physicell_version_id) + continue + end + monads = monadIDs(Sampling(row.sampling_id)) + query = constructSelectQuery(""monads"", ""WHERE monad_id IN ($(join(monads, "","")))""; selection=""physicell_version_id"") + monads_df = queryToDataFrame(query) + monad_physicell_versions = monads_df.physicell_version_id |> unique + if length(monad_physicell_versions) == 1 + DBInterface.execute(centralDB(), ""UPDATE samplings SET physicell_version_id=$(monad_physicell_versions[1]) WHERE sampling_id=$(row.sampling_id);"") + else + println(""WARNING: Multiple PhysiCell versions found for monads in sampling $(row.sampling_id). Not setting the sampling PhysiCell version."") + end + end +end + +function upgradeToV0_0_13(::Bool) + println(""\t- Upgrading to version 0.0.13..."") + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('simulations') WHERE name='rulesets_variation_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE simulations RENAME COLUMN rulesets_variation_id TO rulesets_collection_variation_id;"") + end + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('monads') WHERE name='rulesets_variation_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE monads RENAME COLUMN rulesets_variation_id TO rulesets_collection_variation_id;"") + end + rulesets_collection_folders = queryToDataFrame(constructSelectQuery(""rulesets_collections""; selection=""folder_name"")) |> x -> x.folder_name + for rulesets_collection_folder in rulesets_collection_folders + path_to_rulesets_collection_folder = locationPath(:rulesets_collection, rulesets_collection_folder) + path_to_new_db = joinpath(path_to_rulesets_collection_folder, ""rulesets_collection_variations.db"") + if isfile(path_to_new_db) + continue + end + path_to_old_db = joinpath(path_to_rulesets_collection_folder, ""rulesets_variations.db"") + if !isfile(path_to_old_db) + error(""Could not find a rulesets collection variation database file in $(path_to_rulesets_collection_folder)."") + end + mv(path_to_old_db, path_to_new_db) + db_rulesets_collection_variations = SQLite.DB(path_to_new_db) + if tableExists(""rulesets_variations""; db=db_rulesets_collection_variations) + DBInterface.execute(db_rulesets_collection_variations, ""ALTER TABLE rulesets_variations RENAME TO rulesets_collection_variations;"") + end + if !(DBInterface.execute(db_rulesets_collection_variations, ""SELECT 1 FROM pragma_table_info('rulesets_collection_variations') WHERE name='rulesets_variation_id';"") |> DataFrame |> isempty) + DBInterface.execute(db_rulesets_collection_variations, ""ALTER TABLE rulesets_collection_variations RENAME COLUMN rulesets_variation_id TO rulesets_collection_variation_id;"") + end + end +end + +function upgradeToV0_0_15(auto_upgrade::Bool) + if !continueMilestoneUpgrade(v""0.0.15"", auto_upgrade) + return false + end + + #! first include ic_ecm_variation_id in simulations and monads tables + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('simulations') WHERE name='ic_ecm_variation_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE simulations ADD COLUMN ic_ecm_variation_id INTEGER;"") + DBInterface.execute(centralDB(), ""UPDATE simulations SET ic_ecm_variation_id=CASE WHEN ic_ecm_id=-1 THEN -1 ELSE 0 END;"") + end + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('monads') WHERE name='ic_ecm_variation_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE monads ADD COLUMN ic_ecm_variation_id INTEGER;"") + DBInterface.execute(centralDB(), ""CREATE TABLE monads_temp AS SELECT * FROM monads;"") + DBInterface.execute(centralDB(), ""UPDATE monads_temp SET ic_ecm_variation_id=CASE WHEN ic_ecm_id=-1 THEN -1 ELSE 0 END;"") + DBInterface.execute(centralDB(), ""DROP TABLE monads;"") + createPCMMTable(""monads"", monadsSchema()) + populateTableOnFeatureSubset(centralDB(), ""monads_temp"", ""monads"") + DBInterface.execute(centralDB(), ""DROP TABLE monads_temp;"") + end + + #! now add ic_dc_id to simulations and monads tables + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('simulations') WHERE name='ic_dc_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE simulations ADD COLUMN ic_dc_id INTEGER;"") + DBInterface.execute(centralDB(), ""UPDATE simulations SET ic_dc_id=-1;"") + end + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('monads') WHERE name='ic_dc_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE monads ADD COLUMN ic_dc_id INTEGER;"") + DBInterface.execute(centralDB(), ""CREATE TABLE monads_temp AS SELECT * FROM monads;"") + DBInterface.execute(centralDB(), ""UPDATE monads_temp SET ic_dc_id=-1;"") + DBInterface.execute(centralDB(), ""DROP TABLE monads;"") + createPCMMTable(""monads"", monadsSchema()) + populateTableOnFeatureSubset(centralDB(), ""monads_temp"", ""monads"") + DBInterface.execute(centralDB(), ""DROP TABLE monads_temp;"") + end + return true +end + +function upgradeToV0_0_16(auto_upgrade::Bool) + if !continueMilestoneUpgrade(v""0.0.16"", auto_upgrade) + return false + end + + #! add intracellular_id and intracellular_variation_id to simulations and monads tables + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('simulations') WHERE name='intracellular_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE simulations ADD COLUMN intracellular_id INTEGER;"") + DBInterface.execute(centralDB(), ""UPDATE simulations SET intracellular_id=-1;"") + DBInterface.execute(centralDB(), ""ALTER TABLE simulations ADD COLUMN intracellular_variation_id INTEGER;"") + DBInterface.execute(centralDB(), ""UPDATE simulations SET intracellular_variation_id=-1;"") + end + if DBInterface.execute(centralDB(), ""SELECT 1 FROM pragma_table_info('monads') WHERE name='intracellular_id';"") |> DataFrame |> isempty + DBInterface.execute(centralDB(), ""ALTER TABLE monads ADD COLUMN intracellular_id INTEGER;"") + DBInterface.execute(centralDB(), ""UPDATE monads SET intracellular_id=-1;"") + DBInterface.execute(centralDB(), ""ALTER TABLE monads ADD COLUMN intracellular_variation_id INTEGER;"") + DBInterface.execute(centralDB(), ""UPDATE monads SET intracellular_variation_id=-1;"") + DBInterface.execute(centralDB(), ""CREATE TABLE monads_temp AS SELECT * FROM monads;"") + DBInterface.execute(centralDB(), ""UPDATE monads_temp SET intracellular_id=-1;"") + DBInterface.execute(centralDB(), ""UPDATE monads_temp SET intracellular_variation_id=-1;"") + DBInterface.execute(centralDB(), ""DROP TABLE monads;"") + createPCMMTable(""monads"", monadsSchema()) + populateTableOnFeatureSubset(centralDB(), ""monads_temp"", ""monads"") + DBInterface.execute(centralDB(), ""DROP TABLE monads_temp;"") + end + return true +end + +function upgradeToV0_0_25(::Bool) + println(""\t- Upgrading to version 0.0.25..."") + + #! v0.0.23 accidentally used the capitalized version of these CSV file names + monads_folder = joinpath(dataDir(), ""outputs"", ""monads"") + if isdir(monads_folder) + folders = readdir(monads_folder; sort=false) |> filter(x -> isdir(joinpath(monads_folder, x))) + for folder in folders + if isfile(joinpath(monads_folder, folder, ""Simulations.csv"")) + temp_dst = joinpath(monads_folder, folder, ""__temp_simulations__.csv"") + mv(joinpath(monads_folder, folder, ""Simulations.csv""), temp_dst) + dst = joinpath(monads_folder, folder, ""simulations.csv"") + mv(temp_dst, dst) + end + end + end + + samplings_folder = joinpath(dataDir(), ""outputs"", ""samplings"") + if isdir(samplings_folder) + folders = readdir(samplings_folder; sort=false) |> filter(x -> isdir(joinpath(samplings_folder, x))) + for folder in folders + if isfile(joinpath(samplings_folder, folder, ""Monads.csv"")) + temp_dst = joinpath(samplings_folder, folder, ""__temp_monads__.csv"") + mv(joinpath(samplings_folder, folder, ""Monads.csv""), temp_dst) + dst = joinpath(samplings_folder, folder, ""monads.csv"") + mv(temp_dst, dst) + end + end + end + + trials_folder = joinpath(dataDir(), ""outputs"", ""trials"") + if isdir(trials_folder) + folders = readdir(trials_folder; sort=false) |> filter(x -> isdir(joinpath(trials_folder, x))) + for folder in folders + if isfile(joinpath(trials_folder, folder, ""Samplings.csv"")) + temp_dst = joinpath(trials_folder, folder, ""__temp_samplings__.csv"") + mv(joinpath(trials_folder, folder, ""Samplings.csv""), temp_dst) + dst = joinpath(trials_folder, folder, ""samplings.csv"") + mv(temp_dst, dst) + end + end + end + return true +end + +function upgradeToV0_0_29(auto_upgrade::Bool) + if !continueMilestoneUpgrade(v""0.0.29"", auto_upgrade) + return false + end + + old_file_path = joinpath(dataDir(), ""inputs.toml"") + new_file_path = pathToInputsConfig() + @assert isfile(old_file_path) ""The inputs.toml file is missing. Please create it before upgrading to version 0.0.29."" + @assert isdir(joinpath(dataDir(), ""inputs"")) ""The inputs directory is missing. Please create it before upgrading to version 0.0.29."" + if isfile(new_file_path) + println(""The inputs.toml file is already in the inputs directory. No need to move it."") + else + mv(old_file_path, new_file_path) + end + return true +end + +function upgradeToV0_0_30(auto_upgrade::Bool) + if !continueMilestoneUpgrade(v""0.0.30"", auto_upgrade) + return false + end + + if tableExists(""pcvct_version"") + DBInterface.execute(centralDB(), ""ALTER TABLE pcvct_version RENAME TO pcmm_version;"") + else + println(""While upgrading to version 0.0.30, the pcvct_version table was not found. This is unexpected."") + return false + end + return true +end + +function upgradeToV0_1_3(auto_upgrade::Bool) + if !continueMilestoneUpgrade(v""0.1.3"", auto_upgrade) + return false + end + + old_path = joinpath(dataDir(), ""vct.db"") + new_path = joinpath(dataDir(), ""pcmm.db"") + if isfile(old_path) + close(centralDB()) + mv(old_path, new_path) + pcmm_globals.db = SQLite.DB(new_path) + else + println(""While upgrading to version 0.1.3, the vct.db file was not found. This is unexpected."") + return false + end + return true +end + +function upgradeToV0_2_0(auto_upgrade::Bool) + if !continueMilestoneUpgrade(v""0.2.0"", auto_upgrade) + return false + end + + parseProjectInputsConfigurationFile() + for location in projectLocations().varied + location_folders = queryToDataFrame(constructSelectQuery(locationTableName(location); selection=""folder_name"")) |> x -> x.folder_name + location_variation_id_name = locationVariationIDName(location) + for location_folder in location_folders + path_to_db = joinpath(locationPath(location, location_folder), locationVariationsDBName(location)) + if !isfile(path_to_db) + continue + end + db = SQLite.DB(path_to_db) + table_name = locationVariationsTableName(location) + df = queryToDataFrame(constructSelectQuery(table_name); db=db) + if ""par_key"" in names(df) + continue + end + ids = df[!, location_variation_id_name] + select!(df, Not(location_variation_id_name)) + @assert !(:par_key in names(df)) ""Column par_key already found in table $(table_name) in database at $(path_to_db). It seems the upgrade has already been applied."" + par_names = ""'"" .* names(df) .* ""'"" + sqlite_types = sqliteDataType.(eltype.(eachcol(df))) + col_inserts = par_names .* "" "" .* sqlite_types + + SQLite.transaction(db) + try + DBInterface.execute(db, ""ALTER TABLE $(table_name) RENAME TO $(table_name)_old;"") + schema = ""$location_variation_id_name INTEGER PRIMARY KEY, par_key BLOB UNIQUE"" + if !isempty(col_inserts) + schema *= "","" * join(col_inserts, ',') + end + createPCMMTable(table_name, schema; db=db) + + stmt_str = ""INSERT INTO $(table_name) ($(location_variation_id_name), par_key"" + if !isempty(par_names) + stmt_str *= "", $(join(par_names, ','))"" + end + stmt_str *= "") VALUES ($(join([""?"" for _ in 1:(length(par_names)+2)], "","")));"" + stmt = SQLite.Stmt(db, stmt_str) + + for (row_id, row) in zip(ids, eachrow(df)) + original_vals = [row...] + vals = copy(original_vals) + vals[vals.==""true""] .= 1.0 + vals[vals.==""false""] .= 0.0 + is_string = [v isa String for v in vals] + vals[is_string] .= tryparse.(Float64, vals[is_string]) + @assert all(!isnothing, vals[is_string]) ""All parameter values must be parseable as Float64 to create the binary representation. Found non-parseable values: $(original_vals[is_string .& isnothing.(vals)])."" + @assert all(v -> v ∈ (0.0, 1.0) , vals[is_string]) ""All parameter values that were strings must be 'true' or 'false' to create the binary representation. Found: $(original_vals[is_string .& .!([v ∈ (0.0, 1.0) for v in vals])])."" + original_vals[is_string] .= [v == 0.0 ? ""false"" : ""true"" for v in vals[is_string]] #! fix original vals to be the correct strings + @assert all(x -> x isa Real, vals) ""All parameter values must be Real to create the binary representation. Found: $(typeof.(vals))."" + par_key = reinterpret(UInt8, Vector{Float64}(vals)) + params = [row_id, par_key, original_vals...] + DBInterface.execute(stmt, params) + end + DBInterface.execute(db, ""DROP TABLE $(table_name)_old;"") + validateParsBytes(db, table_name) + catch e + SQLite.rollback(db) + @info """""" + Error during upgrade of database at $(path_to_db): $(e). Not committing changes to any databases. + Please report this issue at https://github.com/drbergman-lab/PhysiCellModelManager.jl/issues + For now, revert back to the previous PCMM version v0.1.7: + + pkg> rm PhysiCellModelManager + pkg> add PhysiCellModelManager@v0.1.7 + """""" + return false + else + SQLite.commit(db) + index_name = ""$(table_name)_index"" + SQLite.dropindex!(db, index_name; ifexists=true) #! remove previous index + end + end + end + return true +end + +@up_fns","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/globals.jl",".jl","5579","122","using Parameters, SQLite + +"""""" + PCMMGlobals + +A mutable struct to hold global variables for the PhysiCellModelManager.jl package. +The global variable `pcmm_globals` is the instance of this struct that is used throughout the package. + +# Fields +- `initialized::Bool`: Indicates whether the project database has been initialized. +- `data_dir::String`: The path to the data directory. This is set when the model manager is initialized. +- `physicell_dir::String`: The path to the PhysiCell directory. This is set when the model manager is initialized. +- `inputs_dict::Dict{Symbol,Any}`: A dictionary that maps the types of inputs to the data that defines how they are set up and what they can do. Read in from the `inputs.toml` file in the `data` directory. +- `project_locations::ProjectLocations`: The global [`ProjectLocations`](@ref) object that contains information about the locations of input files in the project. +- `db::SQLite.DB`: The database connection object to the central SQLite database for the open project. Set this with [`initializeModelManager`](@ref). +- `strict_physicell_check::Bool`: Indicates whether to perform strict checks on the PhysiCell directory for reproducibility. If true, requires a clean git folder (in particular, not downloaded) to skip recompile. +- `current_physicell_version_id::Int`: The ID of the current version of PhysiCell being used as defined in the database. This is set when the model manager is initialized. +- `physicell_compiler::String`: The compiler used to compile the PhysiCell code. This is set when the model manager is initialized. +- `march_flag::String`: The march flag to be used when compiling the code. If running on an HPC, this is set to ""x86-64"" which will work across different CPU manufacturers that may be present on an HPC. Otherwise, set to ""native"". +- `run_on_hpc::Bool`: A boolean that indicates whether the code is running on an HPC environment. This is set to true if the `sbatch` command is available when compiling PhysiCellModelManager.jl. +- `sbatch_options::Dict{String,Any}`: A dictionary that will be used to pass options to the sbatch command. The keys are the flag names and the values are the values used for the flag. This is initialized using [`defaultJobOptions`](@ref) and can be modified using [`setJobOptions`](@ref). +- `max_number_of_parallel_simulations::Int`: The maximum number of parallel simulations that can be run at once. If running on an HPC, this is ignored and instead PhysiCellModelManager.jl will queue one job per simulation. +- `path_to_python::Union{Missing,String}`: The path to the python executable for running PhysiCell Studio. See [`runStudio`](@ref). +- `path_to_studio::Union{Missing,String}`: The path to the PhysiCell Studio directory. See [`runStudio`](@ref). +- `path_to_magick::Union{Missing,String}`: The path to the ImageMagick installation. See [`makeMovie`](@ref). +- `path_to_ffmpeg::Union{Missing,String}`: The path to the FFmpeg installation. See [`makeMovie`](@ref). +"""""" +@with_kw mutable struct PCMMGlobals + initialized::Bool = false + + data_dir::String = """" + physicell_dir::String = """" + + inputs_dict::Dict{Symbol,Any} = Dict{Symbol,Any}() + project_locations::ProjectLocations = ProjectLocations(inputs_dict) + + db::SQLite.DB = SQLite.DB() + + strict_physicell_check::Bool = true + current_physicell_version_id::Int = -1 + physicell_compiler::String = ""g++"" + + run_on_hpc::Bool = isRunningOnHPC() + sbatch_options::Dict{String,Any} = defaultJobOptions() + + march_flag::String = run_on_hpc ? ""x86-64"" : ""native"" + + max_number_of_parallel_simulations::Int = 1 + + path_to_python::Union{Missing,String} = missing + path_to_studio::Union{Missing,String} = missing + path_to_magick::Union{Missing,String} = missing + path_to_ffmpeg::Union{Missing,String} = missing +end + +const pcmm_globals = PCMMGlobals() + +"""""" + findCentralDB() + +Find the central database for the PhysiCellModelManager.jl package and update the global `pcmm_globals.db` variable. +This function checks for the existence of the old `vct.db` file and uses it if it exists, otherwise it uses the new `pcmm.db` file. +"""""" +function findCentralDB() + global pcmm_globals + path_to_db(f) = joinpath(dataDir(), f) + old_db_path = path_to_db(""vct.db"") + path_to_central_db = isfile(old_db_path) ? old_db_path : path_to_db(""pcmm.db"") + pcmm_globals.db = SQLite.DB(path_to_central_db) +end + +"""""" + dataDir() + +Get the data directory global variable for the current project. +"""""" +dataDir() = pcmm_globals.data_dir + +"""""" + physicellDir() + +Get the PhysiCell directory global variable for the current project. +"""""" +physicellDir() = pcmm_globals.physicell_dir + +"""""" + inputsDict() + +Get the inputs dictionary global variable for the current project. +"""""" +inputsDict() = pcmm_globals.inputs_dict + +"""""" + projectLocations() + +Get the project locations global variable for the current project. +"""""" +projectLocations() = pcmm_globals.project_locations + +"""""" + centralDB() + +Get the database global variable for the current project. +"""""" +centralDB() = pcmm_globals.db + +"""""" + isInitialized() + +Check if the model manager has been initialized for a project. +"""""" +isInitialized() = pcmm_globals.initialized + +"""""" + assertInitialized() + +Assert that the model manager has been initialized for a project. +If not, throw an error with a message indicating that the user should run [`initializeModelManager`](@ref) first. +"""""" +function assertInitialized() + @assert isInitialized() ""The model manager has not been initialized for a project. Please run `initializeModelManager` first."" +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/import.jl",".jl","22182","538","using LightXML + +export importProject + +include(""import_classes.jl"") + +"""""" + importProject(path_to_project::AbstractString[; src=Dict(), dest=Dict()]) + +Import a project from the structured in the format of PhysiCell sample projects and user projects into the PhysiCellModelManager.jl structure. + +This function will create new directories every time it is called, even if the project was already imported. +Copy the console output to your scripts to prepare inputs for running the imported project rather than repeatedly running this function. + +# Arguments +- `path_to_project::AbstractString`: Path to the project to import. Relative paths are resolved from the current working directory where Julia was launched. + +# Keyword Arguments +- `src::Dict`: Dictionary of the project sources to import. If absent, tries to use the default names. +The following keys are recognized: $(join([""`\""$fn\""`"" for fn in fieldnames(ImportSources)], "", "", "", and "")). +- `dest::Dict`: Dictionary of the inputs folders to create in the PhysiCellModelManager.jl structure. If absent, taken from the project name. +Any valid project location can be used as a key. For example, `""config""`, `""custom_code""`, `""ic_cell""`, etc. +- `dest::AbstractString`: If a single string is provided, it is used as the name of the folder to create in the `inputs` folder for all locations. + +For both `src` and `dest` (as `Dict`), the key `\""rules\""` is an alias for `\""rulesets_collection\""`. + +# Returns +An `InputFolders` instance with the paths to the imported project files. +This can immediately be used to run simulations. +However, do not use this function in a script as it will repeatedly create new folders each call. + +# Deprecated method +The following method is deprecated and will be removed in the future. +Note that the arguments are optional, positional arguments, not keyword arguments. +```julia +importProject(path_to_project::AbstractString, src::Dict, dest::Dict) +``` +"""""" +function importProject(path_to_project::AbstractString; src=Dict(), dest=Dict()) + assertInitialized() + project_sources = ImportSources(src, path_to_project) + import_dest_folders = ImportDestFolders(path_to_project, dest) + success = resolveProjectSources!(project_sources, path_to_project) + if success + success = createInputFolders!(import_dest_folders, project_sources) + success = success && copyFilesToFolders(path_to_project, project_sources, import_dest_folders) #! only copy if successful so far + success = success && adaptProject(import_dest_folders) + end + if success + return processSuccessfulImport(path_to_project, import_dest_folders) + else + msg = """""" + Failed to import user_project from $(path_to_project) into $(joinpath(dataDir(), ""inputs"")). + See the error messages above for more information. + Cleaning up what was created in $(joinpath(dataDir(), ""inputs"")). + """""" + println(msg) + path_to_inputs = joinpath(dataDir(), ""inputs"") + for loc in projectLocations().all + import_dest_folder = import_dest_folders[loc] + if import_dest_folder.created + path_to_folder = joinpath(path_to_inputs, import_dest_folder.path_from_inputs) + rm(path_to_folder; force=true, recursive=true) + end + end + return + end +end + +function importProject(path_to_project::AbstractString, src, dest=Dict()) + Base.depwarn(""`importProject` with more than one positional argument is deprecated. Use the method `importProject(path_to_project; src=Dict(), dest=Dict())` instead."", :importProject; force=true) + return importProject(path_to_project; src=src, dest=dest) +end + +"""""" + prepareRulesetsCollectionImport(src::Dict, path_to_project::AbstractString) + +Prepare the rulesets collection import source. +"""""" +function prepareRulesetsCollectionImport(src::Dict, path_to_project::AbstractString) + rules_ext = "".csv"" #! default to csv + required = true #! default to requiring rules (just for fewer lines below) + if haskey(src, ""rulesets_collection"") + rules_ext = splitext(src[""rulesets_collection""])[2] + elseif isfile(joinpath(path_to_project, ""config"", ""cell_rules.csv"")) + rules_ext = "".csv"" + elseif isfile(joinpath(path_to_project, ""config"", ""cell_rules.xml"")) + rules_ext = "".xml"" + else + required = false + end + return ImportSource(src, ""rulesets_collection"", ""config"", ""cell_rules$(rules_ext)"", ""file"", required; pcmm_name=""base_rulesets$(rules_ext)"") +end + +"""""" + prepareIntracellularImport(src::Dict, config::ImportSource, path_to_project::AbstractString) + +Prepare the intracellular import source. +"""""" +function prepareIntracellularImport(src::Dict, config::ImportSource, path_to_project::AbstractString) + if haskey(src, ""intracellular"") || isfile(joinpath(path_to_project, ""config"", ""intracellular.xml"")) + return ImportSource(src, ""intracellular"", ""config"", ""intracellular.xml"", ""file"", true) + end + #! now attempt to read the config file and assemble the intracellular file + path_to_xml = joinpath(path_to_project, config.path_from_project) + if !isfile(path_to_xml) #! if the config file is not found, then we cannot proceed with grabbing the intracellular data, just return the default + return ImportSource(src, ""intracellular"", ""config"", ""intracellular.xml"", ""file"", false) + end + xml_doc = parse_file(path_to_xml) + cell_definitions_element = retrieveElement(xml_doc, [""cell_definitions""]) + cell_type_to_components_dict = Dict{String,PhysiCellComponent}() + for cell_definition_element in child_elements(cell_definitions_element) + @assert name(cell_definition_element) == ""cell_definition"" ""The child elements of should all be elements."" + cell_type = attribute(cell_definition_element, ""name"") + phenotype_element = find_element(cell_definition_element, ""phenotype"") + intracellular_element = find_element(phenotype_element, ""intracellular"") + if isnothing(intracellular_element) + continue + end + type = attribute(intracellular_element, ""type"") + @assert type ∈ [""roadrunner""] ""PhysiCellModelManager.jl does not yet support intracellular type $type. It only supports roadrunner."" + path_to_file = find_element(intracellular_element, ""sbml_filename"") |> content + temp_component = PhysiCellComponent(type, basename(path_to_file)) + #! now we have to rely on the path to the file is correct relative to the parent directory of the config file (that should usually be the case) + path_to_src = joinpath(path_to_project, path_to_file) + path_to_dest = createComponentDestFilename(path_to_src, temp_component) + component = PhysiCellComponent(type, basename(path_to_dest)) + if !isfile(path_to_dest) + cp(path_to_src, path_to_dest) + end + + cell_type_to_components_dict[cell_type] = component + end + + if isempty(cell_type_to_components_dict) + return ImportSource(src, ""intracellular"", ""config"", ""intracellular.xml"", ""file"", false) + end + + intracellular_folder = assembleIntracellular!(cell_type_to_components_dict; name=""temp_assembled_from_$(splitpath(path_to_project)[end])"", skip_db_insert=true) + mv(joinpath(locationPath(:intracellular, intracellular_folder), ""intracellular.xml""), joinpath(path_to_project, ""config"", ""assembled_intracellular_for_import.xml""); force=true) + rm(locationPath(:intracellular, intracellular_folder); force=true, recursive=true) + + free(xml_doc) + return ImportSource(src, ""intracellular"", ""config"", ""assembled_intracellular_for_import.xml"", ""file"", true; pcmm_name=""intracellular.xml"", copy_or_move=_move_) +end + +"""""" + createComponentDestFilename(src_lines::Vector{String}, component::PhysiCellComponent) + +Create a file name for the component file to be copied to. +If a file exists with the same name and content, it will not be copied again. +If a file exists with the same name but different content, a new file name will be created by appending a number to the base name. +"""""" +function createComponentDestFilename(path_to_file::String, component::PhysiCellComponent) + src_lines = readlines(path_to_file) + base_path = joinpath(dataDir(), ""components"", pathFromComponents(component)) + folder = dirname(base_path) + mkpath(folder) + base_filename, file_ext = basename(base_path) |> splitext + n = 0 + path_to_dest = joinpath(folder, base_filename * file_ext) + while isfile(path_to_dest) + if src_lines == readlines(path_to_dest) + return path_to_dest + end + n += 1 + path_to_dest = joinpath(folder, base_filename * ""_$(n)"" * file_ext) + end + return path_to_dest +end + +"""""" + resolveProjectSources!(project_sources::ImportSources, path_to_project::AbstractString) + +Resolve the project sources by checking if they exist in the project directory. +"""""" +function resolveProjectSources!(project_sources::ImportSources, path_to_project::AbstractString) + success = true + for fieldname in fieldnames(ImportSources) + project_source = getfield(project_sources, fieldname)::ImportSource + success &= resolveProjectSource!(project_source, path_to_project) + end + return success +end + +"""""" + resolveProjectSource!(project_source::ImportSource, path_to_project::AbstractString) + +Resolve the project source by checking if it exists in the project directory. +"""""" +function resolveProjectSource!(project_source::ImportSource, path_to_project::AbstractString) + exist_fn = project_source.type == ""file"" ? isfile : isdir + project_source.found = exist_fn(joinpath(path_to_project, project_source.path_from_project)) + if project_source.found || !project_source.required + return true + end + + msg = """""" + Source $(project_source.type) $(project_source.path_from_project) does not exist in $(path_to_project). + Update the src dictionary to include the correct $(project_source.type) name. + For example: `src=Dict(""$(project_source.src_key)""=>""$(splitpath(project_source.path_from_project)[end])"")`. + Aborting import. + """""" + println(msg) + return false +end + +"""""" + createInputFolders!(import_dest_folders::ImportDestFolders, project_sources::ImportSources) + +Create input folders based on the provided project sources and destination folders. +"""""" +function createInputFolders!(import_dest_folders::ImportDestFolders, project_sources::ImportSources) + success = true + for loc in projectLocations().all + import_dest_folder = import_dest_folders[loc] + if loc in projectLocations().required || getfield(project_sources, loc).found + success &= createInputFolder!(import_dest_folder) + end + end + return success +end + +"""""" + createInputFolder!(import_dest_folder::ImportDestFolder) + +Create an input folder based on the provided destination folder. +"""""" +function createInputFolder!(import_dest_folder::ImportDestFolder) + path_to_inputs = joinpath(dataDir(), ""inputs"") + path_from_inputs_vec = splitpath(import_dest_folder.path_from_inputs) + path_from_inputs_to_collection = joinpath(path_from_inputs_vec[1:end-1]...) + folder_base = path_from_inputs_vec[end] + folder_name = folder_base + path_base = joinpath(path_to_inputs, path_from_inputs_to_collection) + n = 0 + while isdir(joinpath(path_base, folder_name)) + n += 1 + folder_name = ""$(folder_base)_$(n)"" + end + import_dest_folder.path_from_inputs = joinpath(path_from_inputs_to_collection, folder_name) + path_to_folder = joinpath(path_to_inputs, import_dest_folder.path_from_inputs) + mkpath(path_to_folder) + path_to_metadata = joinpath(path_to_folder, ""metadata.xml"") + writeDescriptionToMetadata(path_to_metadata, import_dest_folder.description) + import_dest_folder.created = true + return true +end + +"""""" + writeDescriptionToMetadata(path_to_metadata::AbstractString, description::AbstractString) + +Write the description to the metadata file. +"""""" +function writeDescriptionToMetadata(path_to_metadata::AbstractString, description::AbstractString) + xml_doc = XMLDocument() + xml_root = create_root(xml_doc, ""metadata"") + description_element = new_child(xml_root, ""description"") + set_content(description_element, description) + save_file(xml_doc, path_to_metadata) + free(xml_doc) + return +end + +"""""" + copyFilesToFolders(path_to_project::AbstractString, project_sources::ImportSources, import_dest_folders::ImportDestFolders) + +Copy files from the project directory to the destination folders in the PhysiCellModelManager.jl structure. +"""""" +function copyFilesToFolders(path_to_project::AbstractString, project_sources::ImportSources, import_dest_folders::ImportDestFolders) + success = true + for fieldname in fieldnames(ImportSources) + project_source = getfield(project_sources, fieldname)::ImportSource + if !project_source.found + continue + end + src = joinpath(path_to_project, project_source.path_from_project) + import_dest_folder = import_dest_folders[project_source.input_folder_key] + dest = joinpath(dataDir(), ""inputs"", import_dest_folder.path_from_inputs, project_source.pcmm_name) + @assert (dest |> (project_source.type == ""file"" ? isfile : isdir)) == false ""In copying $(src) to $(dest), found a $(project_source.type) with the same name. This should be avoided by PhysiCellModelManager. Please open an Issue on GitHub and document your setup and steps."" + project_source.copy_or_move == _copy_ ? cp(src, dest) : mv(src, dest) + end + return success +end + +"""""" + adaptProject(import_dest_folders::ImportDestFolders) + +Adapt the project to be used in the PhysiCellModelManager.jl structure. +"""""" +function adaptProject(import_dest_folders::ImportDestFolders) + success = adaptConfig(import_dest_folders[:config]) + success &= adaptCustomCode(import_dest_folders[:custom_code]) + return success +end + +"""""" + adaptConfig(config::ImportDestFolder) + +Adapt the config file to be used in the PhysiCellModelManager.jl structure. +"""""" +function adaptConfig(::ImportDestFolder) + return true #! nothing to do for now +end + +"""""" + adaptCustomCode(custom_code::ImportDestFolder) + +Adapt the custom code to be used in the PhysiCellModelManager.jl structure. +"""""" +function adaptCustomCode(custom_code::ImportDestFolder) + success = adaptMain(custom_code.path_from_inputs) + success &= adaptMakefile(custom_code.path_from_inputs) + success &= adaptCustomModules(joinpath(custom_code.path_from_inputs, ""custom_modules"")) + return success +end + +"""""" + adaptMain(path_from_inputs::AbstractString) + +Adapt the main.cpp file to be used in the PhysiCellModelManager.jl structure. +"""""" +function adaptMain(path_from_inputs::AbstractString) + path_to_main = joinpath(dataDir(), ""inputs"", path_from_inputs, ""main.cpp"") + lines = readlines(path_to_main) + + filter!(!contains(""copy_command""), lines) #! remove any lines carrying out the copy command, which could be a little risky if the user uses for something other than copying over the config file + + if any(contains(""argument_parser.parse""), lines) + #! already adapted the main.cpp + return true + end + + idx1 = findfirst(contains(""// load and parse settings file(s)""), lines) + if isnothing(idx1) + idx1 = findfirst(contains(""bool XML_status = false;""), lines) + if isnothing(idx1) + msg = """""" + Could not find the line to insert the settings file parsing code. + Also, could not find an argument_parser line. + Aborting the import process. + """""" + println(msg) + return false + end + end + idx_not_xml_status = findfirst(contains(""!XML_status""), lines) + idx2 = idx_not_xml_status + findfirst(contains(""}""), lines[idx_not_xml_status:end]) - 1 + + deleteat!(lines, idx1:idx2) + + parsing_block = """""" + // read arguments + argument_parser.parse(argc, argv); + + // load and parse settings file(s) + load_PhysiCell_config_file(); + """""" + insert!(lines, idx1, parsing_block) + + open(path_to_main, ""w"") do f + for line in lines + println(f, line) + end + end + return true +end + +"""""" + adaptMakefile(path_from_inputs::AbstractString) + +Adapt the Makefile to be used in the PhysiCellModelManager.jl structure. +"""""" +function adaptMakefile(path_from_inputs::AbstractString) + path_to_makefile = joinpath(dataDir(), ""inputs"", path_from_inputs, ""Makefile"") + file_str = read(path_to_makefile, String) + file_str = replace(file_str, ""PhysiCell_rules."" => ""PhysiCell_rules_extended."") + open(path_to_makefile, ""w"") do io + write(io, file_str) + end + return true #! nothing to do for now +end + +"""""" + adaptCustomModules(path_from_inputs::AbstractString) + +Adapt the custom modules to be used in the PhysiCellModelManager.jl structure. +"""""" +function adaptCustomModules(path_from_inputs::AbstractString) + success = adaptCustomHeader(path_from_inputs) + success &= adaptCustomCPP(path_from_inputs) + return success +end + +"""""" + adaptCustomHeader(path_from_inputs::AbstractString) + +Adapt the custom header to be used in the PhysiCellModelManager.jl structure. +"""""" +function adaptCustomHeader(::AbstractString) + return true #! nothing to do for now +end + +"""""" + adaptCustomCPP(path_from_inputs::AbstractString) + +Adapt the custom cpp file to be used in the PhysiCellModelManager.jl structure. +"""""" +function adaptCustomCPP(path_from_inputs::AbstractString) + path_to_custom_cpp = joinpath(dataDir(), ""inputs"", path_from_inputs, ""custom.cpp"") + lines = readlines(path_to_custom_cpp) + idx = findfirst(contains(""load_cells_from_pugixml""), lines) + + if isnothing(idx) + if !any(contains(""load_initial_cells""), lines) + msg = """""" + Could not find the line to insert the initial cells loading code. + Aborting the import process. + """""" + println(msg) + return false + end + return true + end + + lines[idx] = ""\tload_initial_cells();"" + + idx = findfirst(contains(""setup_cell_rules""), lines) + if !isnothing(idx) + lines[idx] = ""\tsetup_behavior_rules();"" + end + + open(path_to_custom_cpp, ""w"") do f + for line in lines + println(f, line) + end + end + return true +end + +"""""" + processSuccessfulImport(path_to_project::AbstractString, import_dest_folders::ImportDestFolders) + +Process the successful import by printing the new folders created, re-initializing the database, printing Julia code to prepare inputs, and returning the `InputFolders` instance. + +[`importProject`](@ref) will create new input folders each time it is called, even if calling a project that was already imported. +So, the printed Julia code should be used to add to scripts that prepare inputs for running the imported project. +"""""" +function processSuccessfulImport(path_to_project::AbstractString, import_dest_folders::ImportDestFolders) + printNewFolders!(path_to_project, import_dest_folders) + println(""Re-initializing the database to include these new entries...\n"") + reinitializeDatabase() + + kwargs = Dict{Symbol, String}() + for (loc, folder) in pairs(import_dest_folders.import_dest_folders) + kwargs[loc] = folder.created ? splitpath(folder.path_from_inputs)[end] : """" + end + + unique_folder_names = kwargs |> values |> unique + naming_str = """" + for unique_folder_name in unique_folder_names + if unique_folder_name == """" + continue + end + these_locs = filter(loc -> kwargs[loc] == unique_folder_name, keys(kwargs)) + s = join(these_locs, "" = "") + s *= "" = "" * ""\""$unique_folder_name\"""" + naming_str *= s * ""\n"" + end + + indent = 4 + inputs_str = ""inputs = InputFolders(\n"" * "" ""^(indent) + inputs_str *= join([String(loc) for loc in projectLocations().required], "",\n"" * "" ""^indent) + + kwargs_str = join([String(loc) * "" = "" * String(loc) for loc in setdiff(projectLocations().all, projectLocations().required) if kwargs[loc] != """"], "",\n"" * "" ""^indent) + + if !isempty(kwargs_str) + inputs_str *= "";\n"" * "" ""^(indent) + inputs_str *= kwargs_str + end + inputs_str *= ""\n)"" + + first_line = ""Copy the following into a Julia script to prepare the inputs for running this imported project:"" + max_len = mapreduce(x -> split(x, ""\n""), vcat, [naming_str, first_line, inputs_str]) .|> length |> maximum + padding = 4 + + println(""#""^(max_len + padding)) + println(""$first_line\n"" * ""-""^length(first_line)) + println(naming_str) + println(inputs_str) + println(""#""^(max_len + padding)) + println() + + return InputFolders(; kwargs...) +end + +"""""" + printNewFolders!(path_to_project::AbstractString, import_dest_folders::ImportDestFolders) + +Internal function to print the new folders created during the import process. +"""""" +function printNewFolders!(path_to_project::AbstractString, import_dest_folders::ImportDestFolders) + print(""Imported project from $(path_to_project) into $(joinpath(dataDir(), ""inputs"")):"") + paths_created = [splitpath(folder.path_from_inputs) for folder in import_dest_folders.import_dest_folders if folder.created] + + while !isempty(paths_created) + printTogether!(paths_created) + end + println(""\n"") +end + +"""""" + printTogether!(paths_created::Vector{Vector{String}}, indent::Int=1) + +Internal helper function to print the paths created during the import process in a structured way. +"""""" +function printTogether!(paths_created::Vector{Vector{String}}, indent::Int=1) + path = popfirst!(paths_created) + + paths_with_shared_first = filter(p -> p[1] == path[1], paths_created) + + if isempty(paths_with_shared_first) + print(""\n"" * "" ""^(4 * indent) * ""- $(joinpath(path...))"") + return + end + + print(""\n"" * "" ""^(4 * indent) * ""- $(path[1])/"") + + next_level_paths = [path, paths_with_shared_first...] .|> copy + popfirst!.(next_level_paths) #! remove the common folder from each path + + while !isempty(next_level_paths) + printTogether!(next_level_paths, indent + 1) + end + + filter!(p -> p[1] != path[1], paths_created) +end +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/runner.jl",".jl","18526","427","import Base.run + +export runAbstractTrial, run + +"""""" + prepareSimulationCommand(simulation::Simulation, monad_id::Int, do_full_setup::Bool, force_recompile::Bool) + +Internal function to prepare the command to run a simulation, including preparing input files and compiling the custom code if necessary. +"""""" +function prepareSimulationCommand(simulation::Simulation, monad_id::Int, do_full_setup::Bool, force_recompile::Bool) + path_to_simulation_output = joinpath(trialFolder(simulation), ""output"") + mkpath(path_to_simulation_output) + + if do_full_setup + for loc in projectLocations().varied + prepareVariedInputFolder(loc, simulation) + end + success = loadCustomCode(simulation; force_recompile=force_recompile) + if !success + simulationFailed(simulation, monad_id) + return nothing + end + end + + executable_str = joinpath(locationPath(:custom_code, simulation), baseToExecutable(""project"")) #! path to executable + config_str = joinpath(locationPath(:config, simulation), locationVariationsFolder(:config), ""config_variation_$(simulation.variation_id[:config]).xml"") + flags = [""-o"", path_to_simulation_output] + if simulation.inputs[:ic_cell].id != -1 + try + append!(flags, [""-i"", pathToICCell(simulation)]) + catch e + println(""\nWARNING: Simulation $(simulation.id) failed to initialize the IC cell file.\n\tCause: $e\n"") + simulationFailed(simulation, monad_id) + return nothing + end + end + if simulation.inputs[:ic_substrate].id != -1 + append!(flags, [""-s"", joinpath(locationPath(:ic_substrate, simulation), ""substrates.csv"")]) #! if ic file included (id != -1), then include this in the command + end + if simulation.inputs[:ic_ecm].id != -1 + try + append!(flags, [""-e"", pathToICECM(simulation)]) #! if ic file included (id != -1), then include this in the command + catch e + println(""\nWARNING: Simulation $(simulation.id) failed to initialize the IC ECM file.\n\tCause: $e\n"") + simulationFailed(simulation, monad_id) + return nothing + end + end + if simulation.inputs[:ic_dc].id != -1 + append!(flags, [""-d"", joinpath(locationPath(:ic_dc, simulation), ""dcs.csv"")]) #! if ic file included (id != -1), then include this in the command + end + if simulation.variation_id[:rulesets_collection] != -1 + path_to_rules_file = joinpath(locationPath(:rulesets_collection, simulation), locationVariationsFolder(:rulesets_collection), ""rulesets_collection_variation_$(simulation.variation_id[:rulesets_collection]).xml"") + append!(flags, [""-r"", path_to_rules_file]) + end + if simulation.variation_id[:intracellular] != -1 + path_to_intracellular_file = joinpath(locationPath(:intracellular, simulation), locationVariationsFolder(:intracellular), ""intracellular_variation_$(simulation.variation_id[:intracellular]).xml"") + append!(flags, [""-n"", path_to_intracellular_file]) + end + return Cmd(`$executable_str $config_str $flags`; env=ENV, dir=physicellDir()) +end + +"""""" + simulationFailed(simulation::Simulation, monad_id::Int) + simulationFailed(simulation_id::Int, monad_id::Int) + +Set the status code of the simulation to ""Failed"" and erase the simulation ID from the `simulations.csv` file for the monad it belongs to. +"""""" +simulationFailed(simulation::Simulation, monad_id::Int) = simulationFailed(simulation.id, monad_id) + +function simulationFailed(simulation_id::Int, monad_id::Int) + DBInterface.execute(centralDB(),""UPDATE simulations SET status_code_id=$(statusCodeID(""Failed"")) WHERE simulation_id=$(simulation_id);"" ) + eraseSimulationIDFromConstituents(simulation_id; monad_id=monad_id) + return +end + +"""""" + SimulationProcess + +A struct to hold the simulation process and its associated monad ID. Users should not need to interact with this struct directly. + +# Fields +- `simulation::Simulation`: The simulation object. +- `monad_id::Int`: The ID of the associated monad. +- `process::Union{Nothing,Base.Process}`: The process associated with the simulation. If the simulation process fails, e.g. if the command cannot be constructed, this will be `nothing`. +- `success::Bool`: The success status of the simulation process. Set after the process has finished. +"""""" +struct SimulationProcess + simulation::Simulation + monad_id::Int + process::Union{Nothing,Base.Process} + success::Bool + + function SimulationProcess(simulation::Simulation; monad_id::Union{Missing,Int}=missing, do_full_setup::Bool=true, force_recompile::Bool=false) + if ismissing(monad_id) + monad = Monad(simulation) + monad_id = monad.id + end + + cmd = prepareSimulationCommand(simulation, monad_id, do_full_setup, force_recompile) + if isnothing(cmd) + updateDatabaseOnCompletion(simulation.id, monad_id, false) + return new(simulation, monad_id, nothing, false) + end + + path_to_simulation_folder = trialFolder(simulation) + DBInterface.execute(centralDB(),""UPDATE simulations SET status_code_id=$(statusCodeID(""Running"")) WHERE simulation_id=$(simulation.id);"" ) + println(""\tRunning simulation: $(simulation.id)..."") + flush(stdout) + if pcmm_globals.run_on_hpc + cmd = prepareHPCCommand(cmd, simulation.id) + the_pipeline = pipeline(ignorestatus(cmd); stdout=joinpath(path_to_simulation_folder, ""hpc.out""), stderr=joinpath(path_to_simulation_folder, ""hpc.err"")) + else + the_pipeline = pipeline(ignorestatus(cmd); stdout=joinpath(path_to_simulation_folder, ""output.log""), stderr=joinpath(path_to_simulation_folder, ""output.err"")) + end + p = try + run(the_pipeline; wait=true) + catch e + println(""\nWARNING: The command for Simulation $(simulation.id) failed to execute.\n\tCause: $e\n"") + nothing + end + success = isnothing(p) ? false : p.exitcode == 0 + updateDatabaseOnCompletion(simulation.id, monad_id, success) + return new(simulation, monad_id, p, success) + end +end + +"""""" + prepCmdForWrap(cmd::Cmd) + +Prepare the command for wrapping in the sbatch command. This is a helper function to remove the backticks from the command string. +"""""" +function prepCmdForWrap(cmd::Cmd) + cmd = string(cmd) + cmd = strip(cmd, '`') + return cmd +end + +"""""" + prepareHPCCommand(cmd::Cmd, simulation_id::Int) + +Prepare the command to run a simulation on an HPC system using sbatch. This function adds the necessary flags to the command and returns it as a Cmd object. +"""""" +function prepareHPCCommand(cmd::Cmd, simulation_id::Int) + path_to_simulation_folder = trialFolder(Simulation, simulation_id) + base_cmd_str = ""sbatch"" + flags = [""--wrap=$(prepCmdForWrap(Cmd(cmd.exec)))"", + ""--wait"", + ""--output=$(joinpath(path_to_simulation_folder, ""output.log""))"", + ""--error=$(joinpath(path_to_simulation_folder, ""output.err""))"", + ""--chdir=$(physicellDir())"" + ] + for (k, v) in pcmm_globals.sbatch_options + @assert !(k in [""wrap"", ""output"", ""error"", ""wait"", ""chdir""]) ""The key $k is reserved for PhysiCellModelManager.jl to set in the sbatch command."" + if typeof(v) <: Function + v = v(simulation_id) + end + #! check if v has any spaces + if occursin("" "", v) + v = ""\""$v\"""" + end + push!(flags, ""--$k=$v"") + end + return `$base_cmd_str $flags` +end + +"""""" + resolveSimulation(simulation_process::SimulationProcess, prune_options::PruneOptions) + +Resolve the simulation process by checking its success status, printing warnings if it failed, and pruning the simulation output if necessary. +"""""" +function resolveSimulation(simulation_process::SimulationProcess, prune_options::PruneOptions) + if isnothing(simulation_process.process) + return + end + simulation = simulation_process.simulation + p = simulation_process.process + path_to_simulation_folder = trialFolder(simulation) + path_to_err = joinpath(path_to_simulation_folder, ""output.err"") + if simulation_process.success + rm(path_to_err; force=true) + rm(joinpath(path_to_simulation_folder, ""hpc.err""); force=true) + else + println(""\nWARNING: Simulation $(simulation.id) failed. Please check $(path_to_err) for more information.\n"") + #! write the execution command to output.err + lines = readlines(path_to_err) + open(path_to_err, ""w+"") do io + #! read the lines of the output.err file + println(io, ""Execution command: $(p.cmd)"") + println(io, ""\n---stderr from PhysiCell---"") + for line in lines + println(io, line) + end + end + end + + pruneSimulationOutput(simulation, prune_options) + return +end + +"""""" + collectSimulationTasks(T::AbstractTrial[; force_recompile::Bool=false]) + +Collect the simulation tasks for the given trial, sampling, monad, or simulation. + +# Arguments +- `T::AbstractTrial`: The trial, sampling, monad, or simulation to collect tasks for. + +# Keyword Arguments +- `force_recompile::Bool=false`: If `true`, forces a recompilation of all files by removing all `.o` files in the PhysiCell directory. +- `do_full_setup::Bool=true`: If `true`, performs a full setup of the simulation, including compiling code and preparing input files. Only used for [`AbstractMonad`](@ref) objects. +"""""" +collectSimulationTasks(simulation::Simulation; force_recompile::Bool=false) = + isStarted(simulation; new_status_code=""Queued"") ? Task[] : [@task SimulationProcess(simulation; do_full_setup=true, force_recompile=force_recompile)] + +function collectSimulationTasks(monad::Monad; do_full_setup::Bool=true, force_recompile::Bool=false) + mkpath(trialFolder(monad)) + + if do_full_setup + compilation_success = loadCustomCode(monad; force_recompile=force_recompile) + if !compilation_success + return Task[] #! do not delete simulations or the monad as these could have succeeded in the past (or on other nodes, etc.) + end + end + + for loc in projectLocations().varied + prepareVariedInputFolder(loc, monad) + end + + simulation_tasks = Task[] + for simulation_id in simulationIDs(monad) + if isStarted(simulation_id; new_status_code=""Queued"") + continue #! if the simulation has already been started (or even completed), then don't run it again + end + simulation = Simulation(simulation_id) + + push!(simulation_tasks, @task SimulationProcess(simulation; monad_id=monad.id, do_full_setup=false, force_recompile=false)) + end + + return simulation_tasks +end + +function collectSimulationTasks(sampling::Sampling; force_recompile::Bool=false) + mkpath(trialFolder(sampling)) + + compilation_success = loadCustomCode(sampling; force_recompile=force_recompile) + if !compilation_success + return Task[] #! do not delete simulations, monads, or the sampling as these could have succeeded in the past (or on other nodes, etc.) + end + + simulation_tasks = [] + for monad in Monad.(constituentIDs(sampling)) + append!(simulation_tasks, collectSimulationTasks(monad, do_full_setup=false, force_recompile=false)) #! run the monad and add the number of new simulations to the total + end + + return simulation_tasks +end + +function collectSimulationTasks(trial::Trial; force_recompile::Bool=false) + mkpath(trialFolder(trial)) + + simulation_tasks = [] + for sampling in Sampling.(constituentIDs(trial)) + append!(simulation_tasks, collectSimulationTasks(sampling; force_recompile=force_recompile)) #! run the sampling and add the number of new simulations to the total + end + + return simulation_tasks +end + +"""""" + PCMMOutput{T<:AbstractTrial} + +A struct to hold the output of the PhysiCellModelManager.jl run, including the [`AbstractTrial`](@ref) object, the number of scheduled simulations, and the number of successful simulations. + +# Fields +- `trial::T`: The trial, sampling, monad, or simulation that was run. +- `n_scheduled::Int`: The number of simulations that were scheduled to run. +- `n_success::Int`: The number of simulations that were successfully completed. +"""""" +struct PCMMOutput{T<:AbstractTrial} + trial::T + n_scheduled::Int + n_success::Int + + function PCMMOutput(trial::T, n_scheduled::Int, n_success::Int) where T<:AbstractTrial + new{T}(trial, n_scheduled, n_success) + end +end + +function Base.show(io::IO, output::PCMMOutput) + println(io, ""PCMM Output"") + println(io, ""------------"") + println(io, output.trial) + println(io, """") + println(io, ""In completing this trial:"") + println(io, "" - Scheduled $(output.n_scheduled) simulations."") + println(io, "" - Successfully completed $(output.n_success) simulations."") +end + +"""""" + simulationIDs(output::PCMMOutput) + +Get the simulation IDs from the output of the PhysiCellModelManager.jl run. +"""""" +simulationIDs(output::PCMMOutput) = simulationIDs(output.trial) + +"""""" + trialType(output::PCMMOutput) + +Get the type of the trial from the output of the PhysiCellModelManager.jl run. +"""""" +trialType(output::PCMMOutput) = trialType(output.trial) + +"""""" + trialID(output::PCMMOutput) + +Get the ID of the trial from the output of the PhysiCellModelManager.jl run. +"""""" +trialID(output::PCMMOutput) = trialID(output.trial) + +"""""" + run(T::AbstractTrial[; force_recompile::Bool=false, prune_options::PruneOptions=PruneOptions()])` + +Run the given simulation, monad, sampling, or trial. + +Call the appropriate functions to run the simulations and return the number of successful simulations. +Also print out messages to the console to inform the user about the progress and results of the simulations. + +# Arguments +- `T::AbstractTrial`: The trial, sampling, monad, or simulation to run. +- `force_recompile::Bool=false`: If `true`, forces a recompilation of all files by removing all `.o` files in the PhysiCell directory. +- `prune_options::PruneOptions=PruneOptions()`: Options for pruning simulations. +"""""" +function run(T::AbstractTrial; force_recompile::Bool=false, prune_options::PruneOptions=PruneOptions()) + simulation_tasks = collectSimulationTasks(T; force_recompile=force_recompile) + n_simulation_tasks = length(simulation_tasks) + n_success = 0 + + println(""Running $(typeof(T)) $(T.id) requiring $(n_simulation_tasks) simulation$(n_simulation_tasks == 1 ? """" : ""s"")..."") + + queue_channel = Channel{Task}(n_simulation_tasks) + result_channel = Channel{SimulationProcess}(n_simulation_tasks) + @async for simulation_task in simulation_tasks + put!(queue_channel, simulation_task) #! if the queue_channel is full, this will block until there is space + end + + for _ in 1:pcmm_globals.max_number_of_parallel_simulations #! start one task per allowed num of parallel sims + @async for simulation_task in queue_channel #! do not let the creation of this task block the creation of the other tasks + #! once the simulation_task is processed, put it in the result_channel and move on to the next simulation_task in the queue_channel + put!(result_channel, processSimulationTask(simulation_task, prune_options)) + end + end + + #! this code block effectively blocks the main thread until all the simulation_tasks have been processed + for _ in 1:n_simulation_tasks #! take exactly the number of expected outputs + simulation_process = take!(result_channel) #! wait until the result_channel has a value to take + n_success += simulation_process.success + end + + n_asterisks = 1 + asterisks = Dict{String, Int}() + size_T = length(T) + println(""Finished $(typeof(T)) $(T.id)."") + println(""\t- Consists of $(size_T) simulations."") + print( ""\t- Scheduled $(n_simulation_tasks) simulations to complete this $(typeof(T))."") + print_low_schedule_message = n_simulation_tasks < size_T + if print_low_schedule_message + println("" ($(repeat(""*"", n_asterisks)))"") + asterisks[""low_schedule_message""] = n_asterisks + n_asterisks += 1 + else + println() + end + print( ""\t- Successful completion of $(n_success) simulations."") + print_low_success_warning = n_success < n_simulation_tasks + if print_low_success_warning + println("" ($(repeat(""*"", n_asterisks)))"") + asterisks[""low_success_warning""] = n_asterisks + n_asterisks += 1 #! in case something gets added later + else + println() + end + if print_low_schedule_message + println(""\n($(repeat(""*"", asterisks[""low_schedule_message""]))) PhysiCellModelManager.jl found matching simulations and will save you time by not re-running them!"") + end + if print_low_success_warning + println(""\n($(repeat(""*"", asterisks[""low_success_warning""]))) Some simulations did not complete successfully. Check the output.err files for more information."") + end + println(""\n--------------------------------------------------\n"") + return PCMMOutput(T, n_simulation_tasks, n_success) +end + +"""""" + runAbstractTrial(T::AbstractTrial; force_recompile::Bool=false, prune_options::PruneOptions=PruneOptions()) + +Deprecated alias for [`run`](@ref), but only with this particular signature. Does not work on `Cmd` objects as `Base.run` is built for. +Also, does not work with `run`ning sensitivity samplings. +"""""" +function runAbstractTrial(T::AbstractTrial; force_recompile::Bool=false, prune_options::PruneOptions=PruneOptions()) + Base.depwarn(""`runAbstractTrial` is deprecated. Use `run` instead."", :runAbstractTrial; force=true) + return run(T; force_recompile=force_recompile, prune_options=prune_options) +end + +"""""" + processSimulationTask(simulation_task, prune_options) + +Process the given simulation task and return whether it was successful. +"""""" +function processSimulationTask(simulation_task, prune_options) + schedule(simulation_task) + simulation_process = fetch(simulation_task) + resolveSimulation(simulation_process, prune_options) + return simulation_process +end + +"""""" + updateDatabaseOnCompletion(simulation_id::Int, monad_id::Int, success::Bool) + +Update the database on completion of a simulation. +"""""" +function updateDatabaseOnCompletion(simulation_id::Int, monad_id::Int, success::Bool) + if success + DBInterface.execute(centralDB(), ""UPDATE simulations SET status_code_id=$(statusCodeID(""Completed"")) WHERE simulation_id=$(simulation_id);"") + else + simulationFailed(simulation_id, monad_id) + end +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/movie.jl",".jl","4508","100","export makeMovie + +"""""" + makeMovie(simulation_id::Int; magick_path::Union{Missing,String}=pcmm_globals.path_to_magick, ffmpeg_path::Union{Missing,String}=pcmm_globals.path_to_ffmpeg) + makeMovie(T::AbstractTrial; kwargs...) + makeMovie(out::PCMMOutput; kwargs...) + +Batch make movies for each simulation identified by the input. + +Use the PhysiCell Makefile to generate the movie. +This process requires first generating JPEG files, which are then used to create the movie. +Deletes the JPEG files after the movie is generated. + +This relies on ImageMagick and FFmpeg being installed on the system. +There are three ways to allow this function to find these dependencies: + 1. Pass the path to the dependencies using the `magick_path` and `ffmpeg_path` keyword arguments. + 2. Set the `PATH` environment variable to include the directories containing the dependencies. + 3. Set environment variables `PCMM_IMAGEMAGICK_PATH` and `PCMM_FFMPEG_PATH` before `using PhysiCellModelManager`. + +# Arguments +- `simulation_id::Int`: The ID of the simulation for which to make the movie. +- `T::AbstractTrial`: Make movies for all simulations in the [`AbstractTrial`](@ref). +- `out::PCMMOutput`: Make movies for all simulations in the output, i.e., all simulations in the completed trial. + +# Keyword Arguments +- `magick_path::Union{Missing,String}`: The path to the ImageMagick executable. If not provided, uses the global variable `pcmm_globals.path_to_magick`. +- `ffmpeg_path::Union{Missing,String}`: The path to the FFmpeg executable. If not provided, uses the global variable `pcmm_globals.path_to_ffmpeg`. + +# Example +```julia +makeMovie(123) # make a movie for simulation 123 +``` +```julia +makeMovie(sampling) # make movies for all simulations in the sampling +``` +```julia +out = run(sampling) # run the sampling +makeMovie(out) # make movies for all simulations in the output +``` +"""""" +function makeMovie(simulation_id::Int; magick_path::Union{Missing,String}=pcmm_globals.path_to_magick, ffmpeg_path::Union{Missing,String}=pcmm_globals.path_to_ffmpeg) + assertInitialized() + path_to_output_folder = joinpath(trialFolder(Simulation, simulation_id), ""output"") + if isfile(""$(path_to_output_folder)/out.mp4"") + movie_generated = false + return movie_generated + end + env = copy(ENV) + os_variable_separator = Sys.iswindows() ? "";"" : "":"" + path_components = split(env[""PATH""], os_variable_separator) + resolveMovieGlobals(magick_path, ffmpeg_path) + if !ismissing(magick_path) && !(magick_path ∈ path_components) + env[""PATH""] = ""$(magick_path)$(os_variable_separator)$(env[""PATH""])"" + end + if !ismissing(ffmpeg_path) && !(ffmpeg_path ∈ path_components) && ffmpeg_path != magick_path + env[""PATH""] = ""$(ffmpeg_path)$(os_variable_separator)$(env[""PATH""])"" + end + if !shellCommandExists(""magick"") + throw(ErrorException(""ImageMagick is not installed. Please install it to generate movies."")) + elseif !shellCommandExists(""ffmpeg"") + throw(ErrorException(""FFmpeg is not installed. Please install it to generate movies."")) + end + cmd = Cmd(`make jpeg OUTPUT=$(path_to_output_folder)`; env=env, dir=physicellDir()) + quietRun(cmd) + cmd = Cmd(`make movie OUTPUT=$(path_to_output_folder)`; env=env, dir=physicellDir()) + quietRun(cmd) + movie_generated = true + jpgs = readdir(joinpath(trialFolder(Simulation, simulation_id), ""output""), sort=false) + filter!(f -> endswith(f, "".jpg""), jpgs) + for jpg in jpgs + rm(joinpath(trialFolder(Simulation, simulation_id), ""output"", jpg)) + end + return movie_generated +end + +"""""" + resolveMovieGlobals(magick_path::Union{Missing,String}, ffmpeg_path::Union{Missing,String}) + +Set the global variables `path_to_magick` and `path_to_ffmpeg` to the provided paths. +"""""" +function resolveMovieGlobals(magick_path::Union{Missing,String}, ffmpeg_path::Union{Missing,String}) + if !ismissing(magick_path) + pcmm_globals.path_to_magick = magick_path + end + if !ismissing(ffmpeg_path) + pcmm_globals.path_to_ffmpeg = ffmpeg_path + end +end + +function makeMovie(T::AbstractTrial; kwargs...) + simulation_ids = simulationIDs(T) + println(""Making movies for $(typeof(T)) $(T.id) with $(length(simulation_ids)) simulations..."") + for simulation_id in simulation_ids + print("" Making movie for simulation $simulation_id..."") + makeMovie(simulation_id; kwargs...) + println(""done."") + end +end + +makeMovie(T::PCMMOutput; kwargs...) = makeMovie(T.trial; kwargs...)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/utilities.jl",".jl","198","6",""""""" + quietRun(cmd::Cmd) + +Run the command with stdout and stderr redirected to devnull so no output goes to the console. +"""""" +quietRun(cmd::Cmd) = run(pipeline(cmd, stdout=devnull, stderr=devnull))","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/variations.jl",".jl","64366","1368","using Distributions +import Distributions: cdf + +export ElementaryVariation, DiscreteVariation, DistributedVariation, CoVariation +export UniformDistributedVariation, NormalDistributedVariation +export GridVariation, LHSVariation, SobolVariation, RBDVariation +export addDomainVariationDimension!, addCustomDataVariationDimension!, addAttackRateVariationDimension! + +################## XMLPath ################## + +"""""" + XMLPath + +Hold the XML path as a vector of strings. + +PhysiCell uses a `:` in names for signals/behaviors from cell custom data. +For example, `custom:sample` is the default way to represent the `sample` custom data in a PhysiCell rule. +PhysiCellModelManager.jl uses `:` to indicate an attribute in an XML path and thus splits on `:` when looking for attribute values. +To avoid this conflict, PhysiCellModelManager.jl will internally replace `custom:` and `custom: ` with `custom `. +Users should never have to think about this. +Any PhysiCellModelManager.jl function that uses XML paths will automatically handle this replacement. +"""""" +struct XMLPath + xml_path::Vector{String} + + function XMLPath(xml_path::AbstractVector{<:AbstractString}) + for path_element in xml_path + tokens = split(path_element, "":"") + if length(tokens) < 4 + continue + end + msg = """""" + Invalid XML path: $(path_element) + It has $(length(tokens)) tokens (':' is the delimiter) but the only valid path element with >3 tokens if one of: + - ::: + - ::custom: (where the final ':' is part of how PhysiCell denotes custom data) + - ::custom: (where the final ':' is part of how PhysiCell denotes custom data) + """""" + @assert (isempty(tokens[2]) || tokens[3] == ""custom"") msg + end + return new(xml_path) + end +end + +columnName(xp::XMLPath) = columnName(xp.xml_path) + +Base.show(io::IO, xp::XMLPath) = println(io, ""XMLPath: $(columnName(xp))"") + +################## Abstract Variations ################## + +"""""" + AbstractVariation + +Abstract type for variations. + +# Subtypes +[`ElementaryVariation`](@ref), [`DiscreteVariation`](@ref), [`DistributedVariation`](@ref), [`CoVariation`](@ref) + +# Methods +[`addVariations`](@ref), [`createTrial`](@ref), [`run`](@ref), +[`_createTrial`](@ref) +"""""" +abstract type AbstractVariation end + +"""""" + ElementaryVariation <: AbstractVariation + +The base type for variations of a single parameter. +"""""" +abstract type ElementaryVariation <: AbstractVariation end + +"""""" + DiscreteVariation + +The location, target, and values of a discrete variation. + +# Fields +- `location::Symbol`: The location of the variation. Can be `:config`, `:rulesets_collection`, `:intracellular`, `:ic_cell`, `:ic_ecm`. The location is inferred from the target. +- `target::XMLPath`: The target of the variation. The target is a vector of strings that represent the XML path to the element being varied. See [`XMLPath`](@ref) for more information. +- `values::Vector{T}`: The values of the variation. The values are the possible values that the target can take on. + +A singleton value can be passed in place of `values` for convenience. + +# Examples +```jldoctest +julia> dv = DiscreteVariation([""overall"", ""max_time""], [1440.0, 2880.0]) +DiscreteVariation (Float64): + location: config + target: overall/max_time + values: [1440.0, 2880.0] +``` +```jldoctest +xml_path = rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""max_response"") +DiscreteVariation(xml_path, 0) +# output +DiscreteVariation (Int64): + location: rulesets_collection + target: behavior_ruleset:name:default/behavior:name:cycle entry/decreasing_signals/max_response + values: [0] +``` +```jldoctest +xml_path = icCellsPath(""default"", ""disc"", 1, ""x0"") +DiscreteVariation(xml_path, [0.0, 100.0]) +# output +DiscreteVariation (Float64): + location: ic_cell + target: cell_patches:name:default/patch_collection:type:disc/patch:ID:1/x0 + values: [0.0, 100.0] +``` +```jldoctest +xml_path = icECMPath(2, ""ellipse"", 1, ""density"") +DiscreteVariation(xml_path, [0.1, 0.2]) +# output +DistributedVariation: + location: ic_ecm + target: layer:ID:2/patch_collection:type:ellipse/patch:ID:1/density + values: [0.1, 0.2] +"""""" +struct DiscreteVariation{T} <: ElementaryVariation + location::Symbol + target::XMLPath + values::Vector{T} + + function DiscreteVariation(target::Vector{<:AbstractString}, values::Vector{T}) where T + return DiscreteVariation(XMLPath(target), values) + end + + function DiscreteVariation(target::XMLPath, values::Vector{T}) where T + location = variationLocation(target) + return new{T}(location, target, values) + end +end + +DiscreteVariation(xml_path::Vector{<:AbstractString}, value::T) where T = DiscreteVariation(xml_path, Vector{T}([value])) + +Base.length(discrete_variation::DiscreteVariation) = length(discrete_variation.values) + +function Base.show(io::IO, dv::DiscreteVariation) + println(io, ""DiscreteVariation ($(variationDataType(dv))):"") + println(io, "" location: $(dv.location)"") + println(io, "" target: $(columnName(dv))"") + println(io, "" values: $(dv.values)"") +end + +function ElementaryVariation(target::Vector{<:AbstractString}, v; kwargs...) + if v isa Distribution{Univariate} + return DistributedVariation(target, v; kwargs...) + else + return DiscreteVariation(target, v; kwargs...) + end +end + +"""""" + DistributedVariation + +The location, target, and distribution of a distributed variation. + +Analagousy to [`DiscreteVariation`](@ref), instances of `DistributedVariation` can be initialized with a `target` (XML path) and a `distribution` (a distribution from the `Distributions` package). +Alternatively, users can use the [`UniformDistributedVariation`](@ref) and [`NormalDistributedVariation`](@ref) functions to create instances of `DistributedVariation`. + +# Fields +- `location::Symbol`: The location of the variation. Can be `:config`, `:rulesets_collection`, `:intracellular`, `:ic_cell`, or `:ic_ecm`. The location is inferred from the target. +- `target::XMLPath`: The target of the variation. The target is a vector of strings that represent the XML path to the element being varied. See [`XMLPath`](@ref) for more information. +- `distribution::Distribution`: The distribution of the variation. +- `flip::Bool=false`: Whether to flip the distribution, i.e., when asked for the iCDF of `x`, return the iCDF of `1-x`. Useful for [`CoVariation`](@ref)'s. + +# Examples +```jldoctest +using Distributions +d = Uniform(1, 2) +DistributedVariation(PhysiCellModelManager.apoptosisPath(""default"", ""death_rate""), d) +# output +DistributedVariation: + location: config + target: cell_definitions/cell_definition:name:default/phenotype/death/model:code:100/death_rate + distribution: Distributions.Uniform{Float64}(a=1.0, b=2.0) +``` +```jldoctest +using Distributions +d = Uniform(1, 2) +flip = true # the cdf on this variation will decrease from 1 to 0 as the value increases from 1 to 2 +DistributedVariation(PhysiCellModelManager.necrosisPath(""default"", ""death_rate""), d; flip=flip) +# output +DistributedVariation (flipped): + location: config + target: cell_definitions/cell_definition:name:default/phenotype/death/model:code:101/death_rate + distribution: Distributions.Uniform{Float64}(a=1.0, b=2.0) +"""""" +struct DistributedVariation <: ElementaryVariation + location::Symbol + target::XMLPath + distribution::Distribution + flip::Bool + + function DistributedVariation(target::Vector{<:AbstractString}, distribution::Distribution; flip::Bool=false) + return DistributedVariation(XMLPath(target), distribution; flip=flip) + end + function DistributedVariation(target::XMLPath, distribution::Distribution; flip::Bool=false) + location = variationLocation(target) + return new(location, target, distribution, flip) + end +end + +"""""" + variationTarget(av::AbstractVariation) + +Get the type [`XMLPath`](@ref) target(s) of a variation +"""""" +variationTarget(ev::ElementaryVariation) = ev.target + +"""""" + variationLocation(av::AbstractVariation) + +Get the location of a variation as a `Symbol`, e.g., `:config`, `:rulesets_collection`, etc. +Can also pass in an [`XMLPath`](@ref) object. +"""""" +variationLocation(ev::ElementaryVariation) = ev.location + +columnName(ev::ElementaryVariation) = variationTarget(ev) |> columnName + +Base.length(::DistributedVariation) = -1 #! set to -1 to be a convention + +function Base.show(io::IO, dv::DistributedVariation) + println(io, ""DistributedVariation"" * (dv.flip ? "" (flipped)"" : """") * "":"") + println(io, "" location: $(dv.location)"") + println(io, "" target: $(columnName(dv))"") + println(io, "" distribution: $(dv.distribution)"") +end + +"""""" + UniformDistributedVariation(xml_path::Vector{<:AbstractString}, lb::T, ub::T; flip::Bool=false) where {T<:Real} + +Create a distributed variation with a uniform distribution. +"""""" +function UniformDistributedVariation(xml_path::Vector{<:AbstractString}, lb::T, ub::T; flip::Bool=false) where {T<:Real} + return DistributedVariation(xml_path, Uniform(lb, ub); flip=flip) +end + +"""""" + NormalDistributedVariation(xml_path::Vector{<:AbstractString}, mu::T, sigma::T; lb::Real=-Inf, ub::Real=Inf, flip::Bool=false) where {T<:Real} + +Create a (possibly truncated) distributed variation with a normal distribution. +"""""" +function NormalDistributedVariation(xml_path::Vector{<:AbstractString}, mu::T, sigma::T; lb::Real=-Inf, ub::Real=Inf, flip::Bool=false) where {T<:Real} + return DistributedVariation(xml_path, truncated(Normal(mu, sigma), lb, ub); flip=flip) +end + +"""""" + variationValues(ev::ElementaryVariation[, cdf]) + +Get the values of an [`ElementaryVariation`](@ref). + +If `ev` is a [`DiscreteVariation`](@ref), all values are returned unless `cdf` is provided. +In that case, the CDF(s) is linearly converted into an index into the values vector and the corresponding value is returned. + +If `ev` is a [`DistributedVariation`](@ref), the `cdf` is required and the iCDF is returned. +The `cdf` can be a single value or a vector of values. + +# Arguments +- `ev::ElementaryVariation`: The variation to get the values of. +- `cdf`: The cumulative distribution function (CDF) values to use for the variation. +"""""" +variationValues(discrete_variation::DiscreteVariation) = discrete_variation.values + +function variationValues(discrete_variation::DiscreteVariation, cdf::Vector{<:Real}) + index = floor.(Int, cdf * length(discrete_variation)) .+ 1 + index[index.==(length(discrete_variation)+1)] .= length(discrete_variation) #! if cdf = 1, index = length(discrete_variation)+1, so we set it to length(discrete_variation) + return discrete_variation.values[index] +end + +function variationValues(dv::DistributedVariation, cdf::Vector{<:Real}) + return map(Base.Fix1(quantile, dv.distribution), dv.flip ? 1 .- cdf : cdf) +end + +variationValues(ev, cdf::Real) = variationValues(ev, [cdf]) + +variationValues(::DistributedVariation) = error(""A cdf must be provided for a DistributedVariation."") + +"""""" + variationValues(f::Function, ev::ElementaryVariation[, cdf]) + +Apply a function `f` to each of the variation values of an [`ElementaryVariation`](@ref). +See [`variationValues`](@ref) for details on how the variation values are obtained. +"""""" +variationValues(f::Function, args...) = f.(variationValues(args...)) + +"""""" + variationDataType(ev::ElementaryVariation) + +Get the data type of the variation. +"""""" +variationDataType(::DiscreteVariation{T}) where T = T +variationDataType(dv::DistributedVariation) = eltype(dv.distribution) + +"""""" + sqliteDataType(ev::ElementaryVariation) + sqliteDataType(data_type::DataType) + +Get the SQLite data type to hold the Julia data type. + +These are the mappings in the order of the if-else statements: +- `Bool` -> `TEXT` +- `Integer` -> `INT` +- `Real` -> `REAL` +- otherwise -> `TEXT` +"""""" +function sqliteDataType(ev::ElementaryVariation) + return sqliteDataType(variationDataType(ev)) +end + +function sqliteDataType(data_type::DataType) + if data_type == Bool + return ""TEXT"" + elseif data_type <: Integer + return ""INT"" + elseif data_type <: Real + return ""REAL"" + else + return ""TEXT"" + end +end + +"""""" + cdf(ev::ElementaryVariation, x::Real) + +Get the cumulative distribution function (CDF) of the variation at `x`. + +If `ev` is a [`DiscreteVariation`](@ref), `x` must be in the values of the variation. +The value returned is from `0:Δ:1` where `Δ=1/(n-1)` and `n` is the number of values in the variation. + +If `ev` is a [`DistributedVariation`](@ref), the CDF is computed from the distribution of the variation. +"""""" +function cdf(discrete_variation::DiscreteVariation, x::Real) + if !(x in discrete_variation.values) + error(""Value not in elementary variation values."") + end + return (findfirst(isequal(x), discrete_variation.values) - 1) / (length(discrete_variation) - 1) +end + +function cdf(dv::DistributedVariation, x::Real) + out = cdf(dv.distribution, x) + if dv.flip + return 1 - out + end + return out +end + +cdf(ev::ElementaryVariation, ::Real) = error(""cdf not defined for $(typeof(ev))"") + +function variationLocation(xp::XMLPath) + if startswith(xp.xml_path[1], ""behavior_ruleset:name:"") + return :rulesets_collection + elseif xp.xml_path[1] == ""intracellulars"" + return :intracellular + elseif startswith(xp.xml_path[1], ""cell_patches:name:"") + return :ic_cell + elseif startswith(xp.xml_path[1], ""layer:ID:"") + return :ic_ecm + else + return :config + end +end + +################## Co-Variations ################## + +"""""" + CoVariation{T<:ElementaryVariation} <: AbstractVariation + +A co-variation of one or more variations. +Each must be of the same type, either `DiscreteVariation` or `DistributedVariation`. + +# Fields +- `variations::Vector{T}`: The variations that make up the co-variation. + +# Constructors +- `CoVariation(inputs::Vararg{Tuple{Vector{<:AbstractString},Distribution},N}) where {N}`: Create a co-variation from a vector of XML paths and distributions. +```julia +CoVariation((xml_path_1, d_1), (xml_path_2, d_2), ...) # d_i are distributions, e.g. `d_1 = Uniform(1, 2)` +``` +- `CoVariation(inputs::Vararg{Tuple{Vector{<:AbstractString},Vector},N}) where {N}`: Create a co-variation from a vector of XML paths and values. +```julia +CoVariation((xml_path_1, val_1), (xml_path_2, val_2), ...) # val_i are vectors of values, e.g. `val_1 = [0.1, 0.2]`, or singletons, e.g. `val_2 = 0.3` +``` +- `CoVariation(evs::Vector{ElementaryVariation})`: Create a co-variation from a vector of variations all the same type. +```julia +CoVariation([discrete_1, discrete_2, ...]) # all discrete variations and with the same number of values +CoVariation([distributed_1, distributed_2, ...]) # all distributed variations +``` +- `CoVariation(inputs::Vararg{T}) where {T<:ElementaryVariation}`: Create a co-variation from a variable number of variations all the same type. +```julia +CoVariation(discrete_1, discrete_2, ...) # all discrete variations and with the same number of values +CoVariation(distributed_1, distributed_2, ...) # all distributed variations +``` +"""""" +struct CoVariation{T<:ElementaryVariation} <: AbstractVariation + variations::Vector{T} + + function CoVariation(inputs::Vararg{Tuple{Vector{<:AbstractString},Distribution},N}) where {N} + variations = DistributedVariation[] + for (xml_path, distribution) in inputs + @assert xml_path isa Vector{<:AbstractString} ""xml_path must be a vector of strings"" + push!(variations, DistributedVariation(xml_path, distribution)) + end + return new{DistributedVariation}(variations) + end + + function CoVariation(inputs::Vararg{Tuple{Vector{<:AbstractString},Vector},N}) where {N} + variations = DiscreteVariation[] + n_discrete = -1 + for (xml_path, val) in inputs + n_vals = length(val) + if n_discrete == -1 + n_discrete = n_vals + else + @assert n_discrete == n_vals ""All discrete vals must have the same length"" + end + push!(variations, DiscreteVariation(xml_path, val)) + end + return new{DiscreteVariation}(variations) + end + + CoVariation(evs::Vector{DistributedVariation}) = return new{DistributedVariation}(evs) + + function CoVariation(evs::Vector{<:DiscreteVariation}) + @assert (length.(evs) |> unique |> length) == 1 ""All DiscreteVariations in a CoVariation must have the same length."" + return new{DiscreteVariation}(evs) + end + + function CoVariation(inputs::Vararg{T}) where {T<:ElementaryVariation} + return CoVariation(Vector{T}([inputs...])) + end +end + +variationTarget(cv::CoVariation) = variationTarget.(cv.variations) +variationLocation(cv::CoVariation) = variationLocation.(cv.variations) +columnName(cv::CoVariation) = columnName.(cv.variations) |> x -> join(x, "" AND "") + +function Base.length(cv::CoVariation) + return length(cv.variations[1]) +end + +function Base.show(io::IO, cv::CoVariation) + data_type = typeof(cv).parameters[1] + data_type_str = string(data_type) + n = length(data_type_str) + println(io, ""CoVariation ($(data_type_str)):"") + println(io, ""------------"" * ""-""^(n + 3)) + locations = variationLocation(cv) + unique_locations = unique(locations) + for location in unique_locations + println(io, "" Location: $location"") + location_inds = findall(isequal(location), locations) + for ind in location_inds + println(io, "" Variation $ind:"") + println(io, "" target: $(columnName(cv.variations[ind]))"") + if data_type == DiscreteVariation + println(io, "" values: $(variationValues(cv.variations[ind]))"") + elseif data_type == DistributedVariation + println(io, "" distribution: $(cv.variations[ind].distribution)"") + println(io, "" flip: $(cv.variations[ind].flip)"") + end + end + end +end + +################## Variation Dimension Functions ################## + +"""""" + addDomainVariationDimension!(evs::Vector{<:ElementaryVariation}, domain::NamedTuple) + +Deprecated function that pushes variations onto `evs` for each domain boundary named in `domain`. + +The names in `domain` can be flexibly named as long as they contain either `min` or `max` and one of `x`, `y`, or `z` (other than the the `x` in `max`). +It is not required to include all three dimensions and their boundaries. +The values for each boundary can be a single value or a vector of values. + +Instead of using this function, use `configPath(""x_min"")`, `configPath(""x_max"")`, etc. to create the XML paths and then use `DiscreteVariation` to create the variations. +Use a [`CoVariation`](@ref) if you want to vary any of these together. + +# Examples: +``` +evs = ElementaryVariation[] +addDomainVariationDimension!(evs, (x_min=-78, xmax=78, min_y=-30, maxy=[30, 60], z_max=10)) +"""""" +function addDomainVariationDimension!(evs::Vector{<:ElementaryVariation}, domain::NamedTuple) + Base.depwarn(""`addDomainVariationDimension!` is deprecated. Use `configPath(\""x_min\"")` etc. to create the XML paths and then use `DiscreteVariation` to create the variations."", :addDomainVariationDimension!, force=true) + dim_chars = [""z"", ""y"", ""x""] #! put x at the end to avoid prematurely matching with ""max"" + for (tag, value) in pairs(domain) + tag = String(tag) + if contains(tag, ""min"") + remaining_characters = replace(tag, ""min"" => """") + dim_side = ""min"" + elseif contains(tag, ""max"") + remaining_characters = replace(tag, ""max"" => """") + dim_side = ""max"" + else + msg = """""" + Invalid tag for a domain dimension: $(tag) + It must contain either 'min' or 'max' + """""" + throw(ArgumentError(msg)) + end + ind = findfirst(contains.(remaining_characters, dim_chars)) + @assert !isnothing(ind) ""Invalid domain dimension: $(tag)"" + dim_char = dim_chars[ind] + tag = ""$(dim_char)_$(dim_side)"" + xml_path = [""domain"", tag] + push!(evs, DiscreteVariation(xml_path, value)) #! do this to make sure that singletons and vectors are converted to vectors + end +end + +"""""" + addAttackRateVariationDimension!(evs::Vector{<:ElementaryVariation}, cell_definition::String, target_name::String, values::Vector{T} where T) + +Deprecated function that pushes a variation onto `evs` for the attack rate of a cell type against a target cell type. + +Instead of using this function, use `configPath(, ""attack"", )` to create the XML path and then use `DiscreteVariation` to create the variation. + +# Examples: +``` +addAttackRateVariationDimension!(evs, ""immune"", ""cancer"", [0.1, 0.2, 0.3]) +``` +"""""" +function addAttackRateVariationDimension!(evs::Vector{<:ElementaryVariation}, cell_definition::String, target_name::String, values::Vector{T} where T) + Base.depwarn(""`addAttackRateVariationDimension!` is deprecated. Use `configPath(, \""attack\"", )` to create the XML path and then use `DiscreteVariation` to create the variation."", :addAttackRateVariationDimension!, force=true) + xml_path = attackRatePath(cell_definition, target_name) + push!(evs, DiscreteVariation(xml_path, values)) +end + +"""""" + addCustomDataVariationDimension!(evs::Vector{<:ElementaryVariation}, cell_definition::String, field_name::String, values::Vector{T} where T) + +Deprecated function that pushes a variation onto `evs` for a custom data field of a cell type. + +Instead of using this function, use `configPath(, ""custom"", )` to create the XML path and then use `DiscreteVariation` to create the variation. + +# Examples: +``` +addCustomDataVariationDimension!(evs, ""immune"", ""perforin"", [0.1, 0.2, 0.3]) +``` +"""""" +function addCustomDataVariationDimension!(evs::Vector{<:ElementaryVariation}, cell_definition::String, field_name::String, values::Vector{T} where T) + Base.depwarn(""`addCustomDataVariationDimension!` is deprecated. Use `configPath(, \""custom\"", )` to create the XML path and then use `DiscreteVariation` to create the variation."", :addCustomDataVariationDimension!, force=true) + xml_path = customDataPath(cell_definition, field_name) + push!(evs, DiscreteVariation(xml_path, values)) +end + +################## Database Interface Functions ################## + +"""""" + addColumns(location::Symbol, folder_id::Int, evs::Vector{<:ElementaryVariation}) + +Add columns to the variations database for the given location and folder_id. +"""""" +function addColumns(location::Symbol, folder_id::Int, evs::Vector{<:ElementaryVariation}) + @assert all(variationLocation.(evs) .== location) ""All variations must be in the same location to do addColumns. Somehow found $(unique(variationLocation.(evs))) here."" + folder = inputFolderName(location, folder_id) + db_columns = locationVariationsDatabase(location, folder) + basenames = inputsDict()[location][""basename""] + basenames = basenames isa Vector ? basenames : [basenames] #! force basenames to be a vector to handle all the same way + basename_is_varied = inputsDict()[location][""varied""] .&& ([splitext(bn)[2] .== "".xml"" for bn in basenames]) #! the varied entry is either a singleton Boolean or a vector of the same length as basenames + basename_ind = findall(basename_is_varied .&& isfile.([joinpath(locationPath(location, folder), bn) for bn in basenames])) + @assert !isnothing(basename_ind) ""Folder $(folder) does not contain a valid $(location) file to support variations. The options are $(basenames[basename_is_varied])."" + @assert length(basename_ind) == 1 ""Folder $(folder) contains multiple valid $(location) files to support variations. The options are $(basenames[basename_is_varied])."" + + path_to_xml = joinpath(locationPath(location, folder), basenames[basename_ind[1]]) + + xps = variationTarget.(evs) + table_name = locationVariationsTableName(location) + + @debug validateParsBytes(db_columns, table_name) + + id_column_name = locationVariationIDName(location) + prev_par_column_names = tableColumns(table_name; db=db_columns) + filter!(x -> !(x in (id_column_name, ""par_key"")), prev_par_column_names) + varied_par_column_names = [columnName(xp.xml_path) for xp in xps] + + is_new_column = [!(varied_column_name in prev_par_column_names) for varied_column_name in varied_par_column_names] + if any(is_new_column) + new_column_names = varied_par_column_names[is_new_column] + new_column_data_types = evs[is_new_column] .|> sqliteDataType + xml_doc = parse_file(path_to_xml) + default_values_for_new = [getSimpleContent(xml_doc, xp.xml_path) for xp in xps[is_new_column]] + free(xml_doc) + for (new_column_name, data_type) in zip(new_column_names, new_column_data_types) + DBInterface.execute(db_columns, ""ALTER TABLE $(table_name) ADD COLUMN '$(new_column_name)' $(data_type);"") + end + + columns = join(""\"""" .* new_column_names .* ""\"""", "","") + placeholders = join([""?"" for _ in new_column_names], "","") + query = ""UPDATE $table_name SET ($columns) = ($placeholders);"" + stmt = SQLite.Stmt(db_columns, query) + DBInterface.execute(stmt, Tuple(default_values_for_new)) + + select_query = constructSelectQuery(table_name; selection=""$(tableIDName(table_name)), par_key"") + par_key_df = queryToDataFrame(select_query; db=db_columns) + + default_values_for_new[default_values_for_new.==""true""] .= ""1"" + default_values_for_new[default_values_for_new.==""false""] .= ""0"" + + new_bytes = reinterpret(UInt8, parse.(Float64, default_values_for_new)) + for row in eachrow(par_key_df) + id = row[1] + par_key = row[2] + append!(par_key, new_bytes) + DBInterface.execute(db_columns, ""UPDATE $table_name SET par_key = ? WHERE $(tableIDName(table_name)) = ?;"", (par_key, id)) + end + end + + @debug validateParsBytes(db_columns, table_name) + + static_par_column_names = deepcopy(prev_par_column_names) + previously_varied_names = varied_par_column_names[.!is_new_column] + filter!(x -> !(x in previously_varied_names), static_par_column_names) + + return static_par_column_names, varied_par_column_names +end + +"""""" + ColumnSetup + +A struct to hold the setup for the columns in a variations database. + +# Fields +- `db::SQLite.DB`: The database connection to the variations database. +- `table::String`: The name of the table in the database. +- `variation_id_name::String`: The name of the variation ID column in the table. +- `ordered_inds::Vector{Int}`: Indexes into the concatenated static and varied values to get the parameters in the order of the table columns (excluding the variation ID and par_key columns). +- `static_values::Vector{String}`: The static values for the columns that are not varied. +- `feature_str::String`: The string representation of the features (columns) in the table. +- `placeholders::String`: The string representation of the placeholders for the values in the table. +- `stmt_insert::SQLite.Stmt`: The prepared statement for inserting new rows into the table. +- `stmt_select::SQLite.Stmt`: The prepared statement for selecting existing rows from the table. +"""""" +struct ColumnSetup + db::SQLite.DB + table::String + variation_id_name::String + ordered_inds::Vector{Int} + static_values::Vector{String} + feature_str::String + placeholders::String + stmt_insert::SQLite.Stmt + stmt_select::SQLite.Stmt +end + +"""""" + addVariationRows(location::Symbol, folder_id::Int, evs::Vector{<:ElementaryVariation}, reference_variation_id::Int, all_varied_values::AbstractVector{<:AbstractVector}) + +Add new rows to the variations database for the given location and folder_id if they don't already exist. +"""""" +function addVariationRows(location::Symbol, folder_id::Int, evs::Vector{<:ElementaryVariation}, reference_variation_id::Int, all_varied_values::AbstractVector{<:AbstractVector}) + column_setup = setUpColumns(location, folder_id, evs, reference_variation_id) + + return [addVariationRow(column_setup, varied_values) for varied_values in all_varied_values] +end + +"""""" + addVariationRow(column_setup::ColumnSetup, varied_values::AbstractVector{String}) + +Add a new row to the variations database using the prepared statement. +If the row already exists, it returns the existing variation ID. +"""""" +function addVariationRow(column_setup::ColumnSetup, varied_values::AbstractVector{String}) + raw_pars = [column_setup.static_values; varied_values] + + pars_as_strs = copy(raw_pars) + pars_as_strs[pars_as_strs.==""true""] .= ""1"" + pars_as_strs[pars_as_strs.==""false""] .= ""0"" + pars_as_floats = parse.(Float64, pars_as_strs) + par_key = reinterpret(UInt8, pars_as_floats[column_setup.ordered_inds]) + params = Tuple([raw_pars; [par_key]]) #! Combine static and varied values into a single tuple for database insertion + new_id = stmtToDataFrame(column_setup.stmt_insert, params) |> x -> x[!, 1] + + new_added = length(new_id) == 1 + if !new_added + df = stmtToDataFrame(column_setup.stmt_select, params; is_row=true) + new_id = df[!, 1] + end + @debug validateParsBytes(column_setup.db, column_setup.table) + return new_id[1] +end + +"""""" + setUpColumns(location::Symbol, folder_id::Int, evs::Vector{<:ElementaryVariation}, reference_variation_id::Int) + +Set up the columns for the variations database for the given location and folder_id. +"""""" +function setUpColumns(location::Symbol, folder_id::Int, evs::Vector{<:ElementaryVariation}, reference_variation_id::Int) + static_par_column_names, varied_par_column_names = addColumns(location, folder_id, evs) + db_columns = locationVariationsDatabase(location, folder_id) + table_name = locationVariationsTableName(location) + variation_id_name = locationVariationIDName(location) + + if isempty(static_par_column_names) + static_values = String[] + table_features = String[] + else + query = constructSelectQuery(table_name, ""WHERE $(variation_id_name)=$(reference_variation_id);""; selection=join(""\"""" .* static_par_column_names .* ""\"""", "", "")) + static_values = queryToDataFrame(query; db=db_columns, is_row=true) |> x -> [string(c[1]) for c in eachcol(x)] |> Vector{String} + table_features = copy(static_par_column_names) + end + append!(table_features, varied_par_column_names) + + feature_str = join(""\"""" .* table_features .* ""\"""", "","") * "",par_key"" + placeholders = join([""?"" for _ in table_features], "","") * "",?"" + + stmt_insert = SQLite.Stmt(db_columns, ""INSERT OR IGNORE INTO $(table_name) ($(feature_str)) VALUES($placeholders) RETURNING $(variation_id_name);"") + where_str = ""WHERE ($(feature_str))=($(placeholders))"" + stmt_str = constructSelectQuery(table_name, where_str; selection=variation_id_name) + stmt_select = SQLite.Stmt(db_columns, stmt_str) + + column_to_full_index = Dict{String,Int}() + for (ind, col_name) in enumerate(table_features) + column_to_full_index[col_name] = ind + end + param_column_names = tableColumns(table_name; db=db_columns) #! ensure columns are up to date + filter!(x -> !(x in (variation_id_name, ""par_key"")), param_column_names) + ordered_inds = [column_to_full_index[col_name] for col_name in param_column_names] + + return ColumnSetup(db_columns, table_name, variation_id_name, ordered_inds, static_values, feature_str, placeholders, stmt_insert, stmt_select) +end + +################## Specialized Variations ################## + +"""""" + AddVariationMethod + +Abstract type for variation methods. + +# Subtypes +[`GridVariation`](@ref), [`LHSVariation`](@ref), [`SobolVariation`](@ref), [`RBDVariation`](@ref) + +# Methods +[`addVariations`](@ref), [`createTrial`](@ref), [`run`](@ref), +[`_createTrial`](@ref) +"""""" +abstract type AddVariationMethod end + +"""""" + GridVariation <: AddVariationMethod + +A variation method that creates a grid of all possible combinations of the values of the variations. + +# Examples +```jldoctest +julia> GridVariation() # the only method for GridVariation +GridVariation() +``` +"""""" +struct GridVariation <: AddVariationMethod end + +"""""" + LHSVariation <: AddVariationMethod + +A variation method that creates a Latin Hypercube Sample of the values of the variations. + +# Fields +Default values from constructors are shown. +- `n::Int`: The number of samples to take. +- `add_noise::Bool=false`: Whether to add noise to the samples or have them be in the center of the bins. +- `rng::AbstractRNG=Random.GLOBAL_RNG`: The random number generator to use. +- `orthogonalize::Bool=true`: Whether to orthogonalize the samples. See https://en.wikipedia.org/wiki/Latin_hypercube_sampling#:~:text=In%20orthogonal%20sampling + +# Examples +```jldoctest +julia> LHSVariation(4) # set `n` and use default values for the rest +LHSVariation(4, false, Random.TaskLocalRNG(), true) +``` +```jldoctest +using Random +LHSVariation(; n=16, add_noise=true, rng=MersenneTwister(1234), orthogonalize=false) +# output +LHSVariation(16, true, MersenneTwister(1234), false) +``` +"""""" +struct LHSVariation <: AddVariationMethod + n::Int + add_noise::Bool + rng::AbstractRNG + orthogonalize::Bool +end +LHSVariation(n; add_noise::Bool=false, rng::AbstractRNG=Random.GLOBAL_RNG, orthogonalize::Bool=true) = LHSVariation(n, add_noise, rng, orthogonalize) +LHSVariation(; n::Int=4, kwargs...) = LHSVariation(n; kwargs...) + +"""""" + SobolVariation <: AddVariationMethod + +A variation method that creates a Sobol sequence of the values of the variations. + +See [`generateSobolCDFs`](@ref) for more information on how the Sobol sequence is generated based on `n` and the other fields. + +See the GlobalSensitivity.jl package for more information on `RandomizationMethod`'s to use. + +# Fields +Default values from constructors are shown. +- `n::Int`: The number of samples to take. +- `n_matrices::Int=1`: The number of matrices to use in the Sobol sequence. +- `randomization::RandomizationMethod=NoRand()`: The randomization method to use on the deterministic Sobol sequence. +- `skip_start::Union{Missing, Bool, Int}=missing`: Whether to skip the start of the sequence. Missing means PhysiCellModelManager.jl will choose the best option. +- `include_one::Union{Missing, Bool}=missing`: Whether to include 1 in the sequence. Missing means PhysiCellModelManager.jl will choose the best option. + +# Examples +```jldoctest +julia> SobolVariation(9) # set `n` and use default values for the rest; will use [0, 0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875, 1] +SobolVariation(9, 1, QuasiMonteCarlo.NoRand(), missing, missing) +``` +```jldoctest +julia> SobolVariation(15; skip_start=true) # use [0.5, 0.25, 0.75, ..., 1/16, 3/16, ..., 15/16] +SobolVariation(15, 1, QuasiMonteCarlo.NoRand(), true, missing) +``` +```jldoctest +julia> SobolVariation(4; include_one=true) # use [0, 0.5, 1] and one of [0.25, 0.75] +SobolVariation(4, 1, QuasiMonteCarlo.NoRand(), missing, true) +``` +"""""" +struct SobolVariation <: AddVariationMethod + n::Int + n_matrices::Int + randomization::RandomizationMethod + skip_start::Union{Missing,Bool,Int} + include_one::Union{Missing,Bool} +end +SobolVariation(n::Int; n_matrices::Int=1, randomization::RandomizationMethod=NoRand(), skip_start::Union{Missing,Bool,Int}=missing, include_one::Union{Missing,Bool}=missing) = SobolVariation(n, n_matrices, randomization, skip_start, include_one) +SobolVariation(; pow2::Int=1, n_matrices::Int=1, randomization::RandomizationMethod=NoRand(), skip_start::Union{Missing,Bool,Int}=missing, include_one::Union{Missing,Bool}=missing) = SobolVariation(2^pow2, n_matrices, randomization, skip_start, include_one) + +"""""" + RBDVariation <: AddVariationMethod + +A variation method that creates a Random Balance Design of the values of the variations. + +This creates `n` sample points where the values in each dimension are uniformly distributed. +By default, this will use Sobol sequences (see [`SobolVariation`](@ref)) to create the sample points. +If `use_sobol` is `false`, it will use random permutations of uniformly spaced points for each dimension. + +# Fields +Default values from constructors are shown. +- `n::Int`: The number of samples to take. +- `rng::AbstractRNG=Random.GLOBAL_RNG`: The random number generator to use. +- `use_sobol::Bool=true`: Whether to use Sobol sequences to create the sample points. +Do not set these next two fields unless you know what you are doing. Let PhysiCellModelManager.jl compute them. +- `pow2_diff::Union{Missing, Int}=missing`: The difference between `n` and the nearest power of 2. Missing means PhysiCellModelManager.jl will compute it if using Sobol sequences. +- `num_cycles::Union{Missing, Int, Rational}=missing`: The number of cycles to use in the Sobol sequence. Missing means PhysiCellModelManager.jl will set it. + +# Examples +```jldoctest +julia> PhysiCellModelManager.RBDVariation(4) # set `n` and use default values for the rest +RBDVariation(4, Random.TaskLocalRNG(), true, 0, 1//2) +``` +```jldoctest +julia> PhysiCellModelManager.RBDVariation(4; use_sobol=false) # use random permutations of uniformly spaced points +RBDVariation(4, Random.TaskLocalRNG(), false, missing, 1//1) +``` +"""""" +struct RBDVariation <: AddVariationMethod + n::Int + rng::AbstractRNG + use_sobol::Bool + pow2_diff::Union{Missing,Int} + num_cycles::Rational + + function RBDVariation(n::Int, rng::AbstractRNG, use_sobol::Bool, pow2_diff::Union{Missing,Int}, num_cycles::Union{Missing,Int,Rational}) + if use_sobol + k = log2(n) |> round |> Int #! nearest power of 2 to n + if ismissing(pow2_diff) + pow2_diff = n - 2^k + else + @assert pow2_diff == n - 2^k ""pow2_diff must be n - 2^k for RBDVariation with Sobol sequence"" + end + @assert abs(pow2_diff) <= 1 ""n must be within 1 of a power of 2 for RBDVariation with Sobol sequence"" + if ismissing(num_cycles) + num_cycles = 1 // 2 + else + @assert num_cycles == 1 // 2 ""num_cycles must be 1//2 for RBDVariation with Sobol sequence"" + end + else + pow2_diff = missing #! not used in this case + if ismissing(num_cycles) + num_cycles = 1 + else + @assert num_cycles == 1 ""num_cycles must be 1 for RBDVariation with random sequence"" + end + end + return new(n, rng, use_sobol, pow2_diff, num_cycles) + end +end + +RBDVariation(n::Int; rng::AbstractRNG=Random.GLOBAL_RNG, use_sobol::Bool=true, pow2_diff=missing, num_cycles=missing) = RBDVariation(n, rng, use_sobol, pow2_diff, num_cycles) + +"""""" + AddVariationsResult + +Abstract type for the result of adding variations to a set of inputs. + +# Subtypes +[`AddGridVariationsResult`](@ref), [`AddLHSVariationsResult`](@ref), [`AddSobolVariationsResult`](@ref), [`AddRBDVariationsResult`](@ref) +"""""" +abstract type AddVariationsResult end + +"""""" + addVariations(method::AddVariationMethod, inputs::InputFolders, avs::Vector{<:AbstractVariation}, reference_variation_id::VariationID=VariationID(inputs)) + +Add variations to the inputs using the specified [`AddVariationMethod`](@ref) and the variations in `avs`. +"""""" +function addVariations(method::AddVariationMethod, inputs::InputFolders, avs::Vector{<:AbstractVariation}, reference_variation_id::VariationID=VariationID(inputs)) + pv = ParsedVariations(avs) + return addVariations(method, inputs, pv, reference_variation_id) +end + +"""""" + LocationParsedVariations + +A struct that holds the variations and their indices into a vector of [`AbstractVariation`](@ref)s for a specific location. + +# Fields +- `variations::Vector{<:ElementaryVariation}`: The variations for the location. +- `indices::Vector{Int}`: The indices of the variations in the vector of [`AbstractVariation`](@ref)s. +"""""" +struct LocationParsedVariations + variations::Vector{<:ElementaryVariation} + indices::Vector{Int} + function LocationParsedVariations(variations::Vector{<:ElementaryVariation}, indices::Vector{Int}) + @assert length(variations) == length(indices) ""variations and indices must have the same length"" + return new(variations, indices) + end +end + +"""""" + ParsedVariations + +A struct that holds the parsed variations and their sizes for all locations. + +# Fields +- `sz::Vector{Int}`: The size of each variation, i.e., the number of values in each variation. +- `variations::Vector{<:AbstractVariation}`: The variations used to create the parsed variations. +- `location_parsed_variations::NamedTuple`: A named tuple of [`LocationParsedVariations`](@ref)s for each location. +"""""" +struct ParsedVariations + sz::Vector{Int} + variations::Vector{<:AbstractVariation} + + location_parsed_variations::NamedTuple + + function ParsedVariations(avs::Vector{<:AbstractVariation}) + sz = length.(avs) + + location_variations_dict = Dict{Symbol,Any}() + for location in projectLocations().varied + location_variations_dict[location] = (ElementaryVariation[], Int[]) + end + + for (i, av) in enumerate(avs) + if av isa ElementaryVariation + av = CoVariation(av) #! wrap it in a covariation + end + @assert av isa CoVariation ""Everything at this point should have been converted to a CoVariation"" + for ev in av.variations + push!(location_variations_dict[variationLocation(ev)][1], ev) + push!(location_variations_dict[variationLocation(ev)][2], i) + end + end + for (_, variation_indices) in values(location_variations_dict) + @assert issorted(variation_indices) ""Variation indices must be sorted after parsing."" + end + location_parsed_variations = [location => LocationParsedVariations(variations, variation_indices) for (location, (variations, variation_indices)) in pairs(location_variations_dict)] |> NamedTuple + return new(sz, avs, location_parsed_variations) + end +end + +Base.getindex(pv::ParsedVariations, location::Symbol)::LocationParsedVariations = pv.location_parsed_variations[location] + +################## Grid Variations ################## + +"""""" + AddGridVariationsResult <: AddVariationsResult + +A struct that holds the result of adding grid variations to a set of inputs. + +# Fields +- `all_variation_ids::AbstractArray{VariationID}`: The variation IDs for all the variations added. +"""""" +struct AddGridVariationsResult <: AddVariationsResult + all_variation_ids::AbstractArray{VariationID} +end + +function addVariations(::GridVariation, inputs::InputFolders, pv::ParsedVariations, reference_variation_id::VariationID) + @assert all(pv.sz .!= -1) ""GridVariation only works with DiscreteVariations"" + varied_locations = projectLocations().varied + all_location_variation_ids = [addLocationGridVariations(location, inputs, pv, reference_variation_id) for location in varied_locations] + return [([location => loc_var_ids[i] for (location, loc_var_ids) in zip(varied_locations, all_location_variation_ids)] |> VariationID) for i in eachindex(all_location_variation_ids[1])] |> AddGridVariationsResult +end + +"""""" + addLocationGridVariations(location::Symbol, inputs::InputFolders, pv::ParsedVariations, reference_variation_id::VariationID) + +Add grid variations for a specific location to the inputs. Used in [`addVariations`](@ref) with a [`GridVariation`](@ref) method. +"""""" +function addLocationGridVariations(location::Symbol, inputs::InputFolders, pv::ParsedVariations, reference_variation_id::VariationID) + if isempty(pv[location].variations) + return fill(reference_variation_id[location], pv.sz...) + end + discrete_variations = Vector{DiscreteVariation}(pv[location].variations) + out = gridToDB(location, discrete_variations, inputs[location].id, reference_variation_id[location], pv[location].indices) + dim_szs = [d in pv[location].indices ? pv.sz[d] : 1 for d in eachindex(pv.sz)] + out = reshape(out, dim_szs...) + + other_dims = [dim_szs[d] == 1 ? pv.sz[d] : 1 for d in eachindex(pv.sz)] + return repeat(out, other_dims...) +end + +"""""" + gridToDB(evs::Vector{<:DiscreteVariation}, folder_id::Int, reference_variation_id::Int) + +Adds a grid of variations to the database from the vector of [`DiscreteVariation`](@ref)s. +"""""" +function gridToDB(evs::Vector{<:DiscreteVariation}, folder_id::Int, reference_variation_id::Int) + locations = variationLocation.(evs) + @assert all(locations .== locations[1]) ""All variations must be in the same location to do gridToDB. Instead got $(locations)."" + location = locations[1] + return gridToDB(location, evs, folder_id, reference_variation_id, 1:length(evs)) +end + +function gridToDB(location::Symbol, evs::Vector{<:DiscreteVariation}, folder_id::Int, reference_variation_id::Int, ev_dims::AbstractVector{Int}) + all_varied_values = [] + for ev_dim in unique(ev_dims) + #! each entry in all_varied_values corresponds to a dimension being varied + #! all_varied_values[1], e.g., is a matrix where each column corresponds to a parameter varied in dimension 1 + #! each column in that matrix is the values that parameter can take on + dim_indices = findall(ev_dim .== ev_dims) + push!(all_varied_values, reduce(hcat, variationValues.(string, evs[dim_indices]))) + end + + #! record the size of each dimension being varied + sz_variations = size.(all_varied_values, 1) + + #! each column corresponds to one parameter vector + #! I is a CartesianIndex, meaning it tracks the row of each matrix in all_varied_values + #! for each dimension being varied (d), get the row I.I[d] from the matrix (all_varied_values[d][I.I[d], :]) + #! and concatenate (vcat) these rows to form the ith parameter vector + values_mat = hcat((reduce(vcat, (all_varied_values[d][I.I[d], :] for d in eachindex(I.I))) for (i, I) in enumerate(CartesianIndices(Dims(sz_variations))))...) + values_iterator = eachcol(values_mat) #! each column is a parameter vector + + return reshape(addVariationRows(location, folder_id, evs, reference_variation_id, values_iterator), sz_variations...) +end + +################## Latin Hypercube Sampling Functions ################## + +"""""" + orthogonalLHS(k::Int, d::Int) + +Generate an orthogonal Latin Hypercube Sample in `d` dimensions with `k` subdivisions in each dimension, requiring `n=k^d` samples. +"""""" +function orthogonalLHS(k::Int, d::Int) + n = k^d + lhs_inds = zeros(Int, (n, d)) + for i in 1:d + n_bins = k^(i - 1) #! number of bins from previous dims (a bin has sampled points that are in the same subelement up through i-1 dim and need to be separated in subsequent dims) + bin_size = k^(d - i + 1) #! number of sampled points in each bin + if i == 1 + lhs_inds[:, 1] = 1:n + else + bin_inds_gps = [(j - 1) * bin_size .+ (1:bin_size) |> collect for j in 1:n_bins] #! the indices belonging to each of the bins (this relies on the sorting step below to easily find which points are currently in the same box and need to be separated along the ith dimension) + for pt_ind = 1:bin_size #! pick ith coordinate for each point in the bin; each iter here will work up the ith coordinates assigning one to each bin at each iter + ind = zeros(Int, n_bins) #! indices where the next set of ith coordinates will go + for (j, bin_inds) in enumerate(bin_inds_gps) #! pick a random, remaining element for each bin + rand_ind_of_ind = rand(1:length(bin_inds)) #! pick the index of a remaining index + ind[j] = popat!(bin_inds, rand_ind_of_ind) #! get the random index and remove it so we don't pick it again + end + lhs_inds[ind, i] = shuffle(1:n_bins) .+ (pt_ind - 1) * n_bins #! for the selected inds, shuffle the next set of ith coords into them + end + end + lhs_inds[:, 1:i] = sortslices(lhs_inds[:, 1:i], dims=1, by=x -> (x ./ (n / k) .|> ceil .|> Int)) #! sort the found values so that sampled points in the same box upon projection into the 1:i dims are adjacent + end + return lhs_inds +end + +"""""" + generateLHSCDFs(n::Int, d::Int[; add_noise::Bool=false, rng::AbstractRNG=Random.GLOBAL_RNG, orthogonalize::Bool=true]) + +Generate a Latin Hypercube Sample of the Cumulative Distribution Functions (CDFs) for `n` samples in `d` dimensions. + +# Arguments +- `n::Int`: The number of samples to take. +- `d::Int`: The number of dimensions to sample. +- `add_noise::Bool=false`: Whether to add noise to the samples or have them be in the center of the bins. +- `rng::AbstractRNG=Random.GLOBAL_RNG`: The random number generator to use. +- `orthogonalize::Bool=true`: Whether to orthogonalize the samples, if possible. See https://en.wikipedia.org/wiki/Latin_hypercube_sampling#:~:text=In%20orthogonal%20sampling + +# Returns +- `cdfs::Matrix{Float64}`: The CDFs for the samples. Each row is a sample and each column is a dimension (corresponding to a feature). + +# Examples +```jldoctest +cdfs = PhysiCellModelManager.generateLHSCDFs(4, 2) +size(cdfs) +# output +(4, 2) +``` +"""""" +function generateLHSCDFs(n::Int, d::Int; add_noise::Bool=false, rng::AbstractRNG=Random.GLOBAL_RNG, orthogonalize::Bool=true) + cdfs = (Float64.(1:n) .- (add_noise ? rand(rng, Float64, n) : 0.5)) / n #! permute below for each parameter separately + k = n^(1 / d) |> round |> Int + if orthogonalize && (n == k^d) + #! then good to do the orthogonalization + lhs_inds = orthogonalLHS(k, d) + else + lhs_inds = reduce(hcat, [shuffle(rng, 1:n) for _ in 1:d]) #! each shuffled index vector is added as a column + end + return cdfs[lhs_inds] +end + +"""""" + AddLHSVariationsResult <: AddVariationsResult + +A struct that holds the result of adding LHS variations to a set of inputs. + +# Fields +- `all_variation_ids::AbstractArray{VariationID}`: The variation IDs for all the variations added. +"""""" +struct AddLHSVariationsResult <: AddVariationsResult + all_variation_ids::AbstractArray{VariationID} +end + +function addVariations(lhs_variation::LHSVariation, inputs::InputFolders, pv::ParsedVariations, reference_variation_id::VariationID) + d = length(pv.sz) + cdfs = generateLHSCDFs(lhs_variation.n, d; add_noise=lhs_variation.add_noise, rng=lhs_variation.rng, orthogonalize=lhs_variation.orthogonalize) + all_location_variation_ids = [addLocationCDFVariations(location, inputs, pv, reference_variation_id, cdfs) for location in projectLocations().varied] + return [([location => loc_var_ids[i] for (location, loc_var_ids) in zip(projectLocations().varied, all_location_variation_ids)] |> VariationID) for i in eachindex(all_location_variation_ids[1])] |> AddLHSVariationsResult +end + +"""""" + addLocationCDFVariations(location::Symbol, inputs::InputFolders, pv::ParsedVariations, reference_variation_id::VariationID, cdfs::AbstractMatrix{Float64}) + +Add variations for a specific location to the inputs. Used in [`addVariations`](@ref) with the [`LHSVariation`](@ref), [`SobolVariation`](@ref), and [`RBDVariation`](@ref) methods. +"""""" +function addLocationCDFVariations(location::Symbol, inputs::InputFolders, pv::ParsedVariations, reference_variation_id::VariationID, cdfs::AbstractMatrix{Float64}) + if isempty(pv[location].variations) + #! if the location is not varied, just return the reference variation id + return fill(reference_variation_id[location], size(cdfs, 1)) + end + return cdfsToVariations(location, pv, inputs[location].id, reference_variation_id[location], cdfs) +end + +################## Sobol Sequence Sampling Functions ################## + +"""""" + generateSobolCDFs(n::Int, d::Int[; n_matrices::Int=1, randomization::RandomizationMethod=NoRand(), skip_start::Union{Missing, Bool, Int}=missing, include_one::Union{Missing, Bool}=missing) + +Generate `n_matrices` Sobol sequences of the Cumulative Distribution Functions (CDFs) for `n` samples in `d` dimensions. + +The subsequence of the Sobol sequence is chosen based on the value of `n` and the value of `include_one`. +If it is one less than a power of 2, e.g. `n=7`, skip 0 and start from 0.5. +Otherwise, it will always start from 0. +If it is one more than a power of 2, e.g. `n=9`, include 1 (unless `include_one` is `false`). + +The `skip_start` field can be used to control this by skipping the start of the sequence. +If `skip_start` is `true`, skip to the smallest consecutive subsequence with the same denominator that has at least `n` elements. +If `skip_start` is `false`, start from 0. +If `skip_start` is an integer, skip that many elements in the sequence, .e.g., `skip_start=1` skips 0 and starts at 0.5. + +If you want to include 1 in the sequence, set `include_one` to `true`. +If you want to exlude 1 (in the case of `n=9`, e.g.), set `include_one` to `false`. + +# Arguments +- `n::Int`: The number of samples to take. +- `d::Int`: The number of dimensions to sample. +- `n_matrices::Int=1`: The number of matrices to use in the Sobol sequence (effectively, the dimension of the sample is `d` x `n_matrices`). +- `randomization::RandomizationMethod=NoRand()`: The randomization method to use on the deterministic Sobol sequence. See GlobalSensitivity.jl. +- `skip_start::Union{Missing, Bool, Int}=missing`: Whether to skip the start of the sequence. Missing means PhysiCellModelManager.jl will choose the best option. +- `include_one::Union{Missing, Bool}=missing`: Whether to include 1 in the sequence. Missing means PhysiCellModelManager.jl will choose the best option. + +# Returns +- `cdfs::Array{Float64, 3}`: The CDFs for the samples. The first dimension is the features, the second dimension is the matrix, and the third dimension is the sample points. + +# Examples +```jldoctest +cdfs = PhysiCellModelManager.generateSobolCDFs(11, 3) +size(cdfs) +# output +(3, 1, 11) +``` +```jldoctest +cdfs = PhysiCellModelManager.generateSobolCDFs(7, 5; n_matrices=2) +size(cdfs) +# output +(5, 2, 7) +``` +"""""" +function generateSobolCDFs(n::Int, d::Int; n_matrices::Int=1, T::Type=Float64, randomization::RandomizationMethod=NoRand(), skip_start::Union{Missing,Bool,Int}=missing, include_one::Union{Missing,Bool}=missing) + s = Sobol.SobolSeq(d * n_matrices) + if ismissing(skip_start) #! default to this + if ispow2(n + 1) #! then n = 2^k - 1 + skip_start = 1 #! skip the first point (0) + else + skip_start = false #! don't skip the first point (0) + if ispow2(n - 1) #! then n = 2^k + 1 + include_one |= ismissing(include_one) #! unless otherwise specified, assume the +1 is to get the boundary 1 included as well + elseif ispow2(n) #! then n = 2^k + nothing #! including 0, grab the first 2^k points + else #! not within 1 of a power of 2, just start at the beginning? + nothing + end + end + end + n_draws = n - (include_one === true) #! if include_one is true, then we need to draw n-1 points and then append 1 to the end + if skip_start == false #! false or 0 + cdfs = randomize(reduce(hcat, [zeros(T, n_matrices * d), [next!(s) for i in 1:n_draws-1]...]), randomization) #! n_draws-1 because the SobolSeq already skips 0 + else + cdfs = Matrix{T}(undef, d * n_matrices, n_draws) + num_to_skip = skip_start === true ? ((1 << (floor(Int, log2(n_draws - 1)) + 1))) : skip_start + num_to_skip -= 1 #! the SobolSeq already skips 0 + for _ in 1:num_to_skip + Sobol.next!(s) + end + for col in eachcol(cdfs) + Sobol.next!(s, col) + end + cdfs = randomize(cdfs, randomization) + end + if include_one === true #! cannot compare missing==true, but can make this comparison + cdfs = hcat(cdfs, ones(T, d * n_matrices)) + end + return reshape(cdfs, (d, n_matrices, n)) +end + +generateSobolCDFs(sobol_variation::SobolVariation, d::Int) = generateSobolCDFs(sobol_variation.n, d; n_matrices=sobol_variation.n_matrices, randomization=sobol_variation.randomization, skip_start=sobol_variation.skip_start, include_one=sobol_variation.include_one) + +"""""" + AddSobolVariationsResult <: AddVariationsResult + +A struct that holds the result of adding Sobol variations to a set of inputs. + +# Fields +- `all_variation_ids::AbstractArray{VariationID}`: The variation IDs for all the variations added. +- `cdfs::Array{Float64, 3}`: The CDFs for the samples. The first dimension is the varied parameters, the second dimension is the design matrices, and the third dimension is the samples. +"""""" +struct AddSobolVariationsResult <: AddVariationsResult + all_variation_ids::AbstractArray{VariationID} + cdfs::Array{Float64,3} +end + +function addVariations(sobol_variation::SobolVariation, inputs::InputFolders, pv::ParsedVariations, reference_variation_id::VariationID) + d = length(pv.sz) + cdfs = generateSobolCDFs(sobol_variation, d) #! cdfs is (d, sobol_variation.n_matrices, sobol_variation.n) + cdfs_reshaped = reshape(cdfs, (d, sobol_variation.n_matrices * sobol_variation.n)) #! reshape to (d, sobol_variation.n_matrices * sobol_variation.n) so that each column is a sobol sample + cdfs_reshaped = cdfs_reshaped' #! transpose so that each row is a sobol sample + all_location_variation_ids = [addLocationCDFVariations(location, inputs, pv, reference_variation_id, cdfs_reshaped) for location in projectLocations().varied] + all_variation_ids = [([location => loc_var_ids[i] for (location, loc_var_ids) in zip(projectLocations().varied, all_location_variation_ids)] |> VariationID) for i in eachindex(all_location_variation_ids[1])] + all_variation_ids = reshape(all_variation_ids, (sobol_variation.n_matrices, sobol_variation.n)) |> permutedims + return AddSobolVariationsResult(all_variation_ids, cdfs) +end + +################## Random Balance Design Sampling Functions ################## + +"""""" + generateRBDCDFs(rbd_variation::RBDVariation, d::Int) + +Generate CDFs for a Random Balance Design (RBD) in `d` dimensions. + +# Arguments +- `rbd_variation::RBDVariation`: The RBD variation method to use. +- `d::Int`: The number of dimensions to sample. + +# Returns +- `cdfs::Matrix{Float64}`: The CDFs for the samples. Each row is a sample and each column is a dimension (corresponding to a parameter / parameter group from a [`CoVariation`](@ref)). +- `rbd_sorting_inds::Matrix{Int}`: A `n_samples` x `d` matrix that gives the ordering of the dimensions to use for the RBD. The order along each column is necessary for computing the RBD, sorting the simulations along the periodic curve. +"""""" +function generateRBDCDFs(rbd_variation::RBDVariation, d::Int) + if rbd_variation.use_sobol + println(""Using Sobol sequence for RBD."") + if rbd_variation.n == 1 + rbd_sorting_inds = fill(1, (1, d)) + cdfs = 0.5 .+ zeros(Float64, (1, d)) + else + @assert !ismissing(rbd_variation.pow2_diff) ""pow2_diff must be calculated for RBDVariation constructor with Sobol sequence. How else could we get here?"" + @assert rbd_variation.num_cycles == 1 // 2 ""num_cycles must be 1//2 for RBDVariation constructor with Sobol sequence. How else could we get here?"" + #! vary along a half period of the sine function since that will cover all CDF values (compare to the full period below). in computing the RBD, we will + #! / __\ /\ <- \ is the flipped version of the / in this line of commented code + #! / / \/ <- \ is the flipped version of the / in this line of commented code + if rbd_variation.pow2_diff == -1 + skip_start = 1 + elseif rbd_variation.pow2_diff == 0 + skip_start = true + else + skip_start = false + end + cdfs = generateSobolCDFs(rbd_variation.n, d; n_matrices=1, randomization=NoRand(), skip_start=skip_start, include_one=rbd_variation.pow2_diff == 1) #! rbd_sorting_inds here is (d, n_matrices=1, rbd_variation.n) + cdfs = reshape(cdfs, d, rbd_variation.n) |> permutedims #! cdfs is now (rbd_variation.n, d) + rbd_sorting_inds = reduce(hcat, map(sortperm, eachcol(cdfs))) + end + else + @assert rbd_variation.num_cycles == 1 ""num_cycles must be 1 for RBDVariation constructor with random sequence. How else could we get here?"" + #! vary along the full period of the sine function and do fft as normal + #! /\ + #! \/ + sorted_s_values = range(-π, stop=π, length=rbd_variation.n + 1) |> collect + pop!(sorted_s_values) + permuted_s_values = [sorted_s_values[randperm(rbd_variation.rng, rbd_variation.n)] for _ in 1:d] |> x -> reduce(hcat, x) + cdfs = 0.5 .+ asin.(sin.(permuted_s_values)) ./ π + rbd_sorting_inds = reduce(hcat, map(sortperm, eachcol(permuted_s_values))) + end + return cdfs, rbd_sorting_inds +end + +function addVariations(rbd_variation::RBDVariation, inputs::InputFolders, pv::ParsedVariations, reference_variation_id::VariationID) + d = length(pv.sz) + cdfs, rbd_sorting_inds = generateRBDCDFs(rbd_variation, d) + all_location_variation_ids = [addLocationCDFVariations(location, inputs, pv, reference_variation_id, cdfs) for location in projectLocations().varied] + variation_matrices = [createSortedRBDMatrix(vids, rbd_sorting_inds) for vids in all_location_variation_ids] + all_variation_ids = [([location => loc_var_ids[i] for (location, loc_var_ids) in zip(projectLocations().varied, all_location_variation_ids)] |> VariationID) for i in eachindex(all_location_variation_ids[1])] + location_variation_ids_dict = [location => variation_matrices[i] for (i, location) in enumerate(projectLocations().varied)] |> Dict + return AddRBDVariationsResult(all_variation_ids, location_variation_ids_dict) +end + +"""""" + createSortedRBDMatrix(variation_ids::Vector{Int}, rbd_sorting_inds::AbstractMatrix{Int}) + +Create a sorted matrix of variation IDs based on the RBD sorting indices. +This ensures that the orderings for each parameter stored for the RBD calculations. +"""""" +function createSortedRBDMatrix(variation_ids::Vector{Int}, rbd_sorting_inds::AbstractMatrix{Int}) + variations_matrix = Array{Int}(undef, size(rbd_sorting_inds)) + for (vm_col, par_sorting_inds) in zip(eachcol(variations_matrix), eachcol(rbd_sorting_inds)) + vm_col .= variation_ids[par_sorting_inds] + end + return variations_matrix +end + +"""""" + AddRBDVariationsResult <: AddVariationsResult + +A struct that holds the result of adding Sobol variations to a set of inputs. + +# Fields +- `all_variation_ids::AbstractArray{VariationID}`: The variation IDs for all the variations added. +- `location_variation_ids_dict::Dict{Symbol, Matrix{Int}}`: A dictionary of the variation IDs for each location. The keys are the locations and the values are the variation IDs for that location. +"""""" +struct AddRBDVariationsResult <: AddVariationsResult + all_variation_ids::AbstractArray{VariationID} + location_variation_ids_dict::Dict{Symbol,Matrix{Int}} +end + +################## Sampling Helper Functions ################## + +"""""" + cdfsToVariations(location::Symbol, pv::ParsedVariations, folder_id::Int, reference_variation_id::Int, cdfs::AbstractMatrix{Float64}) + +Convert the CDFs to variation IDs in the database. +"""""" +function cdfsToVariations(location::Symbol, pv::ParsedVariations, folder_id::Int, reference_variation_id::Int, cdfs::AbstractMatrix{Float64}) + #! CDFs come in as nsamples x ndims matrix. If any parameters are co-varying, they correspond to a single column in the CDFs matrix. + #! This function goes parameter-by-parameter, identifying the column it is associated with and then computing the new values for that parameter. + #! These are the `new_value` vectors (of length nsamples) that are pushed into `new_values`. + #! Converting this into a matrix (using `reduce(hcat, new_values)`) gives us the final varied values, and we use `eachrow` to iterate over the rows. + evs = pv[location].variations + + new_values = [] + ev_dims = pv[location].indices + for (ev, col_ind) in zip(evs, ev_dims) + new_value = variationValues(string, ev, cdfs[:, col_ind]) #! ok, all the new values for the given parameter + push!(new_values, new_value) + end + + all_varied_values = reduce(hcat, new_values) |> eachrow + + return addVariationRows(location, folder_id, evs, reference_variation_id, all_varied_values) +end +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/components.jl",".jl","14741","339","using LightXML, TOML, AutoHashEquals + +export assembleIntracellular!, PhysiCellComponent + +"""""" + PhysiCellComponent + +A struct to hold the information about a component that is used to assemble an input of PhysiCell. + +The `type` and `name` are the only fields that are compared for equality. +The `type` represents the type of component that it is. +Currently, only ""roadrunner"" is supported. +The `name` is the name of the file inside the `components/type/` directory. +The `id` is the id of the component, which will be -1 to indicate it is not yet set. +The `id` is used to link which cell definition(s) use which component(s). + +# Fields +- `type::String`: The type of the component (e.g., ""roadrunner"", ""dfba"", ""maboss""). +- `name::String`: The name of the component (e.g., ""component.xml""). +- `id::Int`: The id of the component (e.g., 1, 2, 3). This is used to link which cell definition(s) use which component(s). A value of -1 indicates that the id is not yet set. + +# Examples +```jldoctest +julia> PhysiCellComponent(""roadrunner"", ""test.xml"") +PhysiCellComponent(""roadrunner"", ""test.xml"", -1) +``` +```jldoctest +component = PhysiCellComponent(""roadrunner"", ""test.xml"") +PhysiCellComponent(component, 78) # set the id to 78; users should not need to do this +# output +PhysiCellComponent(""roadrunner"", ""test.xml"", 78) +``` +"""""" +@auto_hash_equals fields = (type, name) struct PhysiCellComponent #! only compare the name and type for equality + type::String #! type of the file (currently going to be ""roadrunner"", ""dfba"", or ""maboss"") + name::String #! name of the file + id::Int #! id of the component (will be -1 to indicate it is not yet known) + + function PhysiCellComponent(type::String, name::String) + return new(type, name, -1) + end + + function PhysiCellComponent(component::PhysiCellComponent, id::Int) + return new(component.type, component.name, id) + end +end + +pathFromComponents(component::PhysiCellComponent) = joinpath(component.type, component.name) + +function assembleIntracellular!(cell_to_components_dict::Dict{String,<:Union{PhysiCellComponent,Vector{PhysiCellComponent}}}; kwargs...) + cell_to_vec_components_dict = Dict{String,Vector{PhysiCellComponent}}() + for (cell_type, components) in cell_to_components_dict + if components isa PhysiCellComponent + cell_to_vec_components_dict[cell_type] = [components] + else + cell_to_vec_components_dict[cell_type] = components + end + end + return assembleIntracellular!(cell_to_vec_components_dict; kwargs...) +end + +"""""" + assembleIntracellular!(cell_to_components_dict::Dict{String,Vector{PhysiCellComponent}}; name::String=""assembled"", skip_db_insert::Bool=false) + +Assembles the intracellular components for the given cell types into a single file. + +First, check if the components have been previously assembled. +If so, return that folder name. +If not, create a new folder and save the components there as a single file along with the assembly manifest; finally, update the database with the new folder. + +# Arguments +- `cell_to_components_dict::Dict{String,Vector{PhysiCellComponent}}`: A dictionary mapping cell types to their components. + - The keys are the cell type names (e.g., ""T_cell"", ""B_cell""). + - The values can be either a single [`PhysiCellComponent`](@ref) or a vector of `PhysiCellComponent`s. +- `name::String`: The name of the folder to create (default is ""assembled""). +- `skip_db_insert::Bool`: If true, skip the database insert (default is false). Skipped when importing a project. Users should not need to set this. + +# Returns +- `folder::String`: The name of the folder where the components were assembled. +"""""" +function assembleIntracellular!(cell_to_components_dict::Dict{String,Vector{PhysiCellComponent}}; name::String=""assembled"", skip_db_insert::Bool=false) + assertInitialized() + #! get all components to assign IDs + unique_components = PhysiCellComponent[] + for components in values(cell_to_components_dict) + for component in components + if component in unique_components + continue + end + push!(unique_components, component) + end + end + temp_ids = Dict{PhysiCellComponent,Int}() + for (i, c) in enumerate(unique_components) + temp_ids[c] = i + end + + #! create the assembly record first to compare and then to save (if assembling now) + assembly_manifest = Dict{String,Dict{String,Any}}() + assembly_manifest[""cell_definitions""] = Dict{String,Any}() + assembly_manifest[""intracellulars""] = Dict{String,Any}() + for (cell_type, components) in cell_to_components_dict + if isempty(components) + continue + end + assembly_manifest[""cell_definitions""][cell_type] = Int[] + for component in components + id_str = string(temp_ids[component]) + push!(assembly_manifest[""cell_definitions""][cell_type], temp_ids[component]) + assembly_manifest[""intracellulars""][id_str] = Dict{String,Any}() + assembly_manifest[""intracellulars""][id_str][""type""] = component.type + assembly_manifest[""intracellulars""][id_str][""name""] = component.name + end + end + + #! compare against previously-assembled intracellulars + path_to_folder = intracellularFolder(assembly_manifest) + if !isnothing(path_to_folder) + updateIntracellularComponentIDs!(cell_to_components_dict, path_to_folder) + return splitpath(path_to_folder)[end] + end + + #! pick a folder name, adding a number if it already exists + path_to_folders = locationPath(:intracellular) + folder = name + n = 0 + while isdir(joinpath(path_to_folders, folder)) + n += 1 + folder = ""$(name)_$(n)"" + end + path_to_folder = joinpath(path_to_folders, folder) + mkdir(path_to_folder) + + #! since we're here and creating a new folder, it is possible that prevoiusly defined ids could conflict, so let's no rely on them. + for (cell_type, components) in cell_to_components_dict + updated_components = PhysiCellComponent[] + for component in components + push!(updated_components, PhysiCellComponent(component, temp_ids[component])) + end + cell_to_components_dict[cell_type] = updated_components + end + + xml_doc = XMLDocument() + xml_root = create_root(xml_doc, ""PhysiCell_intracellular_mappings"") + + #! create cell definitions element + e_cell_definitions = new_child(xml_root, ""cell_definitions"") + for (cell_type, components) in cell_to_components_dict + e_cell_definition = new_child(e_cell_definitions, ""cell_definition"") + set_attribute(e_cell_definition, ""name"", cell_type) + e_intracellular_ids = new_child(e_cell_definition, ""intracellular_ids"") + for component in components + e_intracellular_id = new_child(e_intracellular_ids, ""ID"") + set_content(e_intracellular_id, string(component.id)) + end + end + + #! create intracellulars element + e_intracellulars = new_child(xml_root, ""intracellulars"") + for (component, i) in temp_ids + e_intracellular = new_child(e_intracellulars, ""intracellular"") + set_attribute(e_intracellular, ""ID"", string(i)) + set_attribute(e_intracellular, ""type"", component.type) + + path_to_component_xml = joinpath(dataDir(), ""components"", pathFromComponents(component)) + component_xml_doc = parse_file(path_to_component_xml) + component_xml_root = root(component_xml_doc) + add_child(e_intracellular, component_xml_root) + free(component_xml_doc) + end + + save_file(xml_doc, joinpath(path_to_folder, ""intracellular.xml"")) + free(xml_doc) + + #! record the assembly of the document + open(joinpath(path_to_folder, ""assembly.toml""), ""w"") do io + TOML.print(io, assembly_manifest) + end + + #! make sure the database is updated, variations.db intialized + if isInitialized() && !skip_db_insert + insertFolder(:intracellular, splitpath(folder)[end]) + end + + #! return just the folder name + return folder +end + +"""""" + intracellularFolder(assembly_manifest::Dict) + +Get the folder that contains the intracellular assembly manifest that is equivalent to the given assembly manifest, if one exists. + +If no such folder exists, return nothing. +"""""" +function intracellularFolder(assembly_manifest::Dict) + path_to_location_folders = locationPath(:intracellular) + + for folder in readdir(path_to_location_folders; join=true, sort=false) + #! only look in folders that have an assembly.toml file + if !isdir(folder) || !isfile(joinpath(folder, ""assembly.toml"")) + continue + end + previous_assembly_manifest = TOML.parsefile(joinpath(folder, ""assembly.toml"")) + if intracellularAssemblyManifestsEquivalent(previous_assembly_manifest, assembly_manifest) + return folder + end + end + return nothing +end + +"""""" + intracellularAssemblyManifestsEquivalent(A::Dict, B::Dict) + +Compare two intracellular assembly manifests to see if they are equivalent. + +Two manifests may assign different IDs to the same components. +This function compares the component files to see if the manifests are equivalent. +"""""" +function intracellularAssemblyManifestsEquivalent(A::Dict, B::Dict) + + function _get_cell_to_components_dict(d::Dict) + cell_to_components_dict = Dict{String,Vector{PhysiCellComponent}}() + for (cell_type, ids) in d[""cell_definitions""] + cell_to_components_dict[cell_type] = PhysiCellComponent[] + for id in string.(ids) + component = PhysiCellComponent(d[""intracellulars""][id][""type""], d[""intracellulars""][id][""name""]) #! all will have PhysiCellComponent id -1 + @assert !(component in cell_to_components_dict[cell_type]) ""Duplicate component in cell type $cell_type: $component"" + push!(cell_to_components_dict[cell_type], component) + end + end + return cell_to_components_dict + end + + dict_assembly_A = _get_cell_to_components_dict(A) + dict_assembly_B = _get_cell_to_components_dict(B) + all_cell_types = Set(union(keys(dict_assembly_A), keys(dict_assembly_B))) + + for cell_type in all_cell_types + #! first check if the cell type actually has components in A or B + has_intracellular_A = haskey(dict_assembly_A, cell_type) && !isempty(dict_assembly_A[cell_type]) + has_intracellular_B = haskey(dict_assembly_B, cell_type) && !isempty(dict_assembly_B[cell_type]) + if !has_intracellular_A && !has_intracellular_B + continue + end + + #! if one has the cell type and the other does not, then these are not the same (⊻ = XOR) + if (has_intracellular_A ⊻ has_intracellular_B) + return false + end + + #! otherwise, both have it, check that these are the same + if Set{PhysiCellComponent}(dict_assembly_A[cell_type]) != Set{PhysiCellComponent}(dict_assembly_B[cell_type]) + return false + end + end + return true +end + +"""""" + updateIntracellularComponentIDs!(cell_to_components_dict::Dict{String,Vector{PhysiCellComponent}}, path_to_folder::String) + +Update the IDs of the components in the given dictionary to match those in the assembly manifest in the given folder. +"""""" +function updateIntracellularComponentIDs!(cell_to_components_dict::Dict{String,Vector{PhysiCellComponent}}, path_to_folder::String) + path_to_file = joinpath(path_to_folder, ""assembly.toml"") + @assert isfile(path_to_file) ""Assembly file does not exist: $path_to_file"" + assembly_manifest = TOML.parsefile(path_to_file) + + for (cell_type, components) in cell_to_components_dict + if isempty(components) + continue + end + new_components = PhysiCellComponent[] + for component in components + component_id = findComponentID(assembly_manifest, component) + push!(new_components, PhysiCellComponent(component, parse(Int, component_id))) + end + cell_to_components_dict[cell_type] = new_components + end +end + +"""""" + findComponentID(assembly_manifest::Dict, component::PhysiCellComponent) + +Find the ID of the given component in the assembly manifest. +"""""" +function findComponentID(assembly_manifest::Dict, component::PhysiCellComponent) + for (id, component_dict) in assembly_manifest[""intracellulars""] + if component_dict[""name""] == component.name && component_dict[""type""] == component.type + return id + end + end + @assert false ""Component not found in assembly manifest: $component"" +end + +"""""" + disassembleIntracellular(path_to_xml::String) + +Disassemble the intracellular XML file into separate files for each intracellular component. + +The files will be saved next to the varied XML file with the following naming convention: +`__ID_.xml` +where `` is the base name of the input XML file, `` is the cell type that uses the component, `` is the ID of the component, and `` is the type of the component (e.g., ""roadrunner""). +"""""" +function disassembleIntracellular(path_to_xml::String) + folder, base_filename = splitdir(path_to_xml) + basename = splitext(base_filename)[1] + filename_fn = (cell, id, type) -> joinpath(folder, ""$(basename)_$(cell)_ID$(id)_$(type).xml"") + xml_doc = parse_file(path_to_xml) + cell_definitions_element = retrieveElement(xml_doc, [""cell_definitions""]) + intracellular_to_id_map = Dict{Int,Vector{String}}() + for cell_definition_element in get_elements_by_tagname(cell_definitions_element, ""cell_definition"") + name = attribute(cell_definition_element, ""name"") + intracellular_ids_element = find_element(cell_definition_element, ""intracellular_ids"") + for id_element in get_elements_by_tagname(intracellular_ids_element, ""ID"") + id = parse(Int, content(id_element)) + if !haskey(intracellular_to_id_map, id) + intracellular_to_id_map[id] = String[] + end + push!(intracellular_to_id_map[id], name) + end + end + + intracellulars_element = retrieveElement(xml_doc, [""intracellulars""]) + for intracellular_element in get_elements_by_tagname(intracellulars_element, ""intracellular"") + id = parse(Int, attribute(intracellular_element, ""ID"")) + type = attribute(intracellular_element, ""type"") + sbml_root = find_element(intracellular_element, ""sbml"") + intracellular_xml_doc = XMLDocument() + set_root(intracellular_xml_doc, sbml_root) + for cell in intracellular_to_id_map[id] + filename = filename_fn(cell, id, type) + save_file(intracellular_xml_doc, filename) + end + free(intracellular_xml_doc) + end + free(xml_doc) +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/deletion.jl",".jl","23352","482","using Dates + +export deleteSimulation, deleteSimulations, deleteSimulationsByStatus, resetDatabase + +"""""" + deleteSimulations(simulation_ids::AbstractVector{<:Union{Integer,Missing}}; delete_supers::Bool=true, filters::Dict{<:AbstractString, <:Any}=Dict{AbstractString, Any}()) + +Deletes the simulations with the input IDs from the database and from the `data/outputs/simulations` folder. + +Works with a vector of simulation IDs, a single simulation ID, a vector of `Simulation`s or a single `Simulation`. +If `delete_supers` is `true`, it will also delete any monads, samplings, and trials that no longer have any simulations associated with them. +It is recommended to leave this to `true` to keep the database clean. +The `filters` argument allows for additional SQLite conditions to be added to the `WHERE` clause of the SQLite query. Use this only after inspecting the `simulations` table in the `data/pcmm.db` database. + Note: `deleteSimulation` is an alias for `deleteSimulations`. + +# Examples +``` +deleteSimulations(1:3) +deleteSimulations(4) +deleteSimulations(1:100; filters=Dict(""config_id"" => 1)) # delete simulations with IDs 1 to 100 that have config_id = 1 +``` +"""""" +function deleteSimulations(simulation_ids::AbstractVector{<:Union{Integer,Missing}}; delete_supers::Bool=true, filters::Dict{<:AbstractString, <:Any}=Dict{AbstractString, Any}()) + assertInitialized() + simulation_ids = Vector(simulation_ids) #! filter! does not work on AbstractRange, such as `simulation_ids = 1:3` + filter!(x -> !ismissing(x), simulation_ids) + where_stmt, params = buildWhereClause(""simulations"", simulation_ids, filters) + stmt_str = constructSelectQuery(""simulations"", where_stmt) + sim_df = stmtToDataFrame(stmt_str, params) + simulation_ids = sim_df.simulation_id #! update based on the constraints added + DBInterface.execute(centralDB(),""DELETE FROM simulations WHERE simulation_id IN ($(join(simulation_ids,"","")));"") + + for row in eachrow(sim_df) + rm_hpc_safe(trialFolder(Simulation, row.simulation_id); force=true, recursive=true) + + for (location, location_dict) in pairs(inputsDict()) + if !any(location_dict[""varied""]) + continue + end + id_name = locationIDName(location) + row_id = row[id_name] + folder = inputFolderName(location, row_id) + result_df = constructSelectQuery( + ""simulations"", + ""WHERE $(id_name) = $(row_id) AND $(locationVariationIDName(location)) = $(row[locationVariationIDName(location)])""; + selection=""COUNT(*)"" + ) |> queryToDataFrame + if result_df.var""COUNT(*)""[1] == 0 #! if no other simulations use this input file, then delete it + rm_hpc_safe(joinpath(locationPath(location, folder), locationVariationsTableName(location), ""$(location)_variation_$(row[locationVariationIDName(location)]).xml""); force=true) + end + end + end + + if !delete_supers + return nothing + end + + monad_ids = constructSelectQuery(""monads""; selection=""monad_id"") |> queryToDataFrame |> x -> x.monad_id + monad_ids_to_delete = Int[] + for monad_id in monad_ids + monad_simulation_ids = constituentIDs(Monad, monad_id) + if !any(x -> x in simulation_ids, monad_simulation_ids) #! if none of the monad simulation ids are among those to be deleted, then nothing to do here + continue + end + filter!(x -> !(x in simulation_ids), monad_simulation_ids) + if isempty(monad_simulation_ids) + push!(monad_ids_to_delete, monad_id) + else + recordConstituentIDs(Monad, monad_id, monad_simulation_ids) + end + end + if !isempty(monad_ids_to_delete) + deleteMonad(monad_ids_to_delete; delete_subs=false, delete_supers=true) + end + return nothing +end + +"""""" + buildWhereClause(table_name::String, ids::Vector{<:Integer}, filters::Dict{<:AbstractString, <:Any}; db::SQLite.DB=centralDB()) + +Builds a `WHERE` clause for SQL queries based on the provided IDs and filters. + +Following PCMM conventions, the ID of the table is expected to be named `\""\$(x)_id\""`, where `x` is the table name with the end `s` removed (e.g., `simulation_id` for the `simulations` table). + +# Arguments +- `table_name`: The name of the table to check for valid columns. +- `ids`: A vector of IDs to include in the `WHERE` clause. +- `filters`: A dictionary of additional filters to apply to the `WHERE` clause. Default is an empty dictionary. + The keys should be valid column names and the values should be the values to filter by. + +# Keyword Arguments +- `db`: The SQLite database connection to use. Default is the central database. + +# Examples +```julia-repl +julia> PhysiCellModelManager.buildWhereClause(""simulations"", [1, 2, 3], Dict(""config_id"" => 1)) +(""WHERE simulation_id IN (1,2,3) AND config_id = ?"", Any[1]) +``` +"""""" +function buildWhereClause(table_name::String, ids::Vector{<:Integer}, filters::Dict{<:AbstractString, <:Any}; db::SQLite.DB=centralDB()) + id_name = tableIDName(table_name) + valid_column_names = tableColumns(table_name; db=db) + @assert columnsExist(keys(filters) |> collect, valid_column_names) ""Invalid filter keys for table $(table_name): $(collect(setdiff(keys(filters), valid_column_names))). Valid columns are: $(valid_column_names)."" + clauses = [""$id_name IN ($(join(ids, "","")))""; [""$col = ?"" for col in keys(filters)]] + params = values(filters) |> collect + return ""WHERE "" * join(clauses, "" AND ""), params +end + +deleteSimulations(simulation_id::Int; kwargs...) = deleteSimulations([simulation_id]; kwargs...) +deleteSimulations(simulations::Vector{Simulation}; kwargs...) = deleteSimulations([sim.id for sim in simulations]; kwargs...) +deleteSimulations(simulation::Simulation; kwargs...) = deleteSimulations([simulation]; kwargs...) + +"""""" + deleteSimulation(args...; kwargs...) + +Alias for [`deleteSimulations`](@ref). +"""""" +deleteSimulation = deleteSimulations #! alias + +"""""" + deleteAllSimulations(; kwargs...) + +Delete all simulations. See [`deleteSimulations`](@ref) for the meaning of the keyword arguments. +"""""" +deleteAllSimulations(; kwargs...) = simulationIDs() |> x -> deleteSimulations(x; kwargs...) + +"""""" + deleteMonad(monad_ids::AbstractVector{<:Integer}; delete_subs::Bool=true, delete_supers::Bool=true) + +Delete monads from the database by monad ID. + +# Arguments +- `monad_ids`: list of monad IDs to delete. Can also pass an `Integer`. +- `delete_subs`: If `delete_subs` is `true`, will further delete the simulations corresponding to the monad. +- `delete_supers`: If `delete_supers` is `true`, will further delete any samplings that no longer have associated monads after the deletion. +"""""" +function deleteMonad(monad_ids::AbstractVector{<:Integer}; delete_subs::Bool=true, delete_supers::Bool=true) + DBInterface.execute(centralDB(),""DELETE FROM monads WHERE monad_id IN ($(join(monad_ids,"","")));"") + simulation_ids_to_delete = Int[] + for monad_id in monad_ids + if delete_subs + append!(simulation_ids_to_delete, constituentIDs(Monad, monad_id)) + end + rm_hpc_safe(trialFolder(Monad, monad_id); force=true, recursive=true) + end + if !isempty(simulation_ids_to_delete) + deleteSimulations(simulation_ids_to_delete; delete_supers=false) + end + + if !delete_supers + return nothing + end + + sampling_ids = constructSelectQuery(""samplings""; selection=""sampling_id"") |> queryToDataFrame |> x -> x.sampling_id + sampling_ids_to_delete = Int[] + for sampling_id in sampling_ids + sampling_monad_ids = constituentIDs(Sampling, sampling_id) + if !any(x -> x in monad_ids, sampling_monad_ids) #! if none of the sampling monad ids are among those to be deleted, then nothing to do here + continue + end + filter!(x -> !(x in monad_ids), sampling_monad_ids) + if isempty(sampling_monad_ids) + push!(sampling_ids_to_delete, sampling_id) + else + recordConstituentIDs(Sampling, sampling_id, sampling_monad_ids) + end + end + if !isempty(sampling_ids_to_delete) + deleteSampling(sampling_ids_to_delete; delete_subs=false, delete_supers=true) + end + return nothing +end + +deleteMonad(monad_id::Int; delete_subs::Bool=true, delete_supers::Bool=true) = deleteMonad([monad_id]; delete_subs=delete_subs, delete_supers=delete_supers) + +"""""" + deleteSampling(sampling_ids::AbstractVector{<:Integer}; delete_subs::Bool=true, delete_supers::Bool=true) + +Delete samplings from the database by sampling ID. + +# Arguments +- `sampling_ids`: list of sampling IDs to delete. Can also pass an `Integer`. +- `delete_subs`: If `delete_subs` is `true`, will further delete the monads corresponding to the sampling. +- `delete_supers`: If `delete_supers` is `true`, will further delete any trials that no longer have associated samplings after the deletion. +"""""" +function deleteSampling(sampling_ids::AbstractVector{<:Integer}; delete_subs::Bool=true, delete_supers::Bool=true) + DBInterface.execute(centralDB(),""DELETE FROM samplings WHERE sampling_id IN ($(join(sampling_ids,"","")));"") + monad_ids_to_delete = Int[] + for sampling_id in sampling_ids + if delete_subs + append!(monad_ids_to_delete, constituentIDs(Sampling, sampling_id)) + end + rm_hpc_safe(trialFolder(Sampling, sampling_id); force=true, recursive=true) + end + if !isempty(monad_ids_to_delete) + all_sampling_ids = constructSelectQuery(""samplings""; selection=""sampling_id"") |> queryToDataFrame |> x -> x.sampling_id + for sampling_id in all_sampling_ids + if sampling_id in sampling_ids + continue #! skip the samplings to be deleted (we want to delete their monads) + end + #! this is then a sampling that we are not deleting, do not delete their monads!! + monad_ids = constituentIDs(Sampling, sampling_id) + filter!(x -> !(x in monad_ids), monad_ids_to_delete) #! if a monad to delete is in the sampling to keep, then do not delete it!! (or more in line with logic here: if a monad marked for deletion is not in this sampling we are keeping, then leave it in the deletion list) + end + deleteMonad(monad_ids_to_delete; delete_subs=true, delete_supers=false) + end + + if !delete_supers + return nothing + end + + trial_ids = constructSelectQuery(""trials""; selection=""trial_id"") |> queryToDataFrame |> x -> x.trial_id + trial_ids_to_delete = Int[] + for trial_id in trial_ids + trial_sampling_ids = constituentIDs(Trial, trial_id) + if !any(x -> x in sampling_ids, trial_sampling_ids) #! if none of the trial sampling ids are among those to be deleted, then nothing to do here + continue + end + filter!(x -> !(x in sampling_ids), trial_sampling_ids) + if isempty(trial_sampling_ids) + push!(trial_ids_to_delete, trial_id) + else + recordConstituentIDs(Trial, trial_id, trial_sampling_ids) + end + end + if !isempty(trial_ids_to_delete) + deleteTrial(trial_ids_to_delete; delete_subs=false) + end + return nothing +end + +deleteSampling(sampling_id::Int; delete_subs::Bool=true, delete_supers::Bool=true) = deleteSampling([sampling_id]; delete_subs=delete_subs, delete_supers=delete_supers) + +"""""" + deleteTrial(trial_ids::AbstractVector{<:Integer}; delete_subs::Bool=true) + +Delete trials from the database by trial ID. + +# Arguments +- `trial_ids`: list of trial IDs to delete. Can also pass an `Integer`. +- `delete_subs`: If `delete_subs` is `true`, will further delete the samplings corresponding to the trials. +"""""" +function deleteTrial(trial_ids::AbstractVector{<:Integer}; delete_subs::Bool=true) + DBInterface.execute(centralDB(),""DELETE FROM trials WHERE trial_id IN ($(join(trial_ids,"","")));"") + sampling_ids_to_delete = Int[] + for trial_id in trial_ids + if delete_subs + append!(sampling_ids_to_delete, constituentIDs(Trial, trial_id)) + end + rm_hpc_safe(trialFolder(Trial, trial_id); force=true, recursive=true) + end + if !isempty(sampling_ids_to_delete) + all_trial_ids = constructSelectQuery(""trials""; selection=""trial_id"") |> queryToDataFrame |> x -> x.trial_id + for trial_id in all_trial_ids + if trial_id in trial_ids + continue #! skip the trials to be deleted (we want to delete their samplings) + end + #! this is then a trial that we are not deleting, do not delete their samplings!! + sampling_ids = constituentIDs(Trial, trial_id) + filter!(x -> !(x in sampling_ids), sampling_ids_to_delete) #! if a sampling to delete is in the trial to keep, then do not delete it!! (or more in line with logic here: if a sampling marked for deletion is not in this trial we are keeping, then leave it in the deletion list) + end + deleteSampling(sampling_ids_to_delete; delete_subs=true, delete_supers=false) + end + return nothing +end + +deleteTrial(trial_id::Int; delete_subs::Bool=true) = deleteTrial([trial_id]; delete_subs=delete_subs) + +"""""" + resetDatabase() + +Reset the database (after user confirmation) by deleting all simulations, monads, samplings, and trials. + +All the base inputs files will be kept, so previously run scripts should still work as expected. +If the user aborts the reset, the user will then be asked if they want to continue with the script. + +# Keyword Arguments +- `force_reset::Bool`: If `true`, skips the user confirmation prompt. Default is `false`. +- `force_continue::Bool`: If `true`, skips the user confirmation prompt for continuing with the script after aborting the reset. Default is `false`. +"""""" +function resetDatabase(; force_reset::Bool=false, force_continue::Bool=false) + assertInitialized() + if !force_reset + #! prompt user to confirm + println(""Are you sure you want to reset the database? (y/n)"") + response = readline() + if response != ""y"" #! make user be very specific about resetting + println(""\tYou entered '$response'.\n\tResetting the database has been cancelled."") + if !force_continue + println(""\nDo you want to continue with the script? (y/n)"") + response = readline() + if response != ""y"" #! make user be very specific about continuing + println(""\tYou entered '$response'.\n\tThe script has been cancelled."") + error(""Script cancelled."") + end + println(""You entered '$response'.\n\tThe script will continue."") + end + return + end + end + for folder in [""simulations"", ""monads"", ""samplings"", ""trials""] + rm_hpc_safe(joinpath(dataDir(), ""outputs"", folder); force=true, recursive=true) + end + + for (location, location_dict) in pairs(inputsDict()) + if !any(location_dict[""varied""]) + continue + end + path_to_location = locationPath(location) + for folder in (readdir(path_to_location, sort=false, join=true) |> filter(x->isdir(x))) + resetFolder(location, folder) + end + folders = constructSelectQuery(locationTableName(location); selection=""folder_name"") |> queryToDataFrame |> x -> x.folder_name + for folder in folders + resetFolder(location, joinpath(path_to_location, folder)) + end + end + + for custom_code_folder in (readdir(locationPath(:custom_code), sort=false, join=true) |> filter(x->isdir(x))) + files = [baseToExecutable(""project""), ""compilation.log"", ""compilation.err"", ""macros.txt""] + for file in files + rm_hpc_safe(joinpath(custom_code_folder, file); force=true) + end + end + + custom_code_folders = constructSelectQuery(""custom_codes""; selection=""folder_name"") |> queryToDataFrame |> x -> x.folder_name + for custom_code_folder in custom_code_folders + rm_hpc_safe(joinpath(locationPath(:custom_code, custom_code_folder), baseToExecutable(""project"")); force=true) + end + + rm_hpc_safe(""$(centralDB().file)""; force=true) + initializeDatabase() + return nothing +end + +"""""" + resetFolder(location::Symbol, folder::String) + +Reset a specific folder in the database for a given location, removing the variations database and variations folder. + +# Arguments +- `location`: The location of the folder to reset. +- `folder`: The name of the folder to reset. +"""""" +function resetFolder(location::Symbol, folder::String) + inputs_dict_entry = inputsDict()[location] + path_to_folder = locationPath(location, folder) + if !isdir(path_to_folder) + return + end + if inputs_dict_entry[""basename""] isa Vector + #! keep the most elementary of these and remove the rest + ind = findfirst(x -> joinpath(path_to_folder, x) |> isfile, inputs_dict_entry[""basename""]) + if isnothing(ind) + return #! probably should not end up here, but it could happen if a location folder was created but never populated with the base file + end + for base_file in inputs_dict_entry[""basename""][ind+1:end] + rm_hpc_safe(joinpath(path_to_folder, base_file); force=true) + end + end + rm_hpc_safe(joinpath(path_to_folder, locationVariationsDBName(location)); force=true) + rm_hpc_safe(joinpath(path_to_folder, locationVariationsTableName(location)); force=true, recursive=true) +end + +"""""" + deleteSimulationsByStatus(status_codes_to_delete::Vector{String}=[""Failed""]; user_check::Bool=true) + deleteSimulationsByStatus(status_code_to_delete::String; user_check::Bool=true) + +Delete simulations from the database based on their status codes. + +The list of possible status codes is: ""Not Started"", ""Queued"", ""Running"", ""Completed"", ""Failed"". + +# Arguments +- `status_codes_to_delete::Vector{String}`: A vector of status codes for which simulations should be deleted. Default is `[""Failed""]`. + Can also pass a single status code as a `String`. +- `user_check::Bool`: If `true`, prompts the user for confirmation before deleting simulations. Default is `true`. +"""""" +function deleteSimulationsByStatus(status_codes_to_delete::Vector{String}=[""Failed""]; user_check::Bool=true) + assertInitialized() + df = """""" + SELECT simulations.simulation_id, simulations.status_code_id, status_codes.status_code + FROM simulations + JOIN status_codes + ON simulations.status_code_id = status_codes.status_code_id; + """""" |> queryToDataFrame + + for status_code in status_codes_to_delete + simulation_ids = df.simulation_id[df.status_code .== status_code] + if isempty(simulation_ids) + continue + end + if user_check + println(""Are you sure you want to delete all $(length(simulation_ids)) simulations with status code '$status_code'? (y/n)"") + response = readline() + println(""You entered '$response'."") + if response != ""y"" #! make user be very specific about resetting + println(""\tDeleting simulations with status code '$status_code' has been cancelled."") + continue + end + end + println(""\tDeleting $(length(simulation_ids)) simulations with status code '$status_code'."") + deleteSimulations(simulation_ids) + end +end + +function deleteSimulationsByStatus(status_code_to_delete::String; kwargs...) + deleteSimulationsByStatus([status_code_to_delete]; kwargs...) +end + +"""""" + eraseSimulationIDFromConstituents(simulation_id::Int[; monad_id::Union{Missing,Int}=missing]) + +Erase a simulation ID from the `simulations.csv` file of the monad it belongs to. + +If `monad_id` is not provided, the function will infer it from the simulation ID. +If the monad contains only the given simulation ID, the monad will be deleted. +This is used when running simulations if they error so that the monads no longer rely on them, but the simulation output can still be checked. +"""""" +function eraseSimulationIDFromConstituents(simulation_id::Int; monad_id::Union{Missing,Int}=missing) + if ismissing(monad_id) + query = constructSelectQuery(""simulations"", ""WHERE simulation_id = $(simulation_id)"") + df = queryToDataFrame(query) + all_id_features = [locationIDName(loc) for loc in projectLocations().varied] #! projectLocations().varied is a Tuple, so doing locationIDName.(projectLocations().varied) makes a Tuple, not a Vector + add_id_values = [df[1, id_feature] for id_feature in all_id_features] + all_variation_id_features = [locationVariationIDName(loc) for loc in projectLocations().varied] #! projectLocations().varied is a Tuple, so doing locationVariationIDName.(projectLocations().varied) makes a Tuple, not a Vector + all_variation_id_values = [df[1, variation_id_feature] for variation_id_feature in all_variation_id_features] + all_features = [all_id_features; all_variation_id_features] + all_values = [add_id_values; all_variation_id_values] + + @assert columnsExist(all_features, ""monads"") ""The columns $(all_features) do not all exist in the 'monads' table. Cannot erase simulation ID from constituents."" + placeholders = join([""?"" for _ in all_features], "","") + where_str = ""WHERE ($(join(all_features, "", ""))) = ($placeholders)"" + stmt_str = constructSelectQuery(""monads"", where_str; selection=""monad_id"") + df = stmtToDataFrame(stmt_str, all_values; is_row=true) + + monad_id = df.monad_id[1] + end + simulation_ids = constituentIDs(Monad, monad_id) + index = findfirst(x->x==simulation_id, simulation_ids) + if isnothing(index) + return #! maybe this could happen? so let's check just in case + end + if length(simulation_ids)==1 + #! then this was the only simulation in this monad; delete the monad and any samplings, etc. that depend on it + #! do not delete the given simulation from the database so that we can check the output files + deleteMonad(monad_id; delete_subs=false, delete_supers=true) + return + end + deleteat!(simulation_ids, index) + recordConstituentIDs(Monad, monad_id, simulation_ids) +end + +"""""" + rm_hpc_safe(path::String; force::Bool=false, recursive::Bool=false) + +Remove files and take care if on an HPC since the NFS filesystem can leave behind extra files. + +If on an HPC, move deleted files into the hidden directory `data/.trash/` in a time-stamped folder. +"""""" +function rm_hpc_safe(path::String; force::Bool=false, recursive::Bool=false) + if !pcmm_globals.run_on_hpc + rm(path; force=force, recursive=recursive) + return + end + if !ispath(path) + return + end + #! NFS filesystem could stop the deletion by putting a lock on the folder or something + src = path + path_rel_to_data = replace(path, ""$(dataDir())/"" => """") + date_time = Dates.format(now(),""yymmdd"") + initial_dest = joinpath(dataDir(), "".trash"", ""data-$(date_time)"", path_rel_to_data) + main_path, file_ext = splitext(initial_dest) + suffix = """" + path_to_dest(main_path, suffix, file_ext) = suffix == """" ? ""$(main_path)$(file_ext)"" : ""$(main_path)-$(suffix)$(file_ext)"" + while ispath(path_to_dest(main_path, suffix, file_ext)) + suffix = suffix == """" ? ""1"" : string(parse(Int, suffix) + 1) + end + dest = path_to_dest(main_path, suffix, file_ext) + mkpath(dirname(dest)) + mv(src, dest; force=force) +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/analysis/pcf.jl",".jl","15692","340","using PairCorrelationFunction, RecipesBase + +import PairCorrelationFunction: pcf + +@compat public pcf + +"""""" + PCMMPCFResult + +A struct to hold the results of the pair correlation function (PCF) calculation. + +The start and end radii for each annulus are stored in the `radii` field. +Thus, there is one more radius than there are annuli, i.e. `length(radii) == size(g, 1) + 1`. +Each column of `g` corresponds to a time point in the `time` field, hence `size(g, 2) == length(time)`. + +# Fields +- `time::Vector{Float64}`: The time points at which the PCF was calculated. +- `pcf_result::PairCorrelationFunction.PCFResult`: The result of the PCF calculation. + +# Example +```jldoctest +using PairCorrelationFunction +time = 12.0 +radii = [0.0, 1.0, 2.0] +g = [0.5, 1.2] +PhysiCellModelManager.PCMMPCFResult(time, PairCorrelationFunction.PCFResult(radii, g)) +# output +PCMMPCFResult: + Time: 12.0 + Radii: 0.0 - 2.0 with 2 annuli, Δr = 1.0 + g: 0.5 - 1.2 (min - max) +``` +```jldoctest +using PairCorrelationFunction +time = [12.0; 24.0; 36.0] +radii = [0.0, 1.0, 2.0] +g = [0.5 0.6 0.4; 1.2 1.15 1.4] +PhysiCellModelManager.PCMMPCFResult(time, PairCorrelationFunction.PCFResult(radii, g)) +# output +PCMMPCFResult: + Time: 12.0 - 36.0 (n = 3) + Radii: 0.0 - 2.0 with 2 annuli, Δr = 1.0 + g: 0.4 - 1.4 (min - max) +``` +"""""" +struct PCMMPCFResult + time::Vector{Float64} + pcf_result::PairCorrelationFunction.PCFResult + + function PCMMPCFResult(time::Float64, result::PairCorrelationFunction.PCFResult) + @assert size(result.g, 2) == 1 ""If time is a single value, g must be a vector or a matrix with one column. Found $(size(result.g, 2)) columns."" + return new([time], result) + end + + function PCMMPCFResult(time::Vector{Float64}, result::PairCorrelationFunction.PCFResult) + @assert size(result.g, 2) == length(time) ""If time is a vector, g must be a matrix with matching number of columns. Found $(length(time)) timepoints but $(size(result.g, 2)) columns."" + return new(time, result) + end +end + +function Base.hcat(gs::Vararg{PCMMPCFResult}) + time = reduce(vcat, [g.time for g in gs]) + pcf_result = hcat([g.pcf_result for g in gs]...) + return PCMMPCFResult(time, pcf_result) +end + +function Base.show(io::IO, p::PCMMPCFResult) + println(io, ""PCMMPCFResult:"") + if length(p.time) == 1 + println(io, "" Time: $(p.time[1])"") + else + println(io, "" Time: $(p.time[1]) - $(p.time[end]) (n = $(length(p.time)))"") + end + print(io, "" Radii: $(p.pcf_result.radii[1]) - $(p.pcf_result.radii[end]) with $(length(p.pcf_result.radii)-1) annuli"") + rs = p.pcf_result.radii + drs = diff(rs) + display_tol = 0.01 #! if the radii deltas are within 1%, just display it as being the same for simplicity + if all(drs .> drs[1] * (1-display_tol)) && all(drs .< drs[1] * (1 + display_tol)) + println(io, "", Δr = $(drs[1])"") + else + println(io, "", Δr varying on [min = $(minimum(drs)), max = $(maximum(drs))]"") + end + temp_g = filter(!isnan, p.pcf_result.g) + println(io, "" g: $(minimum(temp_g)) - $(maximum(temp_g)) (min - max)"") +end + +"""""" + pcf(S::AbstractPhysiCellSequence, center_cell_types, target_cell_types=center_cell_types; include_dead::Union{Bool,Tuple{Bool,Bool}}=false, dr::Float64=20.0) + pcf(simulation::Simulation[, index], args...; kwargs...) + pcf(simulation_id::Integer[, index], args...; kwargs...) + pcf(pcmm_output::PCMMOutput{Simulation}[, index], args...; kwargs...) + +Calculate the pair correlation function (PCF) between two sets of cell types in a PhysiCell simulation snapshot or sequence. + +The `center_cell_types` and `target_cell_types` can be strings or vectors of strings. +This will compute one PCF rather than one for each pair of (center, target) cell types, i.e., all centers are compared to all targets. +If omitted, the target_cell_types will be the same as the center_cell_types, i.e., not a cross-PCF. +The `include_dead` argument can be a boolean or a tuple of booleans to indicate whether to include the dead centers and/or targets, respectively. +The `dr` argument specifies the bin size (thickness of each annulus) for the PCF calculation. + +In the signatures with an `index`, if it is provided then a single snapshot is analyzed, otherwise the entire sequence is analyzed. +The `index` must be an integer or either the symbol `:initial` or `:final`. + +# Arguments +- `S::AbstractPhysiCellSequence`: A [`PhysiCellSnapshot`](@ref) or [`PhysiCellSequence`](@ref) object. +- `center_cell_types`: The cell type name(s) to use as the center of the PCF. +- `target_cell_types`: The cell type name(s) to use as the target of the PCF. +- `simulation::Simulation`: The simulation object. +- `simulation_id::Integer`: The ID of the PhysiCell simulation. +- `pcmm_output::PCMMOutput{Simulation}`: The output of a PCMM simulation run. +- `index::Union{Integer, Symbol}`: The index of the snapshot to analyze (can be an integer or the symbol `:initial` or `:final`). + +# Keyword Arguments +- `include_dead::Union{Bool,Tuple{Bool,Bool}}`: Whether to include dead cells in the PCF calculation. If a tuple, the first element indicates whether to include dead centers and the second element indicates whether to include dead targets. +- `dr::Float64`: The bin size for the PCF calculation. + +# Alternate methods +- `pcf(simulation::Simulation, index::Union{Integer, Symbol}, center_cell_types, target_cell_types=center_cell_types; kwargs...)`: Calculate the PCF for a specific snapshot in a simulation. +- `pcf(simulation_id::Integer, index::Union{Integer, Symbol}, center_cell_types, target_cell_types=center_cell_types; kwargs...)`: Calculate the PCF for a specific snapshot in a simulation by ID. +- `pcf(simulation_id::Integer, center_cell_types, target_cell_types=center_cell_types; kwargs...)`: Calculate the PCF for all snapshots in a simulation by ID. +- `pcf(simulation::Simulation, center_cell_types, target_cell_types=center_cell_types; kwargs...)`: Calculate the PCF for all snapshots in a simulation. + +# Returns +A [`PCMMPCFResult`](@ref) object containing the time, radii, and g values of the PCF. +Regardless of the type of `S`, the time and radii will always be vectors. +If `S` is a snapshot, the g values will be a vector of the PCF. +If `S` is a sequence, the g values will be a (length(radii)-1 x length(time)) matrix of the PCF. +"""""" +function pcf(snapshot::PhysiCellSnapshot, center_cell_types, target_cell_types=center_cell_types; include_dead::Union{Bool,Tuple{Bool,Bool}}=false, dr::Float64=20.0) + args = preparePCF!(snapshot, center_cell_types, target_cell_types, include_dead, dr) + return pcfSnapshotCalculation(snapshot, args...) +end + +function pcf(sequence::PhysiCellSequence, center_cell_types, target_cell_types=center_cell_types; include_dead::Union{Bool,Tuple{Bool,Bool}}=false, dr::Float64=20.0) + args = preparePCF!(sequence, center_cell_types, target_cell_types, include_dead, dr) + all_results = [pcfSnapshotCalculation(snapshot, args...) for snapshot in sequence.snapshots] + return hcat(all_results...) +end + +pcf(simulation::Simulation, index::Union{Integer, Symbol}, args...; kwargs...) = pcf(PhysiCellSnapshot(simulation, index), args...; kwargs...) +pcf(simulation_id::Integer, index::Union{Integer, Symbol}, center_cell_types, target_cell_types=center_cell_types; kwargs...) = pcf(PhysiCellSnapshot(simulation_id, index), center_cell_types, target_cell_types; kwargs...) + +function pcf(simulation_id::Integer, center_cell_types, target_cell_types=center_cell_types; kwargs...) + print(""Computing PCF sequence for simulation ID $(simulation_id)..."") + result = pcf(PhysiCellSequence(simulation_id), center_cell_types, target_cell_types; kwargs...) + println("" done."") + return result +end + +pcf(simulation::Simulation, args...; kwargs...) = pcf(simulation.id, args...; kwargs...) + +pcf(pcmm_output::PCMMOutput{Simulation}, args...; kwargs...) = pcf(pcmm_output.trial, args...; kwargs...) + +#! pcf helper functions +"""""" + preparePCF!(S::AbstractPhysiCellSequence, center_cell_types, target_cell_types, include_dead::Union{Bool,Tuple{Bool,Bool}}, dr::Float64) + +Prepare the arguments for the PCF calculation. +"""""" +function preparePCF!(S::AbstractPhysiCellSequence, center_cell_types, target_cell_types, include_dead::Union{Bool,Tuple{Bool,Bool}}, dr::Float64) + loadCells!(S) + loadMesh!(S) + center_cell_types, target_cell_types = processPCFCellTypes.([center_cell_types, target_cell_types]) + temp = cellTypeToNameDict(S) + cell_name_to_type_dict = [type_name => type_id for (type_id, type_name) in temp] |> Dict{String,Int} + is_cross_pcf = isCrossPCF(center_cell_types, target_cell_types) + if include_dead isa Bool + include_dead = (include_dead, include_dead) + end + constants = pcfConstants(S, dr) + return (center_cell_types, target_cell_types, cell_name_to_type_dict, include_dead, is_cross_pcf, constants) +end + +"""""" + pcfConstants(S::AbstractPhysiCellSequence, dr::Float64) + +Create a `Constants` object for the PCF calculation based on the mesh of the snapshot or sequence. +"""""" +function pcfConstants(snapshot::PhysiCellSnapshot, dr::Float64) + dx = snapshot.mesh[""x""][2] - snapshot.mesh[""x""][1] + dy = snapshot.mesh[""y""][2] - snapshot.mesh[""y""][1] + xlims = (snapshot.mesh[""x""][1] .- dx/2, snapshot.mesh[""x""][end] .+ dx/2) + ylims = (snapshot.mesh[""y""][1] .- dy/2, snapshot.mesh[""y""][end] .+ dy/2) + constants_lims = [xlims, ylims] + is_3d = length(snapshot.mesh[""z""]) > 1 + if is_3d + dz = snapshot.mesh[""z""][2] - snapshot.mesh[""z""][1] + zlims = (snapshot.mesh[""z""][1] .- dz/2, snapshot.mesh[""z""][end] .+ dz/2) + push!(constants_lims, zlims) + end + return Constants(constants_lims..., dr) +end + +function pcfConstants(sequence::PhysiCellSequence, dr::Float64) + snapshot = sequence.snapshots[1] + return pcfConstants(snapshot, dr) +end + +"""""" + pcfSnapshotCalculation(snapshot::PhysiCellSnapshot, center_cell_types::Vector{String}, target_cell_types::Vector{String}, cell_name_to_type_dict::Dict{String,Int}, include_dead::Union{Bool,Tuple{Bool,Bool}}, is_cross_pcf::Bool, constants::Constants) + +Calculate the pair correlation function (PCF) for a given snapshot. +"""""" +function pcfSnapshotCalculation(snapshot::PhysiCellSnapshot, center_cell_types::Vector{String}, target_cell_types::Vector{String}, cell_name_to_type_dict::Dict{String,Int}, include_dead::Union{Bool,Tuple{Bool,Bool}}, is_cross_pcf::Bool, constants::Constants) + is_3d = ndims(constants) == 3 + cells = snapshot.cells + centers = cellPositionsForPCF(cells, center_cell_types, cell_name_to_type_dict, include_dead[1], is_3d) + if is_cross_pcf + targets = cellPositionsForPCF(cells, target_cell_types, cell_name_to_type_dict, include_dead[2], is_3d) + pcf_result = pcf(centers, targets, constants) + else + pcf_result = pcf(centers, constants) + end + return PCMMPCFResult(snapshot.time, pcf_result) +end + +"""""" + processPCFCellTypes(cell_types) + +Process the cell types for the PCF calculation so that they are always a vector of strings. +"""""" +function processPCFCellTypes(cell_types) + if cell_types isa String + return [cell_types] + elseif cell_types isa AbstractVector{<:AbstractString} + return cell_types + end + throw(ArgumentError(""Cell types must be a string or a vector of strings. Got $(typeof(cell_types))."")) +end + +"""""" + isCrossPCF(center_cell_types::Vector{String}, target_cell_types::Vector{String}) + +Check if the center and target cell types are the same (PCF) or disjoint (cross-PCF); if neither, throw an error. +"""""" +function isCrossPCF(center_cell_types::Vector{String}, target_cell_types::Vector{String}) + center_set = Set(center_cell_types) + target_set = Set(target_cell_types) + if center_set == target_set + return false + elseif isdisjoint(center_set, target_set) + return true + else + throw(ArgumentError(""Center and target cell types must be the same or disjoint. Found $(center_cell_types) and $(target_cell_types)."")) + end +end + +"""""" + cellPositionsForPCF(cells::DataFrame, cell_types::Vector{String}, cell_name_to_type_dict::Dict{String,Int}, include_dead::Bool, is_3d::Bool) + +Get the positions of the cells for the PCF calculation. +"""""" +function cellPositionsForPCF(cells::DataFrame, cell_types::Vector{String}, cell_name_to_type_dict::Dict{String,Int}, include_dead::Bool, is_3d::Bool) + cell_type_id_set = [cell_name_to_type_dict[cell_type] for cell_type in cell_types] |> Set + cell_type_df = cells[[ct in cell_type_id_set for ct in cells.cell_type], :] + if !include_dead + cell_type_df = cell_type_df[.!cell_type_df.dead, :] + end + position_labels = [:position_1, :position_2] + if is_3d + push!(position_labels, :position_3) + end + return reduce(hcat, [cell_type_df[!, label] for label in position_labels]) +end + +#! plotting functions +@recipe function f(results::Vararg{PCMMPCFResult}; time_unit=:min, distance_unit=:um) + args = preparePCFPlot([results...]; time_unit=time_unit, distance_unit=distance_unit) + @series begin + colorscheme --> :cork + PairCorrelationFunction.PCFPlot(args) + end +end + +@recipe function f(results::Vector{PCMMPCFResult}; time_unit=:min, distance_unit=:um) + args = preparePCFPlot(results; time_unit=time_unit, distance_unit=distance_unit) + @series begin + colorscheme --> :cork + PairCorrelationFunction.PCFPlot(args) + end +end + +"""""" + preparePCFPlot(results::Vector{PCMMPCFResult}; time_unit=:min, distance_unit=:um) + +Prepare the time and radii for the PCF plot. +"""""" +function preparePCFPlot(results::Vector{PCMMPCFResult}; time_unit=:min, distance_unit=:um) + @assert all([r.time == results[1].time for r in results]) ""All PCFResults must have the same time vector."" + time = processTime(results[1].time, time_unit) #! we need to make a copy of the time vector anyways, so no need to have a ! function + radii = processDistance(results[1].pcf_result.radii, distance_unit) + return time, radii, [r.pcf_result for r in results] +end + +"""""" + processTime(time::Vector{Float64}, time_unit::Symbol) + +Process the time vector to convert it to the desired time unit. +Options are :min, :s, :h, :d, :w, :mo, and :y. +"""""" +function processTime(time, time_unit) + time_unit = Symbol(time_unit) + if time_unit in [:min, :minute, :minutes] + elseif time_unit in [:s, :second, :seconds] + time = time .* 60 + elseif time_unit in [:h, :hour, :hours] + time = time ./ 60 + elseif time_unit in [:d, :day, :days] + time = time ./ 1440 + elseif time_unit in [:w, :week, :weeks] + time = time ./ 10080 + elseif time_unit in [:mo, :month, :months] + time = time ./ 43200 #! assumes 30 days in a month + elseif time_unit in [:y, :year, :years] + time = time ./ 525600 #! assumes exactly 365 days in a year + else + throw(ArgumentError(""Invalid time unit: $(time_unit). Must be one of :min, :s, :h, :d, :w, or :y."")) + end + return time +end + +"""""" + processDistance(distance::Vector{Float64}, distance_unit::Symbol) + +Process the distance vector to convert it to the desired distance unit. +Options are :um, :mm, and :cm. +"""""" +function processDistance(distance, distance_unit) + distance_unit = Symbol(distance_unit) + if distance_unit in [:um, :micrometer, :micrometers, :μm, :micron, :microns] + #! default PhysiCell distance unit + elseif distance_unit in [:mm, :millimeter, :millimeters] + distance = distance ./ 1000 + elseif distance_unit in [:cm, :centimeter, :centimeters] + distance = distance ./ 100 + else + throw(ArgumentError(""Invalid distance unit: $(distance_unit). Must be one of :um, :mm, or :cm."")) + end + return distance +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/analysis/graphs.jl",".jl","7268","147","using Graphs, MetaGraphsNext + +include(joinpath(@__DIR__, "".."", "".."", ""deps"", ""DeprecateKeywords.jl"")) +import .DeprecateKeywords: @depkws + +export connectedComponents + +"""""" + connectedComponents(snapshot::PhysiCellSnapshot, graph=:neighbors; include_cell_type_names=:all_in_one, exclude_cell_type_names::String[], include_dead::Bool=false) + connectedComponents(simulation::Simulation, index, graph; kwargs...) + connectedComponents(pcmm_output::PCMMOutput{Simulation}, args...; kwargs...) + +Find the connected components of a graph in a PhysiCell snapshot. + +The computation can be done on subsets of cells based on their cell types. + +# Arguments +- `snapshot::PhysiCellSnapshot`: The snapshot to analyze +- `graph`: The graph data to use (default is `:neighbors`); must be one of `:neighbors`, `:attachments`, or `:spring_attachments`; can also be a string +- `simulation::Simulation`: The simulation object to analyze +- `index`: The index of the snapshot to analyze (can be an integer or a symbol) +- `pcmm_output::PCMMOutput{Simulation}`: The output of a PCMM simulation run to analyze + +# Keyword Arguments +- `include_cell_type_names`: The cell types to include in the analysis (default is `:all_in_one`). Full list of options: + - `:all` - compute connected components for all cell types individually + - `:all_in_one` - compute connected components for all cell types together + - `""cell_type_1""` - compute connected components only for the cells of type `cell_type_1` + - `[""cell_type_1"", ""cell_type_2""]` - compute connected components for the cells of type `cell_type_1` and `cell_type_2` separately + - `[[""cell_type_1"", ""cell_type_2""]]` - compute connected components for the cells of type `cell_type_1` and `cell_type_2` together + - `[[""cell_type_1"", ""cell_type_2""], ""cell_type_3""]` - compute connected components for the cells of type `cell_type_1` and `cell_type_2` together, and for the cells of type `cell_type_3` separately +- `exclude_cell_type_names`: The cell types to exclude from the analysis (default is `String[]`); can be a single string or a vector of strings +- `include_dead`: Whether to include dead cells in the analysis (default is `false`) + +# Returns +A dictionary in which each key is one of the following: +- cell type name (String) +- list of cell type names (Vector{String}) +- list of cell type names followed by the symbol :include_dead (Vector{Any}) + +For each key, the value is a list of connected components in the graph. +Each component is represented as a vector of vertex labels. +As of this writing, the vertex labels are the simple `AgentID` class that wraps the cell ID. +"""""" +@depkws force=true function connectedComponents(snapshot::PhysiCellSnapshot, graph::Symbol=:neighbors; include_cell_type_names=:all_in_one, exclude_cell_type_names=String[], include_dead::Bool=false, + @deprecate(include_cell_types, include_cell_type_names), @deprecate(exclude_cell_types, exclude_cell_type_names)) + is_all_in_one = include_cell_type_names == :all_in_one + cell_type_to_name_dict = cellTypeToNameDict(snapshot) + cell_type_names = values(cell_type_to_name_dict) |> collect + + include_cell_type_names = processIncludeCellTypes(include_cell_type_names, cell_type_names) + exclude_cell_type_names = processExcludeCellTypes(exclude_cell_type_names) + + loadGraph!(snapshot, graph) + if is_all_in_one + G = getfield(snapshot, graph) |> deepcopy + if include_dead + key = [include_cell_type_names[1]; :include_dead] + else + key = include_cell_type_names[1] + loadCells!(snapshot) + dead_cell_ids = snapshot.cells.ID[snapshot.cells.dead] |> Set + vertices_to_remove = [v for v in vertices(G) if G.vertex_labels[v].id in dead_cell_ids] + sort!(vertices_to_remove; rev=true) + for v in vertices_to_remove + rem_vertex!(G, v) + end + end + return Dict(key => _connectedComponents(G)) + end + + loadCells!(snapshot) + + #! if not all_in_one, then we need to manage the cells carefully + data = Dict{Any,Any}() + if include_dead + id_to_name = [row.ID => cell_type_to_name_dict[row.cell_type] for row in eachrow(snapshot.cells)] |> Dict + else + #! map any dead cells to the Symbol :dead so it cannot be in the list of String cell types + id_to_name = [row.ID => (row.dead ? :dead : cell_type_to_name_dict[row.cell_type]) for row in eachrow(snapshot.cells)] |> Dict + end + + for cell_group in include_cell_type_names + if cell_group isa String + internal_keys = [cell_group] #! standardize so that all are vectors + else + internal_keys = cell_group + @assert internal_keys isa Vector{String} ""include_cell_type_names must be a vector of strings"" + end + setdiff!(internal_keys, exclude_cell_type_names) #! remove any cell types that are to be excluded (also removes duplicates) + if isempty(internal_keys) + continue + end + G = getfield(snapshot, graph) |> deepcopy + vertices_to_remove = [v for v in vertices(G) if !in(id_to_name[G.vertex_labels[v].id], internal_keys)] + sort!(vertices_to_remove; rev=true) + for v in vertices_to_remove + rem_vertex!(G, v) + end + + output_key = include_dead ? [internal_keys; :include_dead] : internal_keys + if length(output_key) == 1 + output_key = output_key[1] + end + data[output_key] = _connectedComponents(G) + end + return data +end + +connectedComponents(snapshot::PhysiCellSnapshot, graph::String; kwargs...) = connectedComponents(snapshot, Symbol(graph); kwargs...) + +function connectedComponents(simulation::Simulation, index::Union{Integer, Symbol}, graph::Union{Symbol,String}=:neighbors; kwargs...) + snapshot = PhysiCellSnapshot(simulation, index) + return connectedComponents(snapshot, graph; kwargs...) +end + +connectedComponents(pcmm_output::PCMMOutput{Simulation}, args...; kwargs...) = connectedComponents(pcmm_output.trial, args...; kwargs...) + +"""""" + _connectedComponents(G::MetaGraph) + +Find the connected components of a graph. + +First compute the transitive closure of the underlying `Graphs.Graph` object. +Then, update the edge data of the `MetaGraph` object to reflect the new edges. +Finally, loop over vertex labels and find the vertices they are connected to until all vertices are accounted for. +Returns a list of connected components, where each component is represented as a vector of vertex labels. +"""""" +function _connectedComponents(G::MetaGraph) + transitiveclosure!(G.graph) + for e in edges(G.graph) + edge_datum = (G.vertex_labels[e.src], G.vertex_labels[e.dst]) + G.edge_data[edge_datum] = nothing + end + remaining_labels = Set(G.vertex_labels |> values) + components = [] + while !isempty(remaining_labels) + next_label = pop!(remaining_labels) + next_label_ind = G.vertex_properties[next_label][1] + neighbor_inds = all_neighbors(G.graph, next_label_ind) + neighbor_labels = [G.vertex_labels[i] for i in neighbor_inds] + component = vcat(next_label, neighbor_labels) + push!(components, component) + setdiff!(remaining_labels, component) + end + return components +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/analysis/population.jl",".jl","21977","517","using RecipesBase + +export finalPopulationCount, populationCount, populationTimeSeries + +"""""" + populationCount(snapshot, cell_type_to_name_dict::Dict{Int,String}=Dict{Int,String}(), labels::Vector{String}=String[]; include_dead::Bool=false) + +Return the population count of a snapshot as a dictionary with cell type names as keys and their counts as values. + +If the snapshot is missing, it will return missing. +This helps in cases where the files have been deleted, for example by pruning. + +# Arguments +- `snapshot::PhysiCellSnapshot`: The snapshot to count the cells in. +- `cell_type_to_name_dict::Dict{Int,String}`: A dictionary mapping cell type IDs to names (default is an empty dictionary). If not provided, it is read from the snapshot files. +- `labels::Vector{String}`: The labels to identify the cell data. If not provided, it is read from the snapshot files. + +# Keyword Arguments +- `include_dead::Bool`: Whether to include dead cells in the count. Default is `false`. +"""""" +function populationCount(snapshot::PhysiCellSnapshot, cell_type_to_name_dict::Dict{Int,String}=Dict{Int,String}(), labels::Vector{String}=String[]; include_dead::Bool=false) + loadCells!(snapshot, cell_type_to_name_dict, labels) + data = Dict{String, Int}() + if include_dead + cell_df = snapshot.cells + else + cell_df = @view snapshot.cells[snapshot.cells.dead .== false, :] + end + if isempty(cell_type_to_name_dict) + cell_type_to_name_dict = cellTypeToNameDict(snapshot) + end + cell_type_names = values(cell_type_to_name_dict) + for cell_type_name in cell_type_names + data[cell_type_name] = count(x -> x == cell_type_name, cell_df.cell_type_name) + end + return data +end + +populationCount(::Missing, args...; kwargs...) = missing + +"""""" + AbstractPopulationTimeSeries + +Abstract type representing a population time series for either a simulation or a monad. +"""""" +abstract type AbstractPopulationTimeSeries end + +"""""" + SimulationPopulationTimeSeries <: AbstractPopulationTimeSeries + +Holds the data for a simulation's population time series. + +If constructed using a `Simulation` or an `Integer` (representing a simulation ID), it will save the time series inside the `simulations/simulation_id/summary/` folder. +It will also look for previously computed time series there to avoid recomputing them. + +# Examples +``` +spts = SimulationPopulationTimeSeries(1) # first checks if the population time series is already computed and if not, computes it +spts = SimulationPopulationTimeSeries(Simulation(1)) # first checks if the population time series is already computed and if not, computes it +spts = SimulationPopulationTimeSeries(1; include_dead=true) # similar, but counts dead cells as well; the file name has \""_include_dead\"" appended +``` + +# Fields +- `simulation_id::Int`: The ID of the simulation. +- `time::Vector{Real}`: The time points of the population time series. +- `cell_count::Dict{String, Vector{Integer}}`: A dictionary where keys are cell type names and values are vectors of cell counts over time. +"""""" +struct SimulationPopulationTimeSeries <: AbstractPopulationTimeSeries + simulation_id::Int + time::Vector{Real} + cell_count::Dict{String, Vector{Integer}} +end + +function SimulationPopulationTimeSeries(sequence::PhysiCellSequence; include_dead::Bool=false) + time = [snapshot.time for snapshot in sequence.snapshots] + cell_count = Dict{String, Vector{Integer}}() + for (i, snapshot) in enumerate(sequence.snapshots) + population_count = populationCount(snapshot, sequence.cell_type_to_name_dict, sequence.labels; include_dead=include_dead) + ismissing(population_count) && continue #! skip if the population count is missing (could happen if the snapshot is empty, which would happen if, e.g., the xml is missing) + for (ID, count) in pairs(population_count) + if !(string(ID) in keys(cell_count)) + cell_count[ID] = zeros(Int, length(time)) + end + cell_count[ID][i] = count + end + end + return SimulationPopulationTimeSeries(sequence.simulation_id, time, cell_count) +end + +function SimulationPopulationTimeSeries(simulation_id::Integer; include_dead::Bool=false, verbose::Bool=true) + verbose ? print(""Computing SimulationPopulationTimeSeries for Simulation $simulation_id..."") : nothing + simulation_folder = trialFolder(Simulation, simulation_id) + path_to_summary = joinpath(simulation_folder, ""summary"") + path_to_file = joinpath(path_to_summary, ""population_time_series$(include_dead ? ""_include_dead"" : """").csv"") + if isfile(path_to_file) + df = CSV.read(path_to_file, DataFrame) + spts = SimulationPopulationTimeSeries(simulation_id, df.time, Dict{String, Vector{Integer}}(name => df[!, Symbol(name)] for name in names(df) if name != ""time"")) + else + sequence = PhysiCellSequence(simulation_id; include_cells=true) + if ismissing(sequence) + return missing + end + mkpath(path_to_summary) + spts = SimulationPopulationTimeSeries(sequence; include_dead=include_dead) + df = DataFrame(time=spts.time) + for (name, counts) in pairs(spts.cell_count) + df[!, Symbol(name)] = counts + end + CSV.write(path_to_file, df) + end + verbose ? println(""done."") : nothing + return spts +end + +SimulationPopulationTimeSeries(simulation::Simulation; kwargs...) = SimulationPopulationTimeSeries(simulation.id; kwargs...) + +function Base.getindex(spts::SimulationPopulationTimeSeries, cell_type::String) + if cell_type in keys(spts.cell_count) + return spts.cell_count[cell_type] + elseif cell_type == ""time"" + return spts.time + else + throw(ArgumentError(""Cell type $cell_type not found in the population time series."")) + end +end + +function Base.show(io::IO, spts::SimulationPopulationTimeSeries) + println(io, ""SimulationPopulationTimeSeries for Simulation $(spts.simulation_id):"") + println(io, "" Time: $(formatTimeRange(spts.time))"") + println(io, "" Cell types: $(join(keys(spts.cell_count), "", ""))"") +end + +"""""" + formatTimeRange(v::Vector{<:Real}) + +Format a vector of time points into a string representation. + +Used only for printing certain classes to the console. +"""""" +function formatTimeRange(v::Vector{<:Real}) + @assert !isempty(v) ""Vector is empty."" + if length(v) == 1 + return ""$(v[1])"" + end + #! Calculate the step size + step = v[2] - v[1] + + #! Check if all consecutive differences are equal to the step size + if all(diff(v) .≈ step) + return ""$(v[1]):$step:$(v[end])"" + else + return ""$(v[1])-$(v[end]) (not equally spaced)"" + end +end + +"""""" + finalPopulationCount(simulation::Simulation[; include_dead::Bool=false]) + +Return the final population count of a simulation as a dictionary with cell type names as keys and their counts as values. + +Also works with the simulation ID: +``` +fpc = finalPopulationCount(1) +``` + +# Example +``` +fpc = finalPopulationCount(simulation) +final_default_count = fpc[""default""] +``` +"""""" +function finalPopulationCount(simulation_id::Int; include_dead::Bool=false) + assertInitialized() + final_snapshot = PhysiCellSnapshot(simulation_id, :final; include_cells=true) + return populationCount(final_snapshot; include_dead=include_dead) +end + +finalPopulationCount(simulation::Simulation; kwargs...) = finalPopulationCount(simulation.id; kwargs...) + +finalPopulationCount(pcmm_output::PCMMOutput{Simulation}; kwargs...) = finalPopulationCount(pcmm_output.trial; kwargs...) + +"""""" + MonadPopulationTimeSeries <: AbstractPopulationTimeSeries + +Holds the data for a monad's population time series. + +Note: unlike `SimulationPopulationTimeSeries`, this type does not save the data to a file. + +# Examples + +``` +mpts = MonadPopulationTimeSeries(1) +mpts = MonadPopulationTimeSeries(Monad(1)) +``` + +# Fields +- `monad_id::Int`: The ID of the monad. +- `monad_length::Int`: The number of simulations in the monad. +- `time::Vector{Real}`: The time points of the population time series. +- `cell_count::Dict{String, NamedTuple}`: A dictionary where keys are cell type names and values are NamedTuples with fields `:counts`, `:mean`, and `:std`. +"""""" +struct MonadPopulationTimeSeries <: AbstractPopulationTimeSeries + monad_id::Int + monad_length::Int + time::Vector{Real} + cell_count::Dict{String,NamedTuple} +end + +function MonadPopulationTimeSeries(monad::Monad; include_dead::Bool=false) + simulation_ids = simulationIDs(monad) + monad_length = length(simulation_ids) + time = Real[] + cell_count = Dict{String, NamedTuple}() + _counts = Dict{String,Any}() + for (i, simulation_id) in enumerate(simulation_ids) + spts = SimulationPopulationTimeSeries(simulation_id; include_dead=include_dead) + if ismissing(spts) + continue + end + if isempty(time) + time = spts.time + else + @assert time == spts.time ""Simulations $(simulation_ids[1]) and $(simulation_id) in monad $(monad.id) have different times in their time series."" + end + for (name, cell_count) in pairs(spts.cell_count) + if !haskey(_counts, name) + _counts[name] = [cell_count] + else + push!(_counts[name], cell_count) + end + end + end + _mean = Dict{String, Vector{Real}}() + _std = Dict{String, Vector{Real}}() + for (name, vectors) in _counts + _array = reduce(hcat, vectors) + _mean[name] = mean(_array, dims=2) |> vec + _std[name] = std(_array, dims=2) |> vec + cell_count[name] = [:counts => _array, :mean => _mean[name], :std => _std[name]] |> NamedTuple + end + return MonadPopulationTimeSeries(monad.id, monad_length, time, cell_count) +end + +MonadPopulationTimeSeries(monad_id::Integer; kwargs...) = MonadPopulationTimeSeries(Monad(monad_id); kwargs...) + +function Base.getindex(mpts::MonadPopulationTimeSeries, cell_type::String) + if cell_type in keys(mpts.cell_count) + return mpts.cell_count[cell_type] + elseif cell_type == ""time"" + return mpts.time + else + throw(ArgumentError(""Cell type $cell_type not found in the population time series."")) + end +end + +Base.keys(apts::AbstractPopulationTimeSeries; exclude_time::Bool=false) = exclude_time ? keys(apts.cell_count) : [""time""; keys(apts.cell_count) |> collect] + +function Base.show(io::IO, mpts::MonadPopulationTimeSeries) + println(io, ""MonadPopulationTimeSeries for Monad $(mpts.monad_id):"") + printSimulationIDs(io, Monad(mpts.monad_id)) + println(io, "" Time: $(formatTimeRange(mpts.time))"") + println(io, "" Cell types: $(join(keys(mpts.cell_count), "", ""))"") +end + +"""""" + populationTimeSeries(M::AbstractMonad[; include_dead::Bool=false]) + populationTimeSeries(pcmm_output::PCMMOutput{<:AbstractMonad}[; include_dead::Bool=false]) + +Return the population time series of a simulation or a monad. + +See `SimulationPopulationTimeSeries` and `MonadPopulationTimeSeries` for more details. +"""""" +function populationTimeSeries(M::AbstractMonad; include_dead::Bool=false) + if M isa Simulation + return SimulationPopulationTimeSeries(M; include_dead=include_dead) + else + return MonadPopulationTimeSeries(M; include_dead=include_dead) + end +end + +populationTimeSeries(pcmm_output::PCMMOutput{<:AbstractMonad}; kwargs...) = populationTimeSeries(pcmm_output.trial; kwargs...) + +#! plot recipes +"""""" + getMeanCounts(apts::AbstractPopulationTimeSeries) + +Return the mean counts of a population time series. +"""""" +getMeanCounts(s::SimulationPopulationTimeSeries) = s.cell_count +getMeanCounts(m::MonadPopulationTimeSeries) = [k => v.mean for (k, v) in pairs(m.cell_count)] |> Dict + +@recipe function f(M::AbstractMonad; include_dead=false, include_cell_type_names=:all, exclude_cell_type_names=String[], time_unit=:min) + pts = populationTimeSeries(M; include_dead=include_dead) + time = processTime(pts.time, time_unit) + + #! allow for single string input for either of these + if haskey(plotattributes, :include_cell_types) + @assert include_cell_type_names == :all ""Do not use both `include_cell_types` and `include_cell_type_names` as keyword arguments. Use `include_cell_type_names` instead."" + Base.depwarn(""`include_cell_types` is deprecated as a keyword. Use `include_cell_type_names` instead."", :plot; force=true) + include_cell_type_names = plotattributes[:include_cell_types] + pop!(plotattributes, :include_cell_types) + end + include_cell_type_names = processIncludeCellTypes(include_cell_type_names, keys(pts; exclude_time=true) |> collect) + + if haskey(plotattributes, :exclude_cell_types) + @assert exclude_cell_type_names == String[] ""Do not use both `exclude_cell_types` and `exclude_cell_type_names` as keyword arguments. Use `exclude_cell_type_names` instead."" + Base.depwarn(""`exclude_cell_types` is deprecated as a keyword. Use `exclude_cell_type_names` instead."", :plot; force=true) + exclude_cell_type_names = plotattributes[:exclude_cell_types] + pop!(plotattributes, :exclude_cell_types) + end + exclude_cell_type_names = processExcludeCellTypes(exclude_cell_type_names) + + for k in include_cell_type_names + if k isa String + k = [k] #! standardize so that all are vectors + end + setdiff!(k, exclude_cell_type_names) #! remove any cell types that are to be excluded (also removes duplicates) + if isempty(k) + continue #! skip if all cell types were excluded + end + if length(k) == 1 + name = k[1] + @series begin + label --> name + x = time + y = getMeanCounts(pts)[name] + if length(simulationIDs(M)) > 1 + ribbon := pts[name].std + end + x, y + end + else #! need to basically recalculate since we are combining multiple cell types + simulation_ids = simulationIDs(M) + sptss = [SimulationPopulationTimeSeries(simulation_id; include_dead=include_dead, verbose=false) for simulation_id in simulation_ids] + filter!(!ismissing, sptss) #! remove any that failed to load + sim_sums = [sum([spts[name] for name in k]) for spts in sptss] + all_counts = reduce(hcat, sim_sums) + @series begin + label --> join(k, "", "") + x = time + y = mean(all_counts, dims=2) |> vec + if length(simulationIDs(M)) > 1 + ribbon := std(all_counts, dims=2) |> vec + end + x, y + end + end + end +end + +@recipe function f(sampling::Sampling; include_dead=false, include_cell_type_names=:all, exclude_cell_type_names=String[], time_unit=:min) + df = PhysiCellModelManager.simulationsTable(sampling) + monads = [] + title_tuples = [] + for monad in sampling.monads + push!(monads, monad) + sim_id = simulationIDs(monad)[1] + row_ind = findfirst(df[!, :SimID] .== sim_id) + row = df[row_ind, :] + title_tuple = [row[name] for name in names(row) if !(name in [""SimID""; shortLocationVariationID.(String, projectLocations().varied)])] + push!(title_tuples, title_tuple) + end + + order = sortperm(title_tuples) + title_tuples = title_tuples[order] + monads = monads[order] + + layout --> (length(monads), 1) #! easy room for improvement here + + for (i, (monad, title_tuple)) in enumerate(zip(monads, title_tuples)) + @series begin + title --> ""("" * join(title_tuple, "", "") * "")"" + subplot := i + legend := false + include_dead --> include_dead + include_cell_type_names --> include_cell_type_names + exclude_cell_type_names --> exclude_cell_type_names + time_unit --> time_unit + monad + end + end +end + +@recipe function f(::Type{PCMMOutput{T}}, out::PCMMOutput{T}) where T <: AbstractSampling + out.trial +end + +@recipe function f(::Type{PCMMOutput{Trial}}, out::PCMMOutput{Trial}) + throw(ArgumentError(""Plotting an entire trial not (yet?) defined. Break it down into at least Samplings first."")) +end + +"""""" + plotbycelltype(T::AbstractTrial; include_dead::Bool=false, include_cell_type_names=:all, exclude_cell_type_names=String[], time_unit=:min) + +Plot the population time series of a trial by cell type. + +Each cell type gets its own subplot. +Each monad gets its own series within each subplot. + +# Arguments +- `T::AbstractTrial`: The trial to plot. + +# Keyword Arguments +- `include_dead::Bool`: Whether to include dead cells in the count. Default is `false`. +- `include_cell_type_names::Vector{String}`: A vector of cell type names to include in the plot. Default is `:all`, which includes all cell types in separate plots. +- `exclude_cell_type_names::Vector{String}`: A vector of cell type names to exclude from the plot. Default is an empty vector, i.e., no cell types are excluded. +- `time_unit::Symbol`: The time unit to use for the x-axis. Default is `:min`, which uses minutes. +"""""" +plotbycelltype + +@userplot PlotByCellType + +struct CellTypeInMonads + time::Vector{Vector{Real}} + cell_count_means::Vector{Vector{Real}} + cell_count_stds::Vector{Vector{Real}} +end + +@recipe function f(p::PlotByCellType; include_dead=false, include_cell_type_names=:all, exclude_cell_type_names=String[], time_unit=:min) + @assert length(p.args) == 1 ""Expected exactly 1 argument, got $(length(p.args))."" + if (p.args[1] isa PCMMOutput) + T = p.args[1].trial + else + T = p.args[1] + end + @assert typeof(T) <: AbstractTrial ""Expected first argument to be a subtype of AbstractTrial, got $(typeof(p.args[1]))."" + + if T isa Simulation + monads = [Monad(T)] + else + monads = Monad.(monadIDs(T)) + end + + simulation_id = simulationIDs(T) |> first + all_cell_types = cellTypeToNameDict(simulation_id) |> values |> collect + + if haskey(plotattributes, :include_cell_types) + @assert include_cell_type_names == :all ""Do not use both `include_cell_types` and `include_cell_type_names` as keyword arguments. Use `include_cell_type_names` instead."" + Base.depwarn(""`include_cell_types` is deprecated as a keyword. Use `include_cell_type_names` instead."", :plot; force=true) + include_cell_type_names = plotattributes[:include_cell_types] + pop!(plotattributes, :include_cell_types) + end + include_cell_type_names = processIncludeCellTypes(include_cell_type_names, all_cell_types) + + if haskey(plotattributes, :exclude_cell_types) + @assert exclude_cell_type_names == String[] ""Do not use both `exclude_cell_types` and `exclude_cell_type_names` as keyword arguments. Use `exclude_cell_type_names` instead."" + Base.depwarn(""`exclude_cell_types` is deprecated as a keyword. Use `exclude_cell_type_names` instead."", :plot; force=true) + exclude_cell_type_names = plotattributes[:exclude_cell_types] + pop!(plotattributes, :exclude_cell_types) + end + exclude_cell_type_names = processExcludeCellTypes(exclude_cell_type_names) + + monad_summary = Dict{Int,Any}() + all_cell_types = Set() + for monad in monads + simulation_ids = simulationIDs(monad) + monad_length = length(simulation_ids) + time = Real[] + cell_count_arrays = Dict{Any, Array{Int,2}}() + sptss = SimulationPopulationTimeSeries.(simulation_ids; include_dead=include_dead, verbose=false) + filter!(!ismissing, sptss) #! remove any that failed to load + for (i, spts) in enumerate(sptss) + if isempty(time) + time = spts.time + else + @assert time == spts.time ""Simulations $(simulation_ids[1]) and $(simulation_ids[i]) in monad $(monad.id) have different times in their time series."" + end + for k in include_cell_type_names + if k isa String + k = [k] #! standardize so that all are vectors + end + setdiff!(k, exclude_cell_type_names) #! remove any cell types that are to be excluded (also removes duplicates) + if isempty(k) + continue #! skip if all cell types were excluded + end + if !haskey(cell_count_arrays, k) + cell_count_arrays[k] = zeros(Int, length(time), monad_length) + end + @assert [haskey(spts.cell_count, ct) for ct in k] |> all ""A cell type in $k not found in simulation $simulation_id which has cell types $(keys(spts.cell_count))."" + cell_count_arrays[k][:,i] = sum([spts.cell_count[ct] for ct in k]) + end + end + cell_count_means = Dict{Any, Vector{Real}}() + cell_count_stds = Dict{Any, Vector{Real}}() + for (name, array) in pairs(cell_count_arrays) + cell_count_means[name] = mean(array, dims=2) |> vec + cell_count_stds[name] = std(array, dims=2) |> vec + push!(all_cell_types, name) + end + monad_summary[monad.id] = (time=time, cell_count_means=cell_count_means, cell_count_stds=cell_count_stds) + end + + layout --> (length(all_cell_types), 1) #! easy room for improvement here + + for (i, cell_type) in enumerate(all_cell_types) + @series begin + title --> cell_type + time_unit --> time_unit + legend := false + subplot := i + x = [monad_summary[monad.id].time for monad in monads] + y = [monad_summary[monad.id].cell_count_means[cell_type] for monad in monads] + z = [monad_summary[monad.id].cell_count_stds[cell_type] for monad in monads] + CellTypeInMonads(x, y, z) + end + end +end + +@recipe function f(ctim::CellTypeInMonads; time_unit=:min) + for (x, y, z) in zip(ctim.time, ctim.cell_count_means, ctim.cell_count_stds) + time = processTime(x, time_unit) + @series begin + ribbon := z + time, y + end + end +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/analysis/substrate.jl",".jl","14898","331","using Statistics + +@compat public AverageSubstrateTimeSeries, ExtracellularSubstrateTimeSeries + +"""""" + VoxelWeights + +A struct to hold the voxel weights for a PhysiCell simulation. +# Fields +- `use_weights::Bool`: Whether to use weights for the voxel volumes. If all voxel volumes are the same, this is set to `false`. +- `weights::Vector{Real}`: The weights for the voxel volumes. +- `weight_total::Real`: The total weight of the voxel volumes. +"""""" +struct VoxelWeights + use_weights::Bool + weights::Vector{Real} + weight_total::Real + + function VoxelWeights(weights::AbstractVector{<:Real}) + use_weights = length(unique(weights)) != 1 + weight_total = sum(weights) + return new(use_weights, weights, weight_total) + end + + function VoxelWeights(snapshot::PhysiCellSnapshot) + loadSubstrates!(snapshot) + weights = snapshot.substrates[!, :volume] + return VoxelWeights(weights) + end +end + +"""""" + averageSubstrate(snapshot::PhysiCellSnapshot, substrate_names::Vector{String}=String[], voxel_weights::VoxelWeights=VoxelWeights(snapshot)) + +Compute the average substrate concentrations for every substrate in a PhysiCell snapshot. + +The voxel volumes are used as weights if they are not all the same. + +# Arguments +- `snapshot::PhysiCellSnapshot`: The snapshot to analyze. +- `substrate_names::Vector{String}`: The names of the substrates in the simulation. If not provided, it is read from the snapshot files. +- `voxel_weights::VoxelWeights`: The voxel weights to use. If not provided, it is computed from the snapshot. + +# Returns +- `data::Dict{String, Real}`: A dictionary mapping substrate names to their average concentrations. +"""""" +function averageSubstrate(snapshot::PhysiCellSnapshot, substrate_names::Vector{String}=String[], voxel_weights::VoxelWeights=VoxelWeights(snapshot)) + loadSubstrates!(snapshot, substrate_names) + data = Dict{String, Real}() + + if voxel_weights.use_weights + mean_fn = x -> (x .* voxel_weights.weights |> sum) / total_weight + else + mean_fn = mean + end + + for substrate_name in substrate_names + data[substrate_name] = mean_fn(snapshot.substrates[!, substrate_name]) + end + return data +end + +"""""" + AverageSubstrateTimeSeries + +A struct to hold the average substrate concentrations over time for a PhysiCell simulation. + +Constructed using `AverageSubstrateTimeSeries(x)` where `x` is any of the following: `Integer` (simulation ID), `PhysiCellSequence`, or `Simulation`. + +# Fields +- `simulation_id::Int`: The ID of the PhysiCell simulation. +- `time::Vector{Real}`: The time points at which the snapshots were taken. +- `substrate_concentrations::Dict{String, Vector{Real}}`: A dictionary mapping substrate names to vectors of their average concentrations over time. + +# Example +```julia +asts = PhysiCellModelManager.AverageSubstrateTimeSeries(1) # Load average substrate time series for Simulation 1 +asts.time # Get the time points +asts[""time""] # alternative way to get the time points +asts[""oxygen""] # Get the oxygen concentration over time +``` +"""""" +struct AverageSubstrateTimeSeries + simulation_id::Int + time::Vector{Real} + substrate_concentrations::Dict{String, Vector{Real}} +end + +function AverageSubstrateTimeSeries(sequence::PhysiCellSequence) + time = [snapshot.time for snapshot in sequence.snapshots] + substrate_concentrations = Dict{String, Vector{Real}}() + substrate_names = substrateNames(sequence) + for substrate_name in substrate_names + substrate_concentrations[substrate_name] = zeros(Float64, length(time)) + end + voxel_weights = VoxelWeights(sequence.snapshots[1]) + for (i, snapshot) in enumerate(sequence.snapshots) + snapshot_substrate_concentrations = averageSubstrate(snapshot, substrate_names, voxel_weights) + for substrate_name in keys(snapshot_substrate_concentrations) + substrate_concentrations[substrate_name][i] = snapshot_substrate_concentrations[substrate_name] + end + end + return AverageSubstrateTimeSeries(sequence.simulation_id, time, substrate_concentrations) +end + +function AverageSubstrateTimeSeries(simulation_id::Integer) + print(""Computing average substrate time series for Simulation $simulation_id..."") + simulation_folder = trialFolder(Simulation, simulation_id) + path_to_summary = joinpath(simulation_folder, ""summary"") + path_to_file = joinpath(path_to_summary, ""average_substrate_time_series.csv"") + if isfile(path_to_file) + df = CSV.read(path_to_file, DataFrame) + asts = AverageSubstrateTimeSeries(simulation_id, df.time, Dict{String, Vector{Real}}(name => df[!, Symbol(name)] for name in names(df) if name != ""time"")) + else + sequence = PhysiCellSequence(simulation_id; include_cells=false, include_substrates=true) + if ismissing(sequence) + return missing + end + mkpath(path_to_summary) + asts = AverageSubstrateTimeSeries(sequence) + df = DataFrame(time=asts.time) + for (name, concentrations) in pairs(asts.substrate_concentrations) + df[!, Symbol(name)] = concentrations + end + CSV.write(path_to_file, df) + end + println(""done."") + return asts +end + +AverageSubstrateTimeSeries(simulation::Simulation) = AverageSubstrateTimeSeries(simulation.id) + +AverageSubstrateTimeSeries(pcmm_output::PCMMOutput{Simulation}) = AverageSubstrateTimeSeries(pcmm_output.trial) + +function Base.getindex(asts::AverageSubstrateTimeSeries, name::String) + if name in keys(asts.substrate_concentrations) + return asts.substrate_concentrations[name] + elseif name == ""time"" + return asts.time + else + throw(ArgumentError(""Invalid substrate name: $name"")) + end +end + +function Base.show(io::IO, asts::AverageSubstrateTimeSeries) + println(io, ""AverageSubstrateTimeSeries for Simulation $(asts.simulation_id)"") + println(io, "" Time: $(formatTimeRange(asts.time))"") + println(io, "" Substrates: $(join(keys(asts.substrate_concentrations), "", ""))"") +end + +"""""" + averageExtracellularSubstrate(snapshot::PhysiCellSnapshot, cell_type_to_name_dict::Dict{Int, String}=Dict{Int, String}(), substrate_names::Vector{String}=String[], labels::Vector{String}=String[]; include_dead::Bool=false) + +Compute the average extracellular substrate concentrations for each cell type in a PhysiCell snapshot. + +# Arguments +- `snapshot::PhysiCellSnapshot`: The snapshot to analyze. +- `cell_type_to_name_dict::Dict{Int, String}`: A dictionary mapping cell type IDs to their names. If not provided, it is read from the snapshot files. +- `substrate_names::Vector{String}`: The names of the substrates in the simulation. If not provided, it is read from the snapshot files. +- `labels::Vector{String}`: The labels to use for the cells. If not provided, it is read from the snapshot files. + +# Keyword Arguments +- `include_dead::Bool`: Whether to include dead cells in the analysis (default is `false`). + +# Returns +- `Dict{String, Dict{String, Real}}`: A dictionary mapping cell type names to dictionaries mapping substrate names to their average concentrations. + +That is, if `aes` is the output of this function, then `aes[""cell_type_name""][""substrate_name""]` is the average concentration of `substrate_name` for cells of type `cell_type_name` in the snapshot. +"""""" +function averageExtracellularSubstrate(snapshot::PhysiCellSnapshot, cell_type_to_name_dict::Dict{Int,String}=Dict{Int,String}(), substrate_names::Vector{String}=String[], labels::Vector{String}=String[]; include_dead::Bool=false) + #! if any of the necessary data is missing, return missing + loadCells!(snapshot, cell_type_to_name_dict, labels) |> ismissing && return missing + loadSubstrates!(snapshot, substrate_names) |> ismissing && return missing + loadMesh!(snapshot) |> ismissing && return missing + + cells = snapshot.cells + substrates = snapshot.substrates + mesh = snapshot.mesh + + aes = Dict{String, Dict{String, Real}}() + cells_to_keep = include_dead ? deepcopy(cells) : cells[.!cells.dead, :] + for cell_type_name in values(cell_type_to_name_dict) + cell_type_cells = cells_to_keep[cells_to_keep.cell_type_name .== cell_type_name, :] + + voxel_inds = computeVoxelIndices(cell_type_cells, mesh) + aes[cell_type_name] = Dict{String, Real}() + for substrate_name in substrate_names + aes[cell_type_name][substrate_name] = substrates[voxel_inds, substrate_name] |> mean + end + end + return aes +end + +"""""" + computeVoxelSubscripts(cells::DataFrame, mesh::Dict{String, Vector{Float64}}) + +Compute the voxel subscripts (1-nx, 1-ny, 1-nz) for a set of cells in a PhysiCell simulation. +"""""" +function computeVoxelSubscripts(cells::DataFrame, mesh::Dict{String, Vector{Float64}}) + voxel_subs = Vector{Tuple{Int, Int, Int}}() + x, y, z = cells[!, [:position_1, :position_2, :position_3]] |> eachcol + + nearest_index(c, v) = (c .- v[1]) / (v[2] - v[1]) .|> round .|> Int .|> x -> x.+1 + is = length(mesh[""x""]) == 1 ? fill(1, (length(x),)) : nearest_index(x, mesh[""x""]) + js = length(mesh[""y""]) == 1 ? fill(1, (length(x),)) : nearest_index(y, mesh[""y""]) + ks = length(mesh[""z""]) == 1 ? fill(1, (length(x),)) : nearest_index(z, mesh[""z""]) + voxel_subs = [(i, j, k) for (i, j, k) in zip(is, js, ks)] + return voxel_subs +end + +"""""" + computeVoxelIndices(cells::DataFrame, mesh::Dict{String, Vector{Float64}}) + +Compute the voxel (linear) indices (1-nx*ny*nz) for a set of cells in a PhysiCell simulation. +"""""" +function computeVoxelIndices(cells::DataFrame, mesh::Dict{String, Vector{Float64}}) + voxel_subs = computeVoxelSubscripts(cells, mesh) + nx, ny = length(mesh[""x""]), length(mesh[""y""]) + voxel_inds = [i + nx * (j-1 + ny * (k-1)) for (i, j, k) in voxel_subs] + return voxel_inds +end + +"""""" + ExtracellularSubstrateTimeSeries + +A struct to hold the mean extracellular substrate concentrations per cell type over time for a PhysiCell simulation. + +# Fields +- `simulation_id::Int`: The ID of the PhysiCell simulation. +- `time::Vector{Real}`: The time points at which the snapshots were taken. +- `data::Dict{String, Dict{String, Vector{Real}}}`: A dictionary mapping cell type names to dictionaries mapping substrate names to vectors of their average concentrations over time. + +# Example +```julia +ests = PhysiCellModelManager.ExtracellularSubstrateTimeSeries(1) # Load extracellular substrate time series for Simulation 1 +ests.time # Get the time points +ests[""cancer""][""oxygen""] # Get the oxygen concentration over time for the cancer cell type + +ests = PhysiCellModelManager.ExtracellularSubstrateTimeSeries(simulation; include_dead=true) # Load extracellular substrate time series for a Simulation object, including dead cells +ests[""time""] # Alternate way to get the time points +ests[""cd8""][""IFNg""] # Get the interferon gamma concentration over time for the CD8 cell type + +ests = PhysiCellModelManager.ExtracellularSubstrateTimeSeries(sequence) # Load extracellular substrate time series for a PhysiCellSequence object +``` +"""""" +struct ExtracellularSubstrateTimeSeries + simulation_id::Int + time::Vector{Real} + data::Dict{String,Dict{String,Vector{Real}}} +end + +function ExtracellularSubstrateTimeSeries(sequence::PhysiCellSequence; include_dead::Bool=false) + time = [snapshot.time for snapshot in sequence.snapshots] + data = Dict{String, Dict{String, Vector{Real}}}() + cell_type_to_name_dict = sequence.cell_type_to_name_dict + substrate_names = substrateNames(sequence) + for (i, snapshot) in enumerate(sequence.snapshots) + snapshot_data = averageExtracellularSubstrate(snapshot, cell_type_to_name_dict, substrate_names, sequence.labels; include_dead=include_dead) + for cell_type_name in keys(snapshot_data) + if !haskey(data, cell_type_name) + data[cell_type_name] = Dict{String, Vector{Real}}() + end + for substrate_name in keys(snapshot_data[cell_type_name]) + if !(substrate_name in keys(data[cell_type_name])) + data[cell_type_name][substrate_name] = zeros(Float64, length(time)) + end + data[cell_type_name][substrate_name][i] = snapshot_data[cell_type_name][substrate_name] + end + end + end + return ExtracellularSubstrateTimeSeries(sequence.simulation_id, time, data) +end + +function ExtracellularSubstrateTimeSeries(simulation_id::Integer; include_dead::Bool=false) + print(""Computing extracellular substrate time series for Simulation $simulation_id..."") + simulation_folder = trialFolder(Simulation, simulation_id) + path_to_summary = joinpath(simulation_folder, ""summary"") + path_to_file = joinpath(path_to_summary, ""extracellular_substrate_time_series$(include_dead ? ""_include_dead"" : """").csv"") + if isfile(path_to_file) + df = CSV.read(path_to_file, DataFrame) + data = Dict{String,Dict{String,Vector{Real}}}() + for name in names(df) + if name == ""time"" + continue + end + cell_type_name, substrate_name = split(name, "" AND "") + if !haskey(data, cell_type_name) + data[cell_type_name] = Dict{String, Vector{Real}}() + end + data[cell_type_name][substrate_name] = df[!, name] + end + ests = ExtracellularSubstrateTimeSeries(simulation_id, df.time, data) + else + sequence = PhysiCellSequence(simulation_id; include_cells=true, include_substrates=true, include_mesh=true) + if ismissing(sequence) + return missing + end + mkpath(path_to_summary) + ests = ExtracellularSubstrateTimeSeries(sequence; include_dead=include_dead) + df = DataFrame(time=ests.time) + for (cell_type_name, data) in pairs(ests.data) + for (substrate_name, concentrations) in pairs(data) + df[!, Symbol(cell_type_name * "" AND "" * substrate_name)] = concentrations + end + end + CSV.write(path_to_file, df) + end + println(""done."") + return ests +end + +ExtracellularSubstrateTimeSeries(simulation::Simulation; kwargs...) = ExtracellularSubstrateTimeSeries(simulation.id; kwargs...) + +ExtracellularSubstrateTimeSeries(pcmm_output::PCMMOutput{Simulation}; kwargs...) = ExtracellularSubstrateTimeSeries(pcmm_output.trial; kwargs...) + +function Base.getindex(ests::ExtracellularSubstrateTimeSeries, name::String) + if name in keys(ests.data) + return ests.data[name] + elseif name == ""time"" + return ests.time + else + throw(ArgumentError(""Invalid cell type name: $name"")) + end +end + +function Base.show(io::IO, ests::ExtracellularSubstrateTimeSeries) + println(io, ""ExtracellularSubstrateTimeSeries for Simulation $(ests.simulation_id)"") + println(io, "" Time: $(formatTimeRange(ests.time))"") + substrates = reduce(hcat, [keys(v) for v in values(ests.data)]) |> unique + println(io, "" Substrates: $(join(substrates, "", ""))"") +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/analysis/motility.jl",".jl","6004","99","export motilityStatistics + +"""""" + _motilityStatistics(p[; direction=:any]) + +Compute the motility statistics for a single cell in the PhysiCell simulation. + +Accounts for cell type transitions and computes the distance traveled, time spent, and mean speed for each cell type the given cell has taken on during the simulation. +The speed can be restricted to a specific direction (x, y, z) or calculated in any direction. +In either case, the distance is unsigned. + +This function is used internally by [`motilityStatistics`](@ref). + +# Returns +A `Dict{String, NamedTuple}` where each key is a cell type name visited by the cell and the value is a `NamedTuple` with fields `:time`, `:distance`, and `:speed`. +The values in this named tuple are the time, distance traveled, and mean speed for the cell in that cell type, i.e., all scalars. +"""""" +function _motilityStatistics(p; direction=:any)::Dict{String, NamedTuple} + x, y, z = [col for col in eachcol(p.position)] + cell_type_name = p.cell_type_name + dx = x[2:end] .- x[1:end-1] + dy = y[2:end] .- y[1:end-1] + dz = z[2:end] .- z[1:end-1] + if direction == :x + dist_fn = (dx, _, _) -> abs(dx) + elseif direction == :y + dist_fn = (_, dy, _) -> abs(dy) + elseif direction == :z + dist_fn = (_, _, dz) -> abs(dz) + elseif direction == :any + dist_fn = (dx, dy, dz) -> sqrt(dx ^ 2 + dy ^ 2 + dz ^ 2) + else + error(""Invalid direction: $direction"") + end + type_change = cell_type_name[2:end] .!= cell_type_name[1:end-1] + start_ind = 1 + cell_type_names = unique(cell_type_name) + distance_dict = Dict{String, Float64}(zip(cell_type_names, zeros(Float64, length(cell_type_names)))) + time_dict = Dict{String, Float64}(zip(cell_type_names, zeros(Float64, length(cell_type_names)))) + while start_ind <= length(type_change) + I = findfirst(type_change[start_ind:end]) #! from s to I, cell_type_name is constant. at I+1 it changes + I = isnothing(I) ? length(type_change)+2-start_ind : I #! if the cell_type_name is constant till the end, set I to be at the end + #! If start_ind = 1 (at start of sim) and I = 2 (so cell_type_name[3] != cell_type_name[2], meaning that for steps [1,2] cell_type_name is constnat), only use dx in stepping from 1->2 since somewhere in 2->3 the type changes. That is, use dx[1] + distance_dict[cell_type_name[start_ind]] += sum(dist_fn.(dx[start_ind:I-1], dy[start_ind:I-1], dz[start_ind:I-1])) #! only count distance travelled while remaining in the initial cell_type_name + time_dict[cell_type_name[start_ind]] += p.time[start_ind+I-1] - p.time[start_ind] #! record time spent in this cell_type_name (note p.time is not diffs like dx and dy are, hence the difference in indices) + start_ind += I #! advance the start to the first instance of a new cell_type_name + end + speed_dict = [k => distance_dict[k] / time_dict[k] for k in cell_type_names] |> Dict{String,Float64} #! convert to speed + per_type_stats = Dict{String, NamedTuple}() + for cell_type_name in cell_type_names + per_type_stats[cell_type_name] = [:time=>time_dict[cell_type_name], :distance=>distance_dict[cell_type_name], :speed=>speed_dict[cell_type_name]] |> NamedTuple + end + return per_type_stats +end + +"""""" + motilityStatistics(simulation_id::Integer[; direction=:any]) + motilityStatistics(simulation::Simulation[; direction=:any]) + motilityStatistics(pcmm_output::PCMMOutput{Simulation}[; direction=:any]) + +Return the mean speed, distance traveled, and time alive for each cell in the simulation, broken down by cell type in the case of cell type transitions. + +The time is counted from when the cell first appears in simulation output until it dies or the simulation ends, whichever comes first. +If the cell transitions to a new cell type during the simulation, the time is counted for each cell type separately. +Each cell type taken on by a given cell will be a key in the dictionary returned at that entry. + +# Arguments +- `simulation_id::Integer`: The ID of the PhysiCell simulation. A `Simulation` object can also be passed in. +- `simulation::Simulation`: The simulation object. +- `pcmm_output::PCMMOutput{Simulation}`: The output of a PCMM simulation run. + +# Keyword Arguments +- `direction::Symbol`: The direction to compute the mean speed. Can be `:x`, `:y`, `:z`, or `:any` (default). If `:x`, for example, the mean speed is calculated using only the x component of the cell's movement. + +# Returns +- `AgentDict{Dict{String, NamedTuple}}`: An [`AgentDict`](@ref), i.e., one entry per cell in the simulation. Each dictionary has keys for each cell type taken on by the cell. The values are NamedTuples with fields `:time`, `:distance`, and `:speed`. + +# Example +```julia +ms = motilityStatistics(1) # an AgentDict{Dict{String, NamedTuple}}, one per cell in the simulation +ms[1][""epithelial""] # NamedTuple with fields :time, :distance, :speed for the cell with ID 1 in the simulation corresponding to its time as an `epithelial` cell +ms[1][""mesenchymal""].time # time spent as a `mesenchymal` cell for the cell with ID 1 in the simulation +ms[1][""mesenchymal""].distance # distance traveled as a `mesenchymal` cell for the cell with ID 1 in the simulation +ms[1][""mesenchymal""].speed # mean speed as a `mesenchymal` cell for the cell with ID 1 in the simulation +``` +"""""" +function motilityStatistics(simulation_id::Integer; direction=:any) + assertInitialized() + sequence = PhysiCellSequence(simulation_id; include_cells=true) + if ismissing(sequence) + return missing + end + pos = cellDataSequence(sequence, ""position""; include_dead=false, include_cell_type_name=true) + return [k => _motilityStatistics(p; direction=direction) for (k, p) in pairs(pos) if length(p.time) > 1] |> AgentDict +end + +motilityStatistics(simulation::Simulation; kwargs...) = motilityStatistics(simulation.id; kwargs...) + +motilityStatistics(pcmm_output::PCMMOutput{Simulation}; kwargs...) = motilityStatistics(pcmm_output.trial, kwargs...)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/analysis/analysis.jl",".jl","160","7","include(""preprocessing.jl"") +include(""graphs.jl"") +include(""motility.jl"") +include(""pcf.jl"") +include(""population.jl"") +include(""substrate.jl"") +include(""runtime.jl"")","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/analysis/preprocessing.jl",".jl","2851","56",""""""" + processIncludeCellTypes(include_cell_type_names, all_cell_types::Vector{String}) + +Process the `include_cell_type_names` argument to ensure it is in the correct format. + +Uses the `all_cell_types` vector to determine the valid cell types. + +# Arguments +- `include_cell_type_names`: the cell types to include in the analysis (default is `:all_in_one`). Full list of options: + - `:all` - return the vector of all cell types + - `:all_in_one` - return a vector with a single element, which is a vector of all cell types + - `""cell_type_1""` - return [""cell_type_1""] + - `[""cell_type_1"", ""cell_type_2""]` - return [""cell_type_1"", ""cell_type_2""] + - `[[""cell_type_1"", ""cell_type_2""]]` - return [[""cell_type_1"", ""cell_type_2""]] + - `[[""cell_type_1"", ""cell_type_2""], ""cell_type_3""]` - return [[""cell_type_1"", ""cell_type_2""], ""cell_type_3""] +- `all_cell_types`: a vector of all cell types in the simulation +"""""" +function processIncludeCellTypes(include_cell_type_names, all_cell_types::Vector{String}) + if include_cell_type_names isa Symbol + #! include_cell_type_names = :all + if include_cell_type_names == :all + return all_cell_types + elseif include_cell_type_names == :all_in_one + return [all_cell_types] + end + throw(ArgumentError(""include_cell_type_names must be :all or :all_in_one if a symbol. Got $include_cell_type_names."")) + elseif include_cell_type_names isa String + #! include_cell_type_names = ""cancer"" + return [include_cell_type_names] + elseif include_cell_type_names isa AbstractVector{<:AbstractString} + #! include_cell_type_names = [""cancer"", ""immune""] + elseif include_cell_type_names isa AbstractVector + #! include_cell_type_names = [[""cancer_epi"", ""cancer_mes""], ""immune""] + @assert isa.(include_cell_type_names, Union{String,AbstractVector{<:AbstractString}}) |> all ""include_cell_type_names must consist of strings and vectors of strings."" + else + throw(ArgumentError(""If listing all cell types to include, use either 1) a string or 2) a vector consisting of strings and vectors of strings. Got $(typeof(include_cell_type_names))."")) + end + return include_cell_type_names +end + +"""""" + processExcludeCellTypes(exclude_cell_type_names) + +Process the `exclude_cell_type_names` argument to ensure it is in the correct format. + +If `exclude_cell_type_names` is a string, it is converted to a single-element vector. +If it is a vector, it is returned as is. +"""""" +function processExcludeCellTypes(exclude_cell_type_names) + if exclude_cell_type_names isa String + return [exclude_cell_type_names] + elseif exclude_cell_type_names isa AbstractVector{<:AbstractString} + return exclude_cell_type_names + end + throw(ArgumentError(""exclude_cell_type_names must be a string or a vector of strings."")) +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","src/analysis/runtime.jl",".jl","2692","74","using Dates + +export simulationRuntime, simulationRuntimeIntervals + +"""""" + simulationRuntime(snapshot::PhysiCellSnapshot) + simulationRuntime(simulation::Simulation) + simulationRuntime(pcmm_output::PCMMOutput{Simulation}) + simulationRuntime(simulation_id::Integer) + +Get the runtime (in nanoseconds) to reach a given snapshot or the final snapshot of a simulation or PCMM output. + +# Examples +```jldoctest +runtime = simulationRuntime(snapshot) +typeof(runtime) +# output +Nanosecond +``` +```julia +using Statistics +sim_ids = 1:4 +runtimes = simulationRuntime.(sim_ids) +exact_mean_runtime = mean([runtime.value for runtime in runtimes]) # in nanoseconds +mean_runtime = Nanosecond(round(exact_mean_runtime)) # rounded to nearest nanosecond +println(canonicalize(mean_runtime)) # e.g. 2 minutes, 53 seconds, 748 milliseconds, 31 microseconds +``` +"""""" + +simulationRuntime(snapshot::PhysiCellSnapshot) = snapshot.runtime +simulationRuntime(simulation::Simulation) = PhysiCellSnapshot(simulation, :final) |> simulationRuntime +function simulationRuntime(simulation_id::Integer) + assertInitialized() + PhysiCellSnapshot(simulation_id, :final) |> simulationRuntime +end +simulationRuntime(pcmm_output::PCMMOutput{Simulation}) = pcmm_output.trial |> simulationRuntime + +"""""" + simulationRuntimeIntervals(sequence::PhysiCellSequence) + simulationRuntimeIntervals(simulation::Simulation) + simulationRuntimeIntervals(pcmm_output::PCMMOutput{Simulation}) + simulationRuntimeIntervals(simulation_id::Integer) + +Get the runtime intervals of a simulation. + +# Returns +A named tuple with the time and runtime vectors. +Each entry corresponds to the amount of runtime to simulate from the previous snapshot to the current snapshot. + +# Examples +```julia +seq = simulationRuntimeIntervals(1) +using Plots +plot(seq.time, seq.runtime) # plot time from previous save time vs time +plot(seq.time, cumsum(seq.runtime)) # plot time vs cumulative runtime (same as plotting against the runtime values of each snapshot) +``` +"""""" +function simulationRuntimeIntervals(sequence::PhysiCellSequence) + time = [snapshot.time for snapshot in sequence.snapshots] + runtime = vcat(Nanosecond(0), map(s -> simulationRuntime(s), sequence.snapshots)) |> diff + return (; time=time, runtime=runtime) +end + +function simulationRuntimeIntervals(simulation::Simulation) + sequence = PhysiCellSequence(simulation) + return simulationRuntimeIntervals(sequence) +end + +simulationRuntimeIntervals(pcmm_output::PCMMOutput{Simulation}) = simulationRuntimeIntervals(pcmm_output.trial) +function simulationRuntimeIntervals(simulation_id::Integer) + assertInitialized() + PhysiCellSequence(simulation_id) |> simulationRuntimeIntervals +end +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/runtests.jl",".jl","1033","45","using PhysiCellModelManager, Test + +include(""./test-scripts/PrintHelpers.jl"") + +test_order = [ + ""CreateProjectTests.jl"", + ""ProjectConfigurationTests.jl"", + ""RunnerTests.jl"", + ""UserAPITests.jl"", + ""ImportTests.jl"", + ""PrunerTests.jl"", + ""ConfigurationTests.jl"", + ""IntracellularTests.jl"", + ""ICCellTests.jl"", + ""ICECMTests.jl"", + ""ExportTests.jl"", + ""SensitivityTests.jl"", + ""DatabaseTests.jl"", + ""ClassesTests.jl"", + ""LoaderTests.jl"", + ""MovieTests.jl"", + ""PopulationTests.jl"", + ""SubstrateTests.jl"", + ""GraphsTests.jl"", + ""PCFTests.jl"", + ""RuntimeTests.jl"", + ""VariationsTests.jl"", + ""HPCTests.jl"", + ""ModuleTests.jl"", + ""PhysiCellVersionTests.jl"", + ""PhysiCellStudioTests.jl"", + ""DeletionTests.jl"", + ""DepsTests.jl"" +] + +@testset ""PhysiCellModelManager.jl"" begin + + for test_file in test_order + @testset ""$test_file"" begin + include(""./test-scripts/$(test_file)"") + @test_nowarn PhysiCellModelManager.databaseDiagnostics() + end + end + +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/ConfigurationTests.jl",".jl","12114","234","using LightXML + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +config_folder = ""0_template"" +custom_code_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder) + +n_replicates = 2 + +path_to_xml = joinpath(""data"", ""inputs"", ""configs"", config_folder, ""PhysiCell_settings.xml"") + +cell_type = ""default"" +substrate = ""substrate"" + +#! build all the possible path elements supported by the configPath function + #! single token paths +single_tokens = [""x_min"", ""x_max"", ""y_min"", ""y_max"", ""z_min"", ""z_max"", ""dx"", ""dy"", ""dz"", ""use_2D"", ""max_time"", ""dt_intracellular"", ""dt_diffusion"", ""dt_mechanics"", ""dt_phenotype"", ""full_data_interval"", ""SVG_save_interval""] +element_paths = configPath.(single_tokens) + + #! double token paths +substrate_double_tokens = [""diffusion_coefficient"", ""decay_rate"", ""initial_condition"", ""Dirichlet_boundary_condition"", ""xmin"", ""xmax"", ""ymin"", ""ymax"", ""zmin"", ""zmax""] +append!(element_paths, [configPath(substrate, token) for token in substrate_double_tokens]) + +cell_type_double_tokens = [""total"", ""fluid_fraction"", ""nuclear"", ""fluid_change_rate"", ""cytoplasmic_biomass_change_rate"", ""nuclear_biomass_change_rate"", ""calcified_fraction"", ""calcification_rate"", ""relative_rupture_volume"", ""cell_cell_adhesion_strength"", ""cell_cell_repulsion_strength"", ""relative_maximum_adhesion_distance"", ""attachment_elastic_constant"", ""attachment_rate"", ""detachment_rate"", ""maximum_number_of_attachments"", ""set_relative_equilibrium_distance"", ""set_absolute_equilibrium_distance"", ""speed"", ""persistence_time"", ""migration_bias"", ""apoptotic_phagocytosis_rate"", ""necrotic_phagocytosis_rate"", ""other_dead_phagocytosis_rate"", ""attack_damage_rate"", ""attack_duration"", ""damage_rate"", ""damage_repair_rate"", ""custom:sample""] +append!(element_paths, [configPath(cell_type, token) for token in cell_type_double_tokens]) + +push!(element_paths, configPath(""user_parameters"", ""number_of_cells"")) +push!(element_paths, PhysiCellModelManager.userParametersPath(""number_of_cells"")) + +save_double_tokens = [""full"", ""SVG"", ""svg""] +append!(element_paths, [configPath(""save"", token) for token in save_double_tokens]) + + #! triple token paths +append!(element_paths, [configPath(substrate, ""Dirichlet_options"", token) for token in [""xmin"", ""xmax"", ""ymin"", ""ymax"", ""zmin"", ""zmax""]]) + +append!(element_paths, [configPath(cell_type, tag, 0) for tag in [""cycle_rate"", ""cycle_duration""]]) + +common_death_tags = [""rate"", ""unlysed_fluid_change_rate"", ""lysed_fluid_change_rate"", ""cytoplasmic_biomass_change_rate"", ""nuclear_biomass_change_rate"", ""calcification_rate"", ""relative_rupture_volume""] +append!(element_paths, [configPath(cell_type, ""apoptosis"", tag) for tag in common_death_tags]) +append!(element_paths, [configPath(cell_type, ""necrosis"", tag) for tag in common_death_tags]) + +append!(element_paths, [configPath(cell_type, ""apoptosis"", tag) for tag in [""duration"", ""transition_rate""]]) +append!(element_paths, [configPath(cell_type, ""necrosis"", tag) for tag in [""duration_0"", ""transition_rate_0"", ""duration_1"", ""transition_rate_1""]]) + +push!(element_paths, configPath(cell_type, ""adhesion"", cell_type)) + +append!(element_paths, [configPath(cell_type, ""motility"", tag) for tag in [""enabled"", ""use_2D""]]) +append!(element_paths, [configPath(cell_type, ""chemotaxis"", tag) for tag in [""enabled"", ""substrate"", ""direction""]]) +append!(element_paths, [configPath(cell_type, ""advanced_chemotaxis"", tag) for tag in [""enabled"", ""normalize_each_gradient"", substrate]]) + +append!(element_paths, [configPath(cell_type, substrate, tag) for tag in [""secretion_rate"", ""secretion_target"", ""uptake_rate"", ""net_export_rate""]]) +append!(element_paths, [configPath(cell_type, ""phagocytose"", tag) for tag in [""apoptotic"", ""necrotic"", ""other_dead"", cell_type]]) + +append!(element_paths, [configPath(cell_type, tag, cell_type) for tag in [""fuse to"", ""attack"", ""transform to""]]) +push!(element_paths, PhysiCellModelManager.attackPath(cell_type, cell_type)) +push!(element_paths, PhysiCellModelManager.attackRatesPath(cell_type, cell_type)) + +push!(element_paths, configPath(cell_type, ""custom"", ""sample"")) + + #! four token paths +append!(element_paths, [configPath(cell_type, ""cycle"", tag, 0) for tag in [""duration"", ""rate""]]) +append!(element_paths, [configPath(cell_type, ""necrosis"", tag1, tag2) for tag1 in [""duration"", ""transition_rate""], tag2 in [0, 1]] |> vec) +append!(element_paths, [configPath(cell_type, ""initial_parameter_distribution"", ""Volume"", tag) for tag in [""mu"", ""sigma"", ""lower_bound"", ""upper_bound""]]) +append!(element_paths, [configPath(cell_type, ""initial_parameter_distribution"", ""apoptosis"", tag) for tag in [""min"", ""max""]]) + +#! these paths are known not to be in the template xml (but could be in other xmls) +paths_not_in_template = [ + configPath(""dt_intracellular""), + configPath(cell_type, ""cycle"", ""rate"", 0), + configPath(cell_type, ""apoptosis"", ""transition_rate""), + configPath(cell_type, ""necrosis"", ""transition_rate"", 0), + configPath(cell_type, ""necrosis"", ""transition_rate"", 1), + configPath(cell_type, ""initial_parameter_distribution"", ""Volume"", ""lower_bound"") +] + +#! these are paths that have already been accounted for or don't want to try varying (maybe not a number) +paths_to_skip = [ + configPath(""max_time""), + configPath(""use_2D""), + configPath(""full_data_interval""), + configPath(""SVG_save_interval""), + configPath.([""x_min"", ""x_max"", ""y_min"", ""y_max"", ""z_min"", ""z_max"", ""dx"", ""dy"", ""dz""])..., + [configPath(cell_type, ""motility"", tag) for tag in [""enabled"", ""use_2D""]]..., + [configPath(cell_type, ""chemotaxis"", tag) for tag in [""enabled"", ""substrate"", ""direction""]]..., + [configPath(cell_type, ""advanced_chemotaxis"", tag) for tag in [""enabled"", ""normalize_each_gradient""]]... +] + +xml_doc = parse_file(path_to_xml) +indices_to_pop = [] +for (i, ep) in enumerate(element_paths) + ce = PhysiCellModelManager.retrieveElement(xml_doc, ep; required=false) + test_fn = !isnothing #! default test function + if ep in paths_not_in_template + test_fn = isnothing + push!(indices_to_pop, i) + elseif ep in paths_to_skip + push!(indices_to_pop, i) + else + push!(paths_to_skip, ep) #! do not vary this parameter two times! + end + if (@test test_fn(ce)) isa Test.Fail + println(""Element $(ep) was not retrieved as expected. Expected to get $(test_fn)"") + end +end +free(xml_doc) +for i in reverse(indices_to_pop) + popat!(element_paths, i) +end + +@test_throws ArgumentError configPath(""not_a_par"") +@test_throws ArgumentError configPath(cell_type, ""not_a_par"") +@test_throws ArgumentError configPath(cell_type, ""not_a_tag"", ""par"") +@test_throws ArgumentError configPath(cell_type, ""apoptosis"", ""duration"", 0) +@test_throws ArgumentError configPath(""too"", ""many"", ""args"", ""for"", ""configPath"") +@test_throws ArgumentError configPath(cell_type, ""apoptosis"", ""not_a_death_par"") +@test_throws ArgumentError configPath(cell_type, ""necrosis"", ""not_a_death_par"") + +discrete_variations = [] +for (i, xml_path) in enumerate(element_paths) + if xml_path[end] == ""number_of_cells"" + push!(discrete_variations, DiscreteVariation(xml_path, [1, 2])) + else + push!(discrete_variations, DiscreteVariation(xml_path, float(i))) + end +end +@test_throws ArgumentError PhysiCellModelManager.phagocytosisPath(cell_type, :not_a_type) +push!(discrete_variations, DiscreteVariation([""overall"", ""max_time""], [12.0])) + +out = run(inputs, discrete_variations; n_replicates=n_replicates) + +@test out.trial isa Sampling +@test length(out.trial) == prod(length.(discrete_variations)) * n_replicates +@test out.n_success == length(out.trial) + +## test the in place functions +reference_monad = out.trial.monads[1] + +monads = Monad[] +discrete_variations = DiscreteVariation[] +addDomainVariationDimension!(discrete_variations, (x_min=-78.1, x_max=78.1, y_min=-30.1, y_max=30.1, z_min=-10.1, z_max=10.1)) +monad = createTrial(reference_monad, discrete_variations; n_replicates=n_replicates) +push!(monads, monad) + +discrete_variations = DiscreteVariation[] +addDomainVariationDimension!(discrete_variations, (min_x=-78.2, maxy=30.2)) +monad = createTrial(reference_monad, discrete_variations; n_replicates=n_replicates) +push!(monads, monad) + +@test_throws ArgumentError addDomainVariationDimension!(discrete_variations, (x=70, )) +@test_throws AssertionError addDomainVariationDimension!(discrete_variations, (u_min=70, )) + +sampling_1 = Sampling(monads) + +discrete_variations = DiscreteVariation[] +xml_path = configPath(cell_type, ""speed"") +push!(discrete_variations, DiscreteVariation(xml_path, [0.1, 1.0])) +addCustomDataVariationDimension!(discrete_variations, cell_type, ""sample"", [0.1, 1.0]) +sampling_2 = createTrial(reference_monad, discrete_variations; n_replicates=n_replicates) + +trial = Trial([sampling_1, sampling_2]) + +out = run(trial; force_recompile=false) +@test out.n_success == length(trial) + +hashBorderPrint(""SUCCESSFULLY VARIED CONFIG PARAMETERS!"") + +discrete_variations = [] + +xml_path = rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""max_response"") +push!(discrete_variations, DiscreteVariation(xml_path, [0.0, 1e-8])) +xml_path = rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""signal:name:pressure"", ""half_max"") +push!(discrete_variations, DiscreteVariation(xml_path, [0.25, 0.75])) + +out = run(reference_monad, discrete_variations; n_replicates=n_replicates) + +@test out.n_success == length(out.trial) + +hashBorderPrint(""SUCCESSFULLY VARIED RULESETS PARAMETERS!"") + +discrete_variations = [] +xml_path = configPath(cell_type, ""speed"") +push!(discrete_variations, DiscreteVariation(xml_path, [0.1, 1.0])) +xml_path = rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""signal:name:pressure"", ""half_max"") +push!(discrete_variations, DiscreteVariation(xml_path, [0.3, 0.6])) + +out = run(reference_monad, discrete_variations; n_replicates=n_replicates) +@test out.n_success == length(out.trial) + +hashBorderPrint(""SUCCESSFULLY VARIED CONFIG AND RULESETS PARAMETERS!"") + +# one last set of tests for coverage +discrete_variations = DiscreteVariation[] + +addAttackRateVariationDimension!(discrete_variations, cell_type, cell_type, [0.1]) + +out = run(reference_monad, discrete_variations; n_replicates=n_replicates) +@test out.n_success == length(out.trial) + +@test isnothing(PhysiCellModelManager.prepareVariedInputFolder(:custom_code, Sampling(1))) #! returns nothing because custom codes is not varied +@test_throws ArgumentError PhysiCellModelManager.shortLocationVariationID(:not_a_location) +@test_nowarn PhysiCellModelManager.shortVariationName(:intracellular, ""not_a_var"") +@test_nowarn PhysiCellModelManager.shortVariationName(:intracellular, ""intracellular_variation_id"") +@test_throws ArgumentError PhysiCellModelManager.shortVariationName(:not_a_location, ""not_a_var"") + +xml_doc = parse_file(path_to_xml) +xml_path = [""not"", ""a"", ""path""] +@test_throws ArgumentError PhysiCellModelManager.retrieveElement(xml_doc, xml_path) + +# test the xml rules extended +xml_path = rulePath(""increasing_partial_hill"", ""custom:sample"", ""increasing_signals"", ""max_response"") +vals = [0.1, 1.0] +dv = DiscreteVariation(xml_path, vals) + +config_folder = rules_folder = custom_code_folder = ic_cell_folder = ""template_xml_rules_extended"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rules_folder, ic_cell=ic_cell_folder) +sampling = createTrial(inputs, dv) +PhysiCellModelManager.prepareVariedInputFolder(:rulesets_collection, sampling) +run(sampling) + +# test that a bad path throws an error +cell_definition = ""increasing_partial_hill"" +xml_path = PhysiCellModelManager.cyclePath(cell_definition, ""phase_transition_rates"") +@test_throws AssertionError createTrial(inputs, DiscreteVariation(xml_path, [0.1, 1.0])) + +xml_path = PhysiCellModelManager.phenotypePath(cell_definition, ""volume"") +@test_throws AssertionError createTrial(inputs, DiscreteVariation(xml_path, [0.1, 1.0])) + +xml_path = [""save"", ""SVG"", ""plot_substrate"", ""min_conc""] +@test_throws AssertionError createTrial(inputs, DiscreteVariation(xml_path, [0.1, 1.0]))","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/VariationsTests.jl",".jl","6962","146","using Distributions + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +config_folder = ""0_template"" +custom_code_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +ic_cell_folder = ""1_xml"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder, ic_cell=ic_cell_folder) + +cell_type = ""default"" + +xml_path = configPath(cell_type, ""apoptosis"", ""death_rate"") +dv = UniformDistributedVariation(xml_path, 0.0, 1.0) +@test_throws ErrorException PhysiCellModelManager.variationValues(dv) + +discrete_variation = DiscreteVariation(xml_path, [0.0, 1.0]) +@test_throws ErrorException cdf(discrete_variation, 0.5) + +sobol_variation = PhysiCellModelManager.SobolVariation(; pow2=8) +rbd_variation = PhysiCellModelManager.RBDVariation(16; pow2_diff=0, num_cycles=1//2) +rbd_variation = PhysiCellModelManager.RBDVariation(16; num_cycles=1, use_sobol=false) + +discrete_variations = DiscreteVariation[] +xml_path = rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""max_response"") +vals = [1.0, 2.0] +push!(discrete_variations, DiscreteVariation(xml_path, vals)) + +# Test edge cases of addGrid +add_variations_result = PhysiCellModelManager.addVariations(GridVariation(), inputs, discrete_variations) + +# Test edge cases of addLHS +add_variations_result = PhysiCellModelManager.addVariations(LHSVariation(4), inputs, discrete_variations) + +discrete_variations = DiscreteVariation[] +xml_path = PhysiCellModelManager.cyclePath(cell_type, ""phase_durations"", ""duration:index:0"") +push!(discrete_variations, DiscreteVariation(xml_path, [1.0, 2.0])) +add_variations_result = PhysiCellModelManager.addVariations(LHSVariation(; n=4), inputs, discrete_variations) + +discrete_variations = DiscreteVariation[] +xml_path = icCellsPath(""default"", ""disc"", 1, ""x0"") +vals = [0.0, -100.0] +push!(discrete_variations, DiscreteVariation(xml_path, vals)) +add_variations_result = PhysiCellModelManager.addVariations(LHSVariation(4), inputs, discrete_variations) + +# Test edge cases of addSobol +add_variations_result = PhysiCellModelManager.addVariations(PhysiCellModelManager.SobolVariation(5), inputs, discrete_variations) + +discrete_variations = DiscreteVariation[] +xml_path = PhysiCellModelManager.cyclePath(cell_type, ""phase_durations"", ""duration:index:0"") +push!(discrete_variations, DiscreteVariation(xml_path, [1.0, 2.0])) +add_variations_result = PhysiCellModelManager.addVariations(PhysiCellModelManager.SobolVariation(5; skip_start=false), inputs, discrete_variations) + +discrete_variations = DiscreteVariation[] +xml_path = rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""max_response"") +vals = [1.0, 2.0] +push!(discrete_variations, DiscreteVariation(xml_path, vals)) +add_variations_result = PhysiCellModelManager.addVariations(PhysiCellModelManager.SobolVariation(5; skip_start=4, include_one=true), inputs, discrete_variations) + +# Test edge cases of addRBD +add_variations_result = PhysiCellModelManager.addVariations(PhysiCellModelManager.RBDVariation(1), inputs, discrete_variations) + +discrete_variations = DiscreteVariation[] +xml_path = icCellsPath(""default"", ""disc"", 1, ""x0"") +vals = [0.0, -100.0] +push!(discrete_variations, DiscreteVariation(xml_path, vals)) +add_variations_result = PhysiCellModelManager.addVariations(PhysiCellModelManager.RBDVariation(2), inputs, discrete_variations) + +discrete_variations = DiscreteVariation[] +xml_path = PhysiCellModelManager.cyclePath(cell_type, ""phase_durations"", ""duration:index:0"") +push!(discrete_variations, DiscreteVariation(xml_path, [1.0, 2.0])) +add_variations_result = PhysiCellModelManager.addVariations(PhysiCellModelManager.RBDVariation(3), inputs, discrete_variations) + +add_variations_result = PhysiCellModelManager.addVariations(PhysiCellModelManager.RBDVariation(3; use_sobol=false), inputs, discrete_variations) + +# test ElementaryVariation to initialize both DiscreteVariation and DistributedVariation +@test ElementaryVariation(xml_path, [0.0, 1.0]) isa DiscreteVariation +@test ElementaryVariation(xml_path, Uniform(0.0, 1.0)) isa DistributedVariation + +# CoVariation tests +config_folder = ""0_template"" +custom_code_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +ic_cell_folder = ""1_xml"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder, ic_cell=ic_cell_folder) + +dv_max_time = DiscreteVariation([""overall"", ""max_time""], 12.0) +apoptosis_rate_path = configPath(cell_type, ""apoptosis"", ""death_rate"") +cycle_rate_path = PhysiCellModelManager.cyclePath(cell_type, ""phase_durations"", ""duration:index:0"") +val_1 = [0.0, 1.0] +val_2 = [1000.0, 2000.0] +cv = CoVariation((apoptosis_rate_path, val_1), (cycle_rate_path, val_2)) +println(stdout, cv) + +sampling = createTrial(inputs, [dv_max_time, cv]; n_replicates=2) +@test length(PhysiCellModelManager.constituentIDs(sampling)) == 2 +@test length(sampling) == 4 + +df = PhysiCellModelManager.simulationsTable(sampling) +drs = df[!, Symbol(""default: apop death rate"")] +pdurs = df[!, Symbol(""default: duration:index:0"")] +for (dr, pdur) in zip(drs, pdurs) + @test (val_1.==dr) == (val_2.==pdur) #! make sure they are using the same index in both +end + +max_response_path = rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""max_response"") +mrs = [1.0, 2.0] + +x0_path = icCellsPath(""default"", ""disc"", 1, ""x0"") +x0s = [0.0, -100.0] + +cv_new = CoVariation([cv.variations; DiscreteVariation(max_response_path, mrs); DiscreteVariation(x0_path, x0s)]) +cv_test = CoVariation(cv_new.variations...) +sampling = createTrial(inputs, [dv_max_time, cv_new]; n_replicates=3) +@test length(PhysiCellModelManager.constituentIDs(sampling)) == 2 +@test length(sampling) == 6 + +d_1 = Uniform(0, 1) +d_2 = Normal(3, 0.01) +cv = CoVariation((apoptosis_rate_path, d_1), (cycle_rate_path, d_2)) +sampling = createTrial(LHSVariation(5), inputs, cv; n_replicates=3) +@test length(PhysiCellModelManager.constituentIDs(sampling)) == 5 +@test length(sampling) == 15 +@test PhysiCellModelManager.variationLocation(cv) == [:config, :config] +@test PhysiCellModelManager.variationTarget(cv) == PhysiCellModelManager.XMLPath.([apoptosis_rate_path, cycle_rate_path]) + +cv = CoVariation(cv.variations[1], cv.variations[2]) #! CoVariation(ev1, ev2, ...) +sampling = createTrial(SobolVariation(7), inputs, cv; n_replicates=2) +@test length(PhysiCellModelManager.constituentIDs(sampling)) == 7 + +# more tests for coverage +ev = DiscreteVariation(rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""signal:name:pressure"", ""applies_to_dead""), [true, false]) +@test PhysiCellModelManager.sqliteDataType(ev) == ""TEXT"" + +ev = DiscreteVariation([""options"", ""random_seed""], [""system_clock"", 0]) +@test PhysiCellModelManager.sqliteDataType(ev) == ""TEXT"" + +println(stdout, PhysiCellModelManager.XMLPath(xml_path)) +println(stdout, ev) +println(stdout, UniformDistributedVariation(xml_path, 0.0, 1.0)) +println(stdout, cv) + +deleteSimulationsByStatus(""Not Started""; user_check=false)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/HPCTests.jl",".jl","2785","73","using Dates + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +PhysiCellModelManager.useHPC() + +simulation = Simulation(1) +monad = Monad(simulation) + +cmd_local = PhysiCellModelManager.prepareSimulationCommand(simulation, monad.id, true, false) +cmd_local_str = string(Cmd(cmd_local.exec)) +cmd_local_str = strip(cmd_local_str, '`') +cmd_hpc = PhysiCellModelManager.prepareHPCCommand(cmd_local, simulation.id) + +cmd_string = string(cmd_hpc) +cmd_string = strip(cmd_string, '`') + +@test startswith(cmd_string, ""sbatch"") +@test contains(cmd_string, ""--wrap=$(cmd_local_str)"") +@test contains(cmd_string, ""--wait"") + +# test prep of command +# gh actions runners not expected to have `sbatch` installed +simulation_process = PhysiCellModelManager.SimulationProcess(simulation) +@test isnothing(simulation_process.process) +@test !simulation_process.success + +# test hpc removal of file that does not exist +@test isnothing(PhysiCellModelManager.rm_hpc_safe(""not_a_file.txt"")) + +# test hpc removal of file that does exist +current_time = Dates.now() +threshold_seconds = 15 +end_of_day = DateTime(Dates.year(current_time), Dates.month(current_time), Dates.day(current_time), 23, 59, 59) +threshold_time = end_of_day - Second(threshold_seconds) +is_about_to_be_next_day = current_time >= threshold_time +if is_about_to_be_next_day + #! if it's about to be the next day, wait until it is the next day + sleep(threshold_seconds + 1) +end +path_to_dummy_file = joinpath(PhysiCellModelManager.dataDir(), ""test.txt"") +open(path_to_dummy_file, ""w"") do f + write(f, ""test"") +end +PhysiCellModelManager.rm_hpc_safe(path_to_dummy_file) +@test joinpath(PhysiCellModelManager.dataDir(), "".trash"", ""data-$(Dates.format(now(), ""yymmdd""))"", ""test.txt"") |> isfile + +# test hpc removal of file with same name +path_to_dummy_file = joinpath(PhysiCellModelManager.dataDir(), ""test.txt"") +open(path_to_dummy_file, ""w"") do f + write(f, ""test"") +end +PhysiCellModelManager.rm_hpc_safe(path_to_dummy_file) +@test joinpath(PhysiCellModelManager.dataDir(), "".trash"", ""data-$(Dates.format(now(), ""yymmdd""))"", ""test-1.txt"") |> isfile + +# revert back to not using HPC for remainder of tests +PhysiCellModelManager.useHPC(false) + +new_hpc_options = Dict(""cpus-per-task"" => ""2"", + ""job-name"" => simulation_id -> ""test_$(simulation_id)"") +PhysiCellModelManager.setJobOptions(new_hpc_options) +@test PhysiCellModelManager.pcmm_globals.sbatch_options[""cpus-per-task""] == ""2"" +hpc_command = PhysiCellModelManager.prepareHPCCommand(cmd_local, 78) + +cmd_string = string(hpc_command) +cmd_string = strip(cmd_string, '`') +@assert contains(cmd_string, ""--cpus-per-task=2"") +@assert contains(cmd_string, ""--job-name=test_78"") + +deleteSimulationsByStatus(""Failed""; user_check=false)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/ICCellTests.jl",".jl","2186","62","using LightXML, PhysiCellCellCreator + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +config_folder = ""0_template"" +custom_code_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +ic_cell_folder = ""1_xml"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder, ic_cell=ic_cell_folder) + +n_replicates = 1 + +discrete_variations = [] +push!(discrete_variations, DiscreteVariation(configPath(""max_time""), 12.0)) +push!(discrete_variations, DiscreteVariation(configPath(""full_data""), 6.0)) +push!(discrete_variations, DiscreteVariation(configPath(""svg_save""), 6.0)) + +xml_path = icCellsPath(""default"", ""disc"", 1, ""x0"") +vals = [0.0, -100.0] +push!(discrete_variations, DiscreteVariation(xml_path, vals)) + +xml_path = icCellsPath(""default"", ""disc"", 1, ""rectangle"", 1, ""x0"") +vals = [0.0, 1.0] +push!(discrete_variations, DiscreteVariation(xml_path, vals)) + +out = run(inputs, discrete_variations; n_replicates=n_replicates) + +@test out.trial isa Sampling + +hashBorderPrint(""SUCCESSFULLY ADDED IC CELL VARIATION!"") + +hashBorderPrint(""SUCCESSFULLY CREATED SAMPLING WITH IC CELL VARIATION!"") + +@test out.n_success == length(out.trial) + +simulation_with_ic_cell_xml_id = simulationIDs(out.trial)[1] #! used in ExportTests.jl + +hashBorderPrint(""SUCCESSFULLY RAN SAMPLING WITH IC CELL VARIATION!"") + +discrete_variations = [] +xml_path = icCellsPath(""default"", ""annulus"", 1, ""inner_radius"") +push!(discrete_variations, DiscreteVariation(xml_path, 300.0)) + +out_fail = run(out.trial.monads[1], discrete_variations; n_replicates=n_replicates) +@test out_fail.n_success == 0 + +deleteSimulations(out_fail.trial.id) + +ic_cell_folder = PhysiCellModelManager.createICCellXMLTemplate(""2_xml"") +@test ic_cell_folder == ""2_xml"" +@test isdir(PhysiCellModelManager.locationPath(:ic_cell, ic_cell_folder)) +@test_nowarn PhysiCellModelManager.createICECMXMLTemplate(ic_cell_folder) + +xml_path = icCellsPath(""default"", ""disc"", 1, ""x0"") +dv1 = DiscreteVariation(xml_path, -1e6) #! outside the domain so none can be placed +out_fail = run(inputs, dv1) +@test out_fail.n_success == 0 + +deleteSimulations(out_fail.trial.id)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/PrunerTests.jl",".jl","924","23","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +config_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +custom_code_folder = ""0_template"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder) + +discrete_variations = [] +push!(discrete_variations, DiscreteVariation(configPath(""max_time""), 12.0)) +push!(discrete_variations, DiscreteVariation(configPath(""full_data""), 6.0)) +push!(discrete_variations, DiscreteVariation(configPath(""svg_save""), 6.0)) + +simulation = createTrial(inputs, discrete_variations; use_previous=false) +@test simulation isa Simulation + +prune_options = PruneOptions(true, true, true, true, true, true) +out = run(simulation; force_recompile=false, prune_options=prune_options) +@test out.n_success == 1 + +pruned_simulation_id = simulation.id #! save this for use in other tests","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/IntracellularTests.jl",".jl","1193","23","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +config = ""template-combined"" +custom_code = ""template-combined"" +cell_to_components_dict = Dict(""default"" => PhysiCellComponent(""roadrunner"", ""Toy_Metabolic_Model.xml"")) +intracellular = assembleIntracellular!(cell_to_components_dict; name=""template-combined"") +inputs = InputFolders(config, custom_code; intracellular=intracellular) + +dv1 = DiscreteVariation([""overall"", ""max_time""], 12.0) +xml_path = [""intracellulars"", ""intracellular:ID:1"", ""sbml"", ""model"", ""listOfReactions"", ""reaction:id:Aerobic"", ""kineticLaw"", ""math"", ""apply"", ""apply"", ""cn""] +dv2 = DiscreteVariation(xml_path, [5, 6]) +pcmm_output_intracellular = run(inputs, [dv1, dv2]) #! save for later use +@test pcmm_output_intracellular.n_success == 2 + +macros_lines = PhysiCellModelManager.readMacrosFile(pcmm_output_intracellular.trial) +@test ""ADDON_ROADRUNNER"" in macros_lines + +#! more test coverage +new_intracellular = assembleIntracellular!(cell_to_components_dict; name=""template-combined"") +@test intracellular == new_intracellular #! should not need to make a new folder, the assembly.toml file should show they match","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/RunnerTests.jl",".jl","3950","99","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +n_sims = length(Monad(1)) +monad = Monad(1; n_replicates=1, use_previous=false) +run(monad) +@test length(monad) == n_sims + 1 #! how many simulations were attached to this monad when run +@test length(simulationIDs(monad)) == n_sims+1 #! how many simulations are stored in simulations.csv + +config_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +custom_code_folder = ""0_template"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder) + +n_replicates = 1 + +discrete_variations = [] +push!(discrete_variations, DiscreteVariation(configPath(""max_time""), 12.0)) +push!(discrete_variations, DiscreteVariation(configPath(""full_data""), 6.0)) +push!(discrete_variations, DiscreteVariation(configPath(""svg_save""), 6.0)) + +simulation = createTrial(inputs, discrete_variations) + +out = run(simulation) +@test out.trial isa Simulation +@test out.n_scheduled == 1 +@test out.n_success == 1 + +out2 = run(inputs, discrete_variations) +@test out2.trial isa Simulation +@test out2.n_scheduled == 0 +@test out2.n_success == 0 + +@test PhysiCellModelManager.trialID(out) == PhysiCellModelManager.trialID(out2) +@test out.trial.inputs == out2.trial.inputs +@test out.trial.variation_id == out2.trial.variation_id + +query = PhysiCellModelManager.constructSelectQuery(""simulations"", ""WHERE simulation_id=1"") +df = PhysiCellModelManager.queryToDataFrame(query; is_row=true) + +cell_type = ""default"" +discrete_variations = [] +xml_path = configPath(cell_type, ""cycle_duration"", 0) +push!(discrete_variations, DiscreteVariation(xml_path, [1.0, 2.0])) +xml_path = configPath(cell_type, ""cycle_duration"", 1) +push!(discrete_variations, DiscreteVariation(xml_path, 3.0)) +xml_path = configPath(cell_type, ""cycle_duration"", 2) +push!(discrete_variations, DiscreteVariation(xml_path, 4.0)) +xml_path = configPath(cell_type, ""cycle_duration"", 3) +push!(discrete_variations, DiscreteVariation(xml_path, 5.0)) + +sampling = createTrial(simulation, discrete_variations; n_replicates=n_replicates) + +out = run(sampling; force_recompile=false) +@test out.n_success == length(sampling) + +out2 = run(simulation, discrete_variations; n_replicates=n_replicates, force_recompile=false) +@test out2.trial isa Sampling +@test PhysiCellModelManager.trialID(out2) == sampling.id +@test out2.trial.inputs == sampling.inputs +@test Set(PhysiCellModelManager.constituentIDs(out2.trial)) == Set(PhysiCellModelManager.constituentIDs(sampling)) +@test Set(PhysiCellModelManager.simulationIDs(out2.trial)) == Set(PhysiCellModelManager.simulationIDs(sampling)) +@test out2.n_scheduled == 0 +@test out2.n_success == 0 + +n_simulations = length(sampling) #! number of simulations recorded (in .csvs) for this sampling +n_expected_sims = n_replicates * (discrete_variations .|> length |> prod) +n_variations = length(sampling.monads) + +# make sure the number of simulations in this sampling is what we expected based on... +@test n_simulations == n_expected_sims #! the discrete_variations... +@test n_simulations == n_variations * n_replicates #! ...how many variation ids we recorded (number of rulesets_variations_ids must match variation_ids on construction of sampling) +@test n_simulations == out.n_success #! ...how many simulations succeeded + +out = run(sampling; force_recompile=false) + +# no new simulations should have been run +@test out.n_success == 0 + +trial = Trial([sampling]) +@test trial isa Trial + +out = run(trial; force_recompile=false) + +# no new simulations should have been run +@test out.n_success == 0 + +@test_warn ""`runAbstractTrial` is deprecated. Use `run` instead."" runAbstractTrial(trial; force_recompile=false) + +# run a sim that will produce an error +dv = DiscreteVariation(rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""max_response""), 100.0) +out = run(inputs, dv) +@test out.n_success == 0 + +println(stdout, out) + +deleteSimulations(out.trial.id)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/ProjectConfigurationTests.jl",".jl","460","10","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +@test_throws ArgumentError PhysiCellModelManager.sanitizePathElement("".."") +@test_throws ArgumentError PhysiCellModelManager.sanitizePathElement(""~"") +@test_throws ArgumentError PhysiCellModelManager.sanitizePathElement(""/looks/like/absolute/path"") + +@test_throws ErrorException PhysiCellModelManager.folderIsVaried(:config, ""not-a-config-folder"")","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/PhysiCellStudioTests.jl",".jl","1430","32","using SQLite + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +sim_id = simulationIDs()[1] +fake_python_path = ""fake_python_path"" +fake_studio_path = ""fake_studio_path"" +@test_throws ArgumentError PhysiCellModelManager.resolveStudioGlobals(missing, missing) +@test_throws ArgumentError PhysiCellModelManager.resolveStudioGlobals(fake_python_path, missing) + +@test_throws Base.IOError runStudio(sim_id; python_path=fake_python_path, studio_path=fake_studio_path) + +@test PhysiCellModelManager.pcmm_globals.path_to_python == fake_python_path +@test PhysiCellModelManager.pcmm_globals.path_to_studio == fake_studio_path + +#! test that the studio launches even when the rules file cannot be found +simulation_output_folder = PhysiCellModelManager.pathToOutputFolder(sim_id) +path_to_parsed_rules = joinpath(simulation_output_folder, ""cell_rules_parsed.csv"") +@test isfile(path_to_parsed_rules) +path_to_dummy_parsed_rules = joinpath(simulation_output_folder, ""cell_rules_parsed__.csv"") +@test !isfile(path_to_dummy_parsed_rules) +mv(path_to_parsed_rules, path_to_dummy_parsed_rules) +@test !isfile(path_to_parsed_rules) +@test isfile(path_to_dummy_parsed_rules) +pcmm_output = run(Simulation(sim_id)) +@test_throws Base.IOError runStudio(pcmm_output; python_path=fake_python_path, studio_path=fake_studio_path) + +#! put the file back +mv(path_to_dummy_parsed_rules, path_to_parsed_rules)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/LoaderTests.jl",".jl","4850","96","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +config_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +custom_code_folder = ""0_template"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder) + +discrete_variations = [] +push!(discrete_variations, DiscreteVariation(configPath(""max_time""), 12.0)) +push!(discrete_variations, DiscreteVariation(configPath(""full_data""), 6.0)) +push!(discrete_variations, DiscreteVariation(configPath(""svg_save""), 6.0)) + +out = run(inputs, discrete_variations; use_previous=false) +@test out.trial isa Simulation +cell_labels = PhysiCellModelManager.cellLabels(out.trial) +substrate_names = PhysiCellModelManager.substrateNames(out.trial) +sequence = PhysiCellSequence(PhysiCellModelManager.trialID(out); include_cells=true, include_substrates=true) + +seq_dict = cellDataSequence(sequence, ""elapsed_time_in_phase""; include_dead=true) +@test length(seq_dict) == length(seq_dict.dict) +@test seq_dict[PhysiCellModelManager.AgentID(0)] == seq_dict[0] +@test haskey(seq_dict, PhysiCellModelManager.AgentID(0)) +@test haskey(seq_dict, 0) +@test_nowarn setindex!(seq_dict, seq_dict[0], PhysiCellModelManager.AgentID(78787878)) +@test_nowarn delete!(seq_dict, PhysiCellModelManager.AgentID(78787878)) +@test_nowarn setindex!(seq_dict, seq_dict[0], 78787878) +@test_nowarn delete!(seq_dict, 78787878) +@test_warn ""`getCellDataSequence` is deprecated. Use `cellDataSequence` instead."" getCellDataSequence(sequence, ""elapsed_time_in_phase""; include_dead=true) + +simulation_population_time_series = PhysiCellModelManager.populationTimeSeries(out; include_dead=true) +simulation_population_time_series[""time""] +cell_types = keys(simulation_population_time_series.cell_count) +simulation_population_time_series[first(cell_types)] +@test_throws ArgumentError simulation_population_time_series[""not_a_cell_type""] +simulation_population_time_series = PhysiCellModelManager.populationTimeSeries(out; include_dead=false) + +# brief pause for motility testing +for direction in [:x, :y, :z, :any] + local mean_speed_dicts = motilityStatistics(Simulation(PhysiCellModelManager.trialID(out)); direction=direction) +end +temp_mean_speed_dicts = motilityStatistics(out) +@test ismissing(motilityStatistics(pruned_simulation_id)) + +@test ismissing(PhysiCellSequence(pruned_simulation_id)) +pruned_simulation = Simulation(pruned_simulation_id) +@test PhysiCellModelManager.pathToOutputXML(pruned_simulation) |> PhysiCellModelManager.cellLabels |> isempty +@test PhysiCellModelManager.pathToOutputXML(pruned_simulation) |> PhysiCellModelManager.substrateNames |> isempty + +monad = createTrial(out.trial; n_replicates=0) +@test monad isa Monad + +monad = createTrial(monad; n_replicates=2) +out = run(monad) +monad = out.trial +monad_population_time_series = PhysiCellModelManager.populationTimeSeries(out; include_dead=false) +monad_population_time_series[""time""] +@test_throws ArgumentError monad_population_time_series[""not_a_cell_type""] + +# misc testing +snapshot = sequence.snapshots[1] +PhysiCellModelManager.cellLabels(snapshot) +PhysiCellModelManager.substrateNames(snapshot) +PhysiCellModelManager.loadSubstrates!(sequence) +PhysiCellModelManager.loadMesh!(sequence) +snapshot = PhysiCellSnapshot(1, 0) +sequence = PhysiCellSequence(Simulation(1)) +cellDataSequence(1, ""position"") +cellDataSequence(Simulation(1), ""position"") + +simulation = Simulation(monad) +out = run(simulation; prune_options=PruneOptions(prune_mat=true)) +@test out.n_success == 1 #! confirm that creating a simulation using simulation = Simulation(monad) creates a new simulation (not one already in the db) +mat_pruned_simulation_id = PhysiCellModelManager.trialID(out) +PhysiCellSnapshot(mat_pruned_simulation_id, 0; include_cells=true) +PhysiCellSnapshot(mat_pruned_simulation_id, 0; include_substrates=true) +snapshot = PhysiCellSnapshot(mat_pruned_simulation_id, 0) +@test ismissing(PhysiCellModelManager.averageExtracellularSubstrate(snapshot)) + +sequence = PhysiCellSequence(mat_pruned_simulation_id; include_attachments=true, include_spring_attachments=true, include_neighbors=true) +PhysiCellModelManager.loadGraph!(sequence, :attachments) +PhysiCellModelManager.loadGraph!(sequence, ""spring_attachments"") +PhysiCellModelManager.loadGraph!(sequence, :neighbors) + +println(stdout, snapshot) +println(stdout, sequence) +println(stdout, sequence.snapshots[1]) + +simulation = Simulation(monad) +out = run(simulation; prune_options=PruneOptions(prune_txt=true)) +txt_pruned_simulation_id = PhysiCellModelManager.trialID(out) +@test ismissing(PhysiCellSnapshot(txt_pruned_simulation_id, 0; include_attachments=true)) +@test ismissing(PhysiCellSnapshot(txt_pruned_simulation_id, 0; include_spring_attachments=true)) +@test ismissing(PhysiCellSnapshot(txt_pruned_simulation_id, 0; include_neighbors=true))","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/ClassesTests.jl",".jl","3434","91","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +config_folder = ""0_template"" +custom_code_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +ic_cell_folder = ""0_template"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder, ic_cell=ic_cell_folder) + +simulation = Simulation(inputs) +@test simulation isa Simulation + +simulation = Simulation(1) +@test simulation isa Simulation + +monad = Monad(1) +@test monad isa Monad + +n_replicates = 1 +config_variation_ids = [1, 2] +rulesets_collection_variation_ids = [1, 1] +ic_cell_variation_ids = [0, 0] +location_variation_ids = Dict{Symbol,Union{Integer,AbstractArray{<:Integer}}}( + :config => config_variation_ids, + :rulesets_collection => rulesets_collection_variation_ids, + :ic_cell => ic_cell_variation_ids +) +sampling = Sampling(inputs, location_variation_ids; + n_replicates=n_replicates, +) +@test sampling isa Sampling +possibly_empty_monad_ids = monadIDs(sampling) + +trial = Trial(1) +@test trial isa Trial + +samplings = [Sampling(1), Sampling(2)] +@test all(typeof.(samplings) .== Sampling) + +trial = Trial(samplings) +@test trial isa Trial + +@test_throws ErrorException Simulation(999) +@test_throws ErrorException Monad(999) +@test_throws ErrorException Sampling(999) + +# misc tests +inputs = InputFolders(; config=""0_template"", custom_code=""0_template"") +simulation = Simulation(Monad(1)) + +@test_throws ArgumentError PhysiCellModelManager.constituentType(Simulation) + +monadIDs(samplings) +@test PhysiCellModelManager.lowerClassString(simulation) == ""simulation"" +@test PhysiCellModelManager.lowerClassString(Monad(1)) == ""monad"" +@test PhysiCellModelManager.lowerClassString(samplings[1]) == ""sampling"" +@test PhysiCellModelManager.lowerClassString(trial) == ""trial"" + +old_march_flag = PhysiCellModelManager.pcmm_globals.march_flag +new_march_flag = ""new_march_flag"" +PhysiCellModelManager.setMarchFlag(new_march_flag) +@test PhysiCellModelManager.pcmm_globals.march_flag == new_march_flag +PhysiCellModelManager.setMarchFlag(old_march_flag) +@test PhysiCellModelManager.pcmm_globals.march_flag == old_march_flag #! make sure it is reset + +#! you probably do not want to use integer variation IDs to initialize a Sampling object. this is just to test edge cases in the constructor +location_variation_ids = Dict{Symbol,Union{Integer,AbstractArray{<:Integer}}}(:config => 0, :rulesets_collection => -1, :ic_cell => -1) +sampling = Sampling(inputs, location_variation_ids) +append!(possibly_empty_monad_ids, monadIDs(sampling)) +location_variation_ids = Dict{Symbol,Union{Integer,AbstractArray{<:Integer}}}(:config => [0], :rulesets_collection => -1, :ic_cell => -1) +sampling = Sampling(inputs, location_variation_ids) +append!(possibly_empty_monad_ids, monadIDs(sampling)) +sampling = Sampling(Monad(1)) +all_monads = simulationIDs() .|> Simulation .|> Monad +all_monad_ids = [monad.id for monad in all_monads] |> unique +trial = Trial(Monad.(all_monad_ids)) + +#! show the stuff +println(stdout, simulation.inputs[:config]) +println(stdout, simulation.inputs) +println(stdout, simulation.variation_id) +println(stdout, simulation) +println(stdout, monad) +println(stdout, sampling) +println(stdout, trial) + +deleteSimulationsByStatus(""Not Started""; user_check=false) +monad_ids_to_delete = setdiff(possibly_empty_monad_ids, all_monad_ids) +PhysiCellModelManager.deleteMonad(monad_ids_to_delete)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/SubstrateTests.jl",".jl","1065","31","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +simulation_id = 1 +simulation = Simulation(simulation_id) +out = run(simulation) +asts = PhysiCellModelManager.AverageSubstrateTimeSeries(simulation_id) +asts = PhysiCellModelManager.AverageSubstrateTimeSeries(out) +ests = PhysiCellModelManager.ExtracellularSubstrateTimeSeries(simulation_id) +ests = PhysiCellModelManager.ExtracellularSubstrateTimeSeries(out) + +@test ismissing(PhysiCellModelManager.AverageSubstrateTimeSeries(pruned_simulation_id)) +snapshot = PhysiCellSnapshot(pruned_simulation_id, :initial) +@test ismissing(snapshot) +@test ismissing(PhysiCellModelManager.ExtracellularSubstrateTimeSeries(pruned_simulation_id)) + +#! misc tests +asts[""time""] +substrate_names = keys(asts.substrate_concentrations) +asts[first(substrate_names)] +@test_throws ArgumentError asts[""not_a_substrate""] + +ests[""time""] +cell_types = keys(ests.data) +ests[first(cell_types)] +@test_throws ArgumentError ests[""not_a_cell_type""] + +println(stdout, asts) +println(stdout, ests)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/DeletionTests.jl",".jl","1674","57","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +# diagnostics +@test_nowarn PhysiCellModelManager.databaseDiagnostics() + +# make a few more sims to test deletion +out = run(Monad(1; n_replicates=3)) +@test out.trial isa Monad + +simulation_id = simulationIDs(out.trial)[1] + +deleteSimulation(simulation_id:simulation_id) +@test !isdir(joinpath(PhysiCellModelManager.dataDir(), ""outputs"", ""simulations"", string(simulation_id))) + +PhysiCellModelManager.eraseSimulationIDFromConstituents(simulationIDs(out.trial)[2]) + +PhysiCellModelManager.deleteMonad(1:4) +PhysiCellModelManager.deleteSampling(1) +PhysiCellModelManager.deleteTrial(1) + +deleteSimulations(1:78; filters=Dict(""config_id"" => 2)) +@test_throws AssertionError deleteSimulations(1:78; filters=Dict(""bad filter; --"" => 2)) + +input_buffer = IOBuffer(""n"") +old_stdin = stdin #! Save the original stdin +Base.stdin = input_buffer +deleteSimulationsByStatus([""Queued"", ""Failed""]) +Base.stdin = old_stdin + +deleteSimulationsByStatus(; user_check=false) + +PhysiCellModelManager.deleteAllSimulations() +resetDatabase(; force_reset=true) + +input_buffer = IOBuffer(""y"") +old_stdin = stdin #! Save the original stdin +Base.stdin = input_buffer +resetDatabase() +Base.stdin = old_stdin + +input_buffer = IOBuffer(""n\nn\n"") +old_stdin = stdin #! Save the original stdin +Base.stdin = input_buffer +@test_throws ErrorException resetDatabase() +Base.stdin = old_stdin + +input_buffer = IOBuffer(""n\ny\n"") +old_stdin = stdin #! Save the original stdin +Base.stdin = input_buffer +resetDatabase() +Base.stdin = old_stdin + +# diagnostics again +@test_nowarn PhysiCellModelManager.databaseDiagnostics()","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/DepsTests.jl",".jl","2683","63","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +include(joinpath(@__DIR__, "".."", "".."", ""deps"", ""DeprecateKeywords.jl"")) +import .DeprecateKeywords: @depkws + +@testset ""DeprecateKeywords"" begin + # force the deprecation warning to be emitted + @depkws force = true function f(; a=2, @deprecate b a) + a + end + + @test f(a=1) === 1 + @test_warn ""Keyword argument `b` is deprecated. Use `a` instead."" (@test f(b=1) == 1) + @test_warn ""Keyword argument `b` is deprecated. Use `a` instead."" (@test f(b=nothing) === nothing) + + # do not force the deprecation warning to be emitted (default behavior) + @depkws force = false function g(; α=2, γ=4, @deprecate(β, α), @deprecate(δ, γ)) + α + γ + end + + @test g() === 6 + @test g(α=1, γ=3) === 4 + + @test_warn ""Keyword argument `β` is deprecated. Use `α` instead."" (@test g(β=1, γ=3) === 4) + @test_warn ""Keyword argument `δ` is deprecated. Use `γ` instead."" (@test g(α=1, δ=3) === 4) + @test_warn ""Keyword argument `β` is deprecated. Use `α` instead."" (@test g(β=1, δ=3) === 4) + + # default behavior is to not emit deprecation warnings, so it will not be emitted + @depkws h(; (@deprecate old_kw new_kw), new_kw::Int=3) = new_kw + @test h() === 3 + @test h(new_kw=1) === 1 + @test_warn ""Keyword argument `old_kw` is deprecated. Use `new_kw` instead."" (@test h(old_kw=1) === 1) + + # Incorrect scope: + @test_throws LoadError (@eval @depkws k(; @deprecate a b, b = 10) = b) + + # Use type assertion with no default set: + @depkws y(; a::Int, (@deprecate b a)) = a + + @test y(a=1) == 1 + @test_warn ""Keyword argument `b` is deprecated. Use `a` instead."" (@test y(b=1) == 1) + # Type assertion should still work: + @test_throws TypeError y(a=1.0) + + # We shouldn't interfere with regular kwargs: + @depkws y2(; a::Int) = a + @test y2(a=1) == 1 + + @depkws m(x; (@deprecate a b), b) = x + b + @test_throws UndefKeywordError m(1.0) + @test_warn ""Keyword argument `a` is deprecated. Use `b` instead."" (@test m(1.0; a=2.0) == 3.0) + @test m(1.0; b=2.0) == 3.0 + + @depkws force(; a=""cat"", @deprecate(b, a)) = a + @test_warn ""Keyword argument `b` is deprecated. Use `a` instead."" (@test force(b=""dog"") == ""dog"") + @test macroexpand(DeprecateKeywords, :(@depkws force(; a=""cat"", @deprecate(b, a)) = a)) |> string |> contains(""force = false"") + @test macroexpand(DeprecateKeywords, :(@depkws force = true force(; a=""cat"", @deprecate(b, a)) = a)) |> string |> contains(""force = true"") + + @test_throws LoadError (@eval @depkws fake_head - true n(; @deprecate a b, b = 10) = b) +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/PCFTests.jl",".jl","1972","51","using Plots, PairCorrelationFunction + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +simulation_id = 1 +simulation = Simulation(simulation_id) +out = run(simulation) +snapshot = PhysiCellSnapshot(simulation_id, :initial) +cell_types = PhysiCellModelManager.cellTypeToNameDict(simulation) |> values |> collect +result = pcf(simulation, cell_types[1]) + +plot(result) +plot(result; time_unit=:s, distance_unit=:mm) +plot(result; time_unit=:s, distance_unit=:cm) + +println(stdout, result) + +result = PhysiCellModelManager.pcf(PhysiCellSnapshot(simulation_id, :initial), cell_types[1]) +result = PhysiCellModelManager.pcf(simulation_id, :initial, cell_types[1]) +result = PhysiCellModelManager.pcf(out, :initial, [cell_types[1]], cell_types[1]) + +plot(result; time_unit=:s) +plot([result]; time_unit=:h) +plot([result]; time_unit=:d) +plot([result]; time_unit=:w) +plot([result]; time_unit=:mo) +plot([result]; time_unit=:y) + +println(stdout, result) + +@test_throws ArgumentError PhysiCellModelManager.pcf(simulation, :initial, :default) #! third argument should be a string or vector of strings +@test_throws ArgumentError plot([result]; time_unit=:not_a_unit) +@test_throws ArgumentError plot([result]; distance_unit=:not_a_unit) + +#! test 3d +dvs = DiscreteVariation[] +domain = (z_min=-20.0, z_max=20.0) +addDomainVariationDimension!(dvs, domain) +push!(dvs, DiscreteVariation([""domain"", ""use_2D""], false)) +out = run(simulation, dvs) +simulation_id = out.trial |> simulationIDs |> first +result = PhysiCellModelManager.pcf(simulation_id, :final, cell_types[1]) + +simulation_id = simulation_from_import |> simulationIDs |> first +snapshot = PhysiCellSnapshot(simulation_id, :final) +cell_types = PhysiCellModelManager.cellTypeToNameDict(snapshot) |> values |> collect +result = PhysiCellModelManager.pcf(snapshot, cell_types[1], cell_types[2]) +@test_throws ArgumentError PhysiCellModelManager.pcf(snapshot, cell_types[1], cell_types[1:2])","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/DatabaseTests.jl",".jl","3928","92","using SQLite + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +simulationsTable() +simulation_ids = 1:5 +printSimulationsTable(simulation_ids) + +# test required folders +config_src_folder = joinpath(PhysiCellModelManager.dataDir(), ""inputs"", ""configs"") +config_dest_folder = joinpath(PhysiCellModelManager.dataDir(), ""inputs"", ""configs_"") +mv(config_src_folder, config_dest_folder) + +custom_code_src_folder = joinpath(PhysiCellModelManager.dataDir(), ""inputs"", ""custom_codes"") +custom_code_dest_folder = joinpath(PhysiCellModelManager.dataDir(), ""inputs"", ""custom_codes_"") +mv(custom_code_src_folder, custom_code_dest_folder) + +@test_throws AssertionError PhysiCellModelManager.createSchema() +@test initializeModelManager() == false + +mv(config_dest_folder, config_src_folder) +mv(custom_code_dest_folder, custom_code_src_folder) + +@test initializeModelManager() == true + +# test bad table +table_name_not_end_in_s = ""test"" +@test_throws ErrorException PhysiCellModelManager.createPCMMTable(table_name_not_end_in_s, """") +schema_without_primary_id = """" +@test_throws ErrorException PhysiCellModelManager.createPCMMTable(""simulations"", schema_without_primary_id) + +@test_throws ArgumentError PhysiCellModelManager.icFilename(""ecm"") + +# misc tests +config_db = PhysiCellModelManager.locationVariationsDatabase(:config, Simulation(1)) +@test config_db isa SQLite.DB + +ic_cell_db = PhysiCellModelManager.locationVariationsDatabase(:ic_cell, Simulation(1)) +@test ic_cell_db isa Missing + +ic_ecm_db = PhysiCellModelManager.locationVariationsDatabase(:ic_ecm, Simulation(1)) +@test ic_ecm_db isa Nothing + +PhysiCellModelManager.variationIDs(:config, Simulation(1)) +PhysiCellModelManager.variationIDs(:config, Sampling(1)) +PhysiCellModelManager.variationIDs(:rulesets_collection, Simulation(1)) +PhysiCellModelManager.variationIDs(:rulesets_collection, Sampling(1)) +PhysiCellModelManager.variationIDs(:ic_cell, Simulation(1)) +PhysiCellModelManager.variationIDs(:ic_cell, Sampling(1)) +PhysiCellModelManager.variationIDs(:ic_ecm, Simulation(1)) +PhysiCellModelManager.variationIDs(:ic_ecm, Sampling(1)) + +PhysiCellModelManager.locationVariationsTable(:config, Sampling(1); remove_constants=true) +PhysiCellModelManager.locationVariationsTable(:rulesets_collection, Sampling(1); remove_constants=true) +PhysiCellModelManager.locationVariationsTable(:ic_cell, Sampling(1); remove_constants=true) +PhysiCellModelManager.locationVariationsTable(:ic_ecm, Sampling(1); remove_constants=true) + +# test bad folder +path_to_bad_folder = joinpath(PhysiCellModelManager.dataDir(), ""inputs"", ""configs"", ""bad_folder"") +mkdir(path_to_bad_folder) + +@test PhysiCellModelManager.reinitializeDatabase() == false + +rm(path_to_bad_folder; force=true, recursive=true) +@test PhysiCellModelManager.initializeDatabase() == true +PhysiCellModelManager.assertInitialized() + +# test stmtToDataFrame error +stmt_str = ""SELECT * FROM simulations WHERE simulation_id = :simulation_id;"" +bad_params = (; :simulation_id => -1) +@test_throws AssertionError PhysiCellModelManager.stmtToDataFrame(stmt_str, bad_params; is_row=true) + +# test getParameterValue +simulation = Simulation(1) +xml_path = [""overall"", ""max_time""] +@test getParameterValue(simulation, xml_path) == 60.0 # max time in the GenerateData.jl test script is set to 60.0 +@test getParameterValue(1, xml_path) == 60.0 # use the simulation_id version + +monad = Monad(simulation) +@test getParameterValue(monad, xml_path) == 60.0 # use the monad version +@test getParameterValue(monad, [""domain"", ""use_2D""]) == true +@test getParameterValue(monad, [""initial_conditions"", ""cell_positions"", ""folder""]) == ""./config"" + +xml_path = icCellsPath(""default"", ""disc"", 1, ""x0"") +@test_throws AssertionError getParameterValue(simulation, xml_path) # not varied in simulation 1 + +@test_nowarn getAllParameterValues(1) +@test_nowarn getAllParameterValues(monad) +@test_nowarn getAllParameterValues(Sampling(1))","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/PopulationTests.jl",".jl","2716","62","using Plots + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +simulation = Simulation(1) +out = run(simulation) +finalPopulationCount(out) + +plot(Simulation(1)) +plot(Sampling(1)) + +plotbycelltype(Simulation(1)) +plotbycelltype(Sampling(1)) +plotbycelltype(Sampling(1); include_cell_type_names=""default"") + +# misc tests +out = Monad(1; n_replicates=3) |> run +mpts = PhysiCellModelManager.MonadPopulationTimeSeries(1) +plot(out) +plot(out.trial) +plot(out; include_cell_type_names=""default"") +plotbycelltype(out) +plotbycelltype(out.trial) + +all_cell_types = [""cancer"", ""immune"", ""epi"", ""mes""] +PhysiCellModelManager.processIncludeCellTypes([""cancer"", ""immune""], all_cell_types) +PhysiCellModelManager.processIncludeCellTypes([""epi"", ""mes"", [""epi"", ""mes""]], all_cell_types) +@test_throws ArgumentError PhysiCellModelManager.processIncludeCellTypes(:mes, all_cell_types) +@test_throws ArgumentError PhysiCellModelManager.processIncludeCellTypes(1, all_cell_types) + +PhysiCellModelManager.processExcludeCellTypes(""cancer"") +@test_throws ArgumentError PhysiCellModelManager.processExcludeCellTypes(:mes) +plot(out; include_cell_type_names=""default"", exclude_cell_type_names=""default"") + +plot(simulation_from_import; include_cell_type_names=[[""fast T cell"", ""slow T cell"", ""effector T cell"", ""exhausted T cell""]]) +monad = Monad(simulation_from_import; n_replicates=2) +out = run(monad) +plot(out; include_cell_type_names=[[""fast T cell"", ""slow T cell"", ""effector T cell"", ""exhausted T cell""]]) + +@test_throws ArgumentError plot(run(Trial(1))) + +plotbycelltype(simulation_from_import; include_cell_type_names=""fast T cell"", exclude_cell_type_names=""fast T cell"") + +@test ismissing(PhysiCellSnapshot(pruned_simulation_id, :initial)) +@test ismissing(finalPopulationCount(pruned_simulation_id)) + +spts = PhysiCellModelManager.SimulationPopulationTimeSeries(1) +println(stdout, spts) +println(stdout, mpts) + +@test PhysiCellModelManager.formatTimeRange([78.0]) == ""78.0"" +@test PhysiCellModelManager.formatTimeRange([0.0, 40.0, 78.0]) == ""0.0-78.0 (not equally spaced)"" + +#! deprecation tests +@test_warn ""`include_cell_types` is deprecated as a keyword. Use `include_cell_type_names` instead."" plot(out; include_cell_types=""fast T cell"") +@test_warn ""`exclude_cell_types` is deprecated as a keyword. Use `exclude_cell_type_names` instead."" plot(out; exclude_cell_types=""fast T cell"") + +@test_warn ""`include_cell_types` is deprecated as a keyword. Use `include_cell_type_names` instead."" plotbycelltype(out; include_cell_types=""fast T cell"") +@test_warn ""`exclude_cell_types` is deprecated as a keyword. Use `exclude_cell_type_names` instead."" plotbycelltype(out; exclude_cell_types=""fast T cell"")","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/PrintHelpers.jl",".jl","1125","32","function printBetweenHashes(s::String) + if length(s) < 30 + s = lpad(s, length(s) + Int(ceil((40 - length(s))/2))) + s = rpad(s, 40) + return [s] + else + s_split = split(s) + s_length = length(s) + s_lengths = [length(x) for x in s_split] + sub_lengths = cumsum(s_lengths .+ (0:(length(s_split)-1))) #! length of string after combining through the ith token, joining with spaces + I = findlast(2 .* sub_lengths .< s_length) + if isnothing(I) + #! then the first token is too long + s_split = [s_split[1][1:15]; s_split[1][16:end]; s_split[2:end]] #! force the split 15 chars into the first token + I = 1 + end + + S1 = join(s_split[1:I], "" "") |> printBetweenHashes + S2 = join(s_split[I+1:end], "" "") |> printBetweenHashes + return [S1; S2] + end +end + +function hashBorderPrint(s::String) + S = printBetweenHashes(s) + str = ""############################################\n"" + for s in S + str *= ""##"" * s * ""##\n"" + end + str *= ""############################################"" + println(str) +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/ExportTests.jl",".jl","2808","77","using LightXML + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +export_test(folder) = begin + @test isdir(folder) + @test isfile(joinpath(folder, ""config"", ""PhysiCell_settings.xml"")) + @test isfile(joinpath(folder, ""main.cpp"")) + @test isfile(joinpath(folder, ""Makefile"")) + @test isfile(joinpath(folder, ""custom_modules"", ""custom.cpp"")) + + @test begin + lines = readlines(joinpath(folder, ""main.cpp"")) + return !any(contains.(lines, ""argument_parser"")) + end + + @test begin + lines = readlines(joinpath(folder, ""custom_modules"", ""custom.cpp"")) + return !any(contains.(lines, ""load_initial_cells"")) + end +end + +export_folder = exportSimulation(1) +export_test(export_folder) + +ic_cell_xml_folder = exportSimulation(simulation_with_ic_cell_xml_id) +export_test(ic_cell_xml_folder) + +# make sim with ic substrate +config = ""0_template"" +custom_code = ""0_template"" +ic_substrate = ""0_template"" +inputs = InputFolders(config, custom_code; ic_substrate=ic_substrate) +dv = DiscreteVariation([""overall"", ""max_time""], 12) +out = run(inputs, dv) +@test out.trial isa Simulation +export_folder = exportSimulation(PhysiCellModelManager.trialID(out)) +export_test(export_folder) + +# make sim with ic ecm +config = ""template-ecm"" +custom_code = ""template-ecm"" +ic_ecm = ""template-ecm"" +inputs = InputFolders(config, custom_code; ic_ecm=ic_ecm) +dv = DiscreteVariation([""overall"", ""max_time""], 12) +out = run(inputs, dv) +@test out.trial isa Simulation +export_folder = exportSimulation(PhysiCellModelManager.trialID(out)) +export_test(export_folder) + +# make sim with id dc +config = ""dirichlet_from_file"" +custom_code = ""dirichlet_from_file"" +ic_dc = ""dirichlet_from_file"" +inputs = InputFolders(config, custom_code; ic_dc=ic_dc) +dv = DiscreteVariation([""overall"", ""max_time""], 12) +out = run(inputs, dv) +@test out.trial isa Simulation +export_folder = exportSimulation(PhysiCellModelManager.trialID(out)) +export_test(export_folder) + +# export with intracellulars +simulation_id = pcmm_output_intracellular |> simulationIDs |> first +path_to_exported_folder = exportSimulation(simulation_id, ""IntracellularTestExport"") +path_to_xml = joinpath(path_to_exported_folder, ""config"", ""PhysiCell_settings.xml"") +@test isfile(path_to_xml) +xml_doc = parse_file(path_to_xml) +path_to_intracellular = [""cell_definitions"", ""cell_definition:name:default"", ""phenotype"", ""intracellular""] +intracellular_element = PhysiCellModelManager.retrieveElement(xml_doc, path_to_intracellular) +@test attribute(intracellular_element, ""type"") == ""roadrunner"" +sbml_filename_element = find_element(intracellular_element, ""sbml_filename"") +@test !isnothing(sbml_filename_element) +filename = content(sbml_filename_element) +@test isfile(joinpath(path_to_exported_folder, filename))","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/CreateProjectTests.jl",".jl","1359","39","using Downloads, LightXML + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +project_dir = ""pcmm_project_sans_template"" +createProject(project_dir; template_as_default=false) +@test PhysiCellModelManager.isInitialized() +@test PhysiCellModelManager.dataDir() == normpath(abspath(joinpath(project_dir, ""data""))) +@test PhysiCellModelManager.physicellDir() == normpath(abspath(joinpath(project_dir, ""PhysiCell""))) + +project_dir = ""."" +createProject(project_dir) +@test PhysiCellModelManager.isInitialized() +@test PhysiCellModelManager.dataDir() == normpath(abspath(joinpath(project_dir, ""data""))) +@test PhysiCellModelManager.physicellDir() == normpath(abspath(joinpath(project_dir, ""PhysiCell""))) + +# tests for coverage +@test PhysiCellModelManager.icFilename(""ecms"") == ""ecm.csv"" +@test PhysiCellModelManager.icFilename(""dcs"") == ""dcs.csv"" + +# test request without authentication token +PCMM_PUBLIC_REPO_AUTH = get(ENV, ""PCMM_PUBLIC_REPO_AUTH"", """") +delete!(ENV, ""PCMM_PUBLIC_REPO_AUTH"") + +try + PhysiCellModelManager.latestReleaseTag(""https://github.com/drbergman/PhysiCell"") +catch e + @test e isa RequestError +else + @test true +end + +ENV[""PCMM_PUBLIC_REPO_AUTH""] = PCMM_PUBLIC_REPO_AUTH + +# run the generated script +include(""../scripts/GenerateData.jl"") #! this file is created by CreateProjectTests.jl","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/RuntimeTests.jl",".jl","706","28","using Dates + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +simulation = Simulation(1) +out = run(simulation) + +#! runtime +runtime1 = simulationRuntime(simulation) +runtime2 = simulationRuntime(1) +runtime3 = simulationRuntime(out) + +@test typeof(runtime1) == Nanosecond +@test runtime1 == runtime2 +@test runtime1 == runtime3 + +#! runtime intervals +intervals1 = simulationRuntimeIntervals(simulation) +intervals2 = simulationRuntimeIntervals(1) +intervals3 = simulationRuntimeIntervals(out) + +@test length(intervals1.time) == length(intervals1.runtime) +@test intervals1.runtime == intervals2.runtime +@test intervals1.runtime == intervals3.runtime +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/ICECMTests.jl",".jl","1334","37","using LightXML, PhysiCellECMCreator + +filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +ic_ecm_folder = ""1_xml"" +ic_ecm_folder = PhysiCellModelManager.createICECMXMLTemplate(ic_ecm_folder) +@test_nowarn PhysiCellModelManager.createICECMXMLTemplate(ic_ecm_folder) + +config_folder = ""template-ecm"" +custom_code_folder = ""template-ecm"" +rulesets_collection_folder = ""0_template"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder, ic_ecm=ic_ecm_folder) + +n_replicates = 1 + +dv1 = DiscreteVariation([""overall"", ""max_time""], 12.0) +dv2 = DiscreteVariation(icECMPath(2, ""ellipse"", 1, ""density""), [0.25, 0.75]) +dv3 = DiscreteVariation(icECMPath(2, ""ellipse_with_shell"", 1, ""interior"", ""density""), 0.2) +out = run(inputs, [dv1, dv2, dv3]; n_replicates=n_replicates) + +macros_lines = PhysiCellModelManager.readMacrosFile(out.trial) +@test ""ADDON_PHYSIECM"" in macros_lines + +# test failing ecm sim +xml_path1 = icECMPath(2, ""ellipse"", 1, ""a"") +xml_path2 = icECMPath(2, ""elliptical_disc"", 1, ""a"") +dv1 = DiscreteVariation(xml_path1, 50.0) +dv2 = DiscreteVariation(xml_path2, 80.0) +cv = CoVariation(dv1, dv2) + +out_fail = run(out.trial.monads[1], cv; n_replicates=n_replicates) +@test out_fail.n_success == 0 + +deleteSimulations(out_fail.trial.id)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/ModuleTests.jl",".jl","835","26","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +PhysiCellModelManager.constituentIDs(Trial, 1) +sim_ids = simulationIDs()[1:2] +simulationIDs(Simulation.(sim_ids)) +PhysiCellModelManager.trialMonads(1) +monadIDs() +monadIDs(Trial(1)) + +@test_warn ""`getSimulationIDs` is deprecated. Use `simulationIDs` instead."" getSimulationIDs(Trial(1)) +@test_warn ""`getMonadIDs` is deprecated. Use `monadIDs` instead."" getMonadIDs(Trial(1)) + +path_to_inputs = joinpath(PhysiCellModelManager.dataDir(), ""inputs"", ""inputs.toml"") +path_to_fake_inputs = joinpath(PhysiCellModelManager.dataDir(), ""inputs"", ""not_inputs.toml"") + +mv(path_to_inputs, path_to_fake_inputs) + +@test initializeModelManager() == false + +mv(path_to_fake_inputs, path_to_inputs) + +@test initializeModelManager() == true +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/PhysiCellVersionTests.jl",".jl","1833","51","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +@test PhysiCellModelManager.physicellVersion() == readchomp(joinpath(PhysiCellModelManager.physicellDir(), ""VERSION.txt"")) + +sim_id = simulationIDs()[1] +@test PhysiCellModelManager.physicellVersion(Simulation(sim_id)) == readchomp(joinpath(PhysiCellModelManager.physicellDir(), ""VERSION.txt"")) + +path_to_file = joinpath(""PhysiCell"", ""Makefile"") + +lines = readlines(path_to_file) +lines[1] *= "" "" +open(path_to_file, ""w"") do f + for line in lines + println(f, line) + end +end + +println(""Testing that PCMM recognizes PhysiCell is dirty..."") +@test !PhysiCellModelManager.gitDirectoryIsClean(PhysiCellModelManager.physicellDir()) +println(""PhysiCell should still be dirty on initialization..."") +@test initializeModelManager(PhysiCellModelManager.physicellDir(), PhysiCellModelManager.dataDir()) +PhysiCellModelManager.physicellVersion() + +lines[1] = lines[1][1:end-1] +open(path_to_file, ""w"") do f + for line in lines + println(f, line) + end +end + +@test PhysiCellModelManager.gitDirectoryIsClean(PhysiCellModelManager.physicellDir()) + +# test with PhysiCell download +original_project_dir = dirname(PhysiCellModelManager.dataDir()) + +project_dir = ""./test-project-download"" +createProject(project_dir; clone_physicell=false) +data_dir = joinpath(project_dir, ""data"") +physicell_dir = joinpath(project_dir, ""PhysiCell"") +@test PhysiCellModelManager.isInitialized() +@test PhysiCellModelManager.dataDir() == normpath(abspath(data_dir)) +@test PhysiCellModelManager.physicellDir() == normpath(abspath(physicell_dir)) +@test initializeModelManager(physicell_dir, data_dir) +PhysiCellModelManager.resolvePhysiCellVersionID() + +@test initializeModelManager(original_project_dir) +PhysiCellModelManager.resolvePhysiCellVersionID() +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/SensitivityTests.jl",".jl","6602","135","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +setNumberOfParallelSims(12) + +config_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +custom_code_folder = ""0_template"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder) + +cell_type = ""default"" +force_recompile = false + +dv_max_time = DiscreteVariation([""overall"", ""max_time""], 12.0) +dv_save_full_data_interval = DiscreteVariation(configPath(""full_data""), 6.0) +dv_save_svg_data_interval = DiscreteVariation(configPath(""svg_save""), 6.0) +discrete_variations = [dv_max_time, dv_save_full_data_interval, dv_save_svg_data_interval] + +add_variations_result = PhysiCellModelManager.addVariations(GridVariation(), inputs, discrete_variations) +reference_variation_id = add_variations_result.all_variation_ids[1] + +xml_path = PhysiCellModelManager.cyclePath(cell_type, ""phase_durations"", ""duration:index:0"") +lower_bound = 250.0 - 50.0 +upper_bound = 350.0 + 50.0 +dv1 = UniformDistributedVariation(xml_path, lower_bound, upper_bound) + +xml_path = PhysiCellModelManager.cyclePath(cell_type, ""phase_durations"", ""duration:index:1"") +vals = [100.0, 200.0, 300.0] +dv2 = DiscreteVariation(xml_path, vals) + +xml_path = PhysiCellModelManager.cyclePath(cell_type, ""phase_durations"", ""duration:index:2"") +mu = 300.0 +sigma = 50.0 +lb = 10.0 +ub = 1000.0 +dv3 = NormalDistributedVariation(xml_path, mu, sigma; lb=lb, ub=ub) + +avs = [CoVariation(dv1, dv3), dv2] + +n_points = 2^1-1 + +gs_fn(simulation_id::Int) = finalPopulationCount(simulation_id)[cell_type] + +moat_sampling = run(MOAT(n_points), inputs, avs; force_recompile=force_recompile, reference_variation_id=reference_variation_id, functions=[gs_fn], n_replicates=1) +moat_sampling = run(MOAT(), inputs, avs; force_recompile=force_recompile, reference_variation_id=reference_variation_id, functions=[gs_fn]) +moat_sampling = run(MOAT(4; orthogonalize=true), inputs, avs; force_recompile=force_recompile, reference_variation_id=reference_variation_id, functions=[gs_fn]) +sobol_sampling = run(Sobolʼ(n_points), inputs, avs; force_recompile=force_recompile, reference_variation_id=reference_variation_id, functions=[gs_fn]) +rbd_sampling = run(RBD(n_points), inputs, avs; force_recompile=force_recompile, reference_variation_id=reference_variation_id, functions=[gs_fn]) + +PhysiCellModelManager.calculateGSA!(moat_sampling, gs_fn) +PhysiCellModelManager.calculateGSA!(sobol_sampling, gs_fn) +PhysiCellModelManager.calculateGSA!(rbd_sampling, gs_fn) + +# test sensitivity with config, rules, ic_cells, and ic_ecm at once +config_folder = ""template-ecm"" +rulesets_collection_folder = ""0_template"" +custom_code_folder = ""template-ecm"" +ic_cell_folder = ""1_xml"" +ic_ecm_folder = ""1_xml"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder, ic_cell=ic_cell_folder, ic_ecm=ic_ecm_folder) + +dv_max_time = DiscreteVariation([""overall"", ""max_time""], 12.0) +dv_save_full_data_interval = DiscreteVariation(configPath(""full_data""), 6.0) +dv_save_svg_data_interval = DiscreteVariation(configPath(""svg_save""), 6.0) +discrete_variations = [dv_max_time, dv_save_full_data_interval, dv_save_svg_data_interval] + +add_variations_result = PhysiCellModelManager.addVariations(GridVariation(), inputs, discrete_variations) +reference_variation_id = add_variations_result.all_variation_ids[1] + +xml_path = PhysiCellModelManager.cyclePath(cell_type, ""phase_durations"", ""duration:index:0"") +lower_bound = 250.0 - 50.0 +upper_bound = 350.0 + 50.0 +dv1 = UniformDistributedVariation(xml_path, lower_bound, upper_bound) + +xml_path = rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""max_response"") +dv2 = UniformDistributedVariation(xml_path, 0.0, 1.0e-8) + +xml_path = icCellsPath(""default"", ""annulus"", 1, ""inner_radius"") +dv3 = UniformDistributedVariation(xml_path, 0.0, 1.0) + +xml_path = icECMPath(2, ""ellipse"", 1, ""density"") +dv4 = UniformDistributedVariation(xml_path, 0.25, 0.75) + +av = CoVariation(dv1, dv2, dv3, dv4) + +moat_sampling = run(MOAT(n_points), inputs, av; force_recompile=force_recompile, reference_variation_id=reference_variation_id, functions=[gs_fn]) +n_simulations_expected = n_points * (1 + 1) * n_replicates +@test length(moat_sampling.sampling) == n_simulations_expected + +sobol_index_methods = (first_order=:Sobol1993, total_order=:Homma1996) +sobol_sampling = run(SobolPCMM(n_points; sobol_index_methods=sobol_index_methods), inputs, av; force_recompile=force_recompile, reference_variation_id=reference_variation_id, functions=[gs_fn]) +sobol_index_methods = (first_order=:Saltelli2010, total_order=:Sobol2007) +sobol_sampling = run(SobolPCMM(n_points; sobol_index_methods=sobol_index_methods), inputs, av; force_recompile=force_recompile, reference_variation_id=reference_variation_id, functions=[gs_fn]) + +reference = simulationIDs(sobol_sampling)[1] |> Simulation +sobol_sampling = run(SobolPCMM(2), reference, av) + +# Testing sensitivity with CoVariations +dv_max_time = DiscreteVariation([""overall"", ""max_time""], 12.0) + +reference = createTrial(inputs, dv_max_time; n_replicates=0) + +dv_apop = UniformDistributedVariation(configPath(""default"", ""apoptosis"", ""death_rate""), 0.0, 1.0) +dv_cycle = UniformDistributedVariation(PhysiCellModelManager.cyclePath(""default"", ""phase_durations"", ""duration:index:0""), 1000.0, 2000.0; flip=true) +dv_necr = NormalDistributedVariation(configPath(""default"", ""necrosis"", ""death_rate""), 1e-4, 1e-5; lb=0.0, ub=1.0, flip=false) +dv_pressure_hfm = UniformDistributedVariation(rulePath(""default"", ""cycle entry"", ""decreasing_signals"", ""signal:name:pressure"", ""half_max""), 0.1, 0.25) +dv_x0 = UniformDistributedVariation(icCellsPath(""default"", ""disc"", 1, ""x0""), -100.0, 0.0; flip=true) +dv_anisotropy = UniformDistributedVariation(icECMPath(2, ""elliptical_disc"", 1, ""anisotropy""), 0.0, 1.0) + +cv1 = CoVariation([dv_apop, dv_cycle]) #! I think wanted these to only be config variations? +cv2 = CoVariation([dv_necr, dv_pressure_hfm, dv_x0, dv_anisotropy]) #! I think I wanted these to be all different locations? +avs = [cv1, cv2] + +method = MOAT(4) +gsa_sampling = run(method, reference, avs) +@test size(gsa_sampling.monad_ids_df) == (4, 3) + +method = Sobolʼ(5) +gsa_sampling = run(method, reference, avs) +@test size(gsa_sampling.monad_ids_df) == (5, 4) + +method = RBD(5) +gsa_sampling = run(method, reference, avs...) # test the method with Vararg variations +@test size(gsa_sampling.monad_ids_df) == (5, 2) + +PhysiCellModelManager.deleteMonad(reference.id) + +# print tests +println(stdout, moat_sampling) +println(stdout, sobol_sampling) +println(stdout, rbd_sampling) + +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/MovieTests.jl",".jl","463","13","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +if Sys.isapple() + makeMovie(Simulation(1)) + @test isfile(joinpath(PhysiCellModelManager.dataDir(), ""outputs"", ""simulations"", ""1"", ""output"", ""out.mp4"")) + @test makeMovie(1) === false + @test makeMovie(run(Simulation(1))) |> isnothing #! makeMovie on the PCMMOutput object +else + @test_throws ErrorException makeMovie(Simulation(1)) +end","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/ImportTests.jl",".jl","4638","105","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +config_folder = ""immune_sample"" +custom_code_folder = rulesets_collection_folder = ic_cell_folder = ""immune_function"" + +path_to_project = joinpath(""PhysiCell"", ""sample_projects"", ""immune_function"") + +dest = Dict() +dest[""config""] = config_folder + +src = Dict() +src[""config""] = ""PhysiCell_settings.xml"" +src[""rulesets_collection""] = ""cell_rules.csv"" +@test importProject(path_to_project; src=src, dest=dest) isa InputFolders + +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder, ic_cell=ic_cell_folder) + +discrete_variations = [] +push!(discrete_variations, DiscreteVariation(configPath(""max_time""), 12.0)) +push!(discrete_variations, DiscreteVariation(configPath(""full_data""), 6.0)) +push!(discrete_variations, DiscreteVariation(configPath(""svg_save""), 6.0)) + +simulation_from_import = createTrial(inputs, discrete_variations; n_replicates=1) #! save this for PopulationTests.jl and GraphsTests.jl, etc. + +out = run(simulation_from_import; force_recompile=false) + +@test out.n_success == length(simulation_from_import) + +@test importProject(path_to_project; src=src, dest=dest) isa InputFolders +@test isdir(PhysiCellModelManager.locationPath(:config, ""immune_sample_1"")) + +src[""rules""] = ""not_rules.csv"" +@test importProject(path_to_project; src=src, dest=dest) |> isnothing + +path_to_fake_project = joinpath(""PhysiCell"", ""sample_projects"", ""not_a_project"") +@test importProject(path_to_fake_project) |> isnothing + +path_to_project = joinpath(""PhysiCell"", ""sample_projects"", ""template"") +folder_name = ""unique-project-name"" +@test importProject(path_to_project; dest=folder_name) isa InputFolders +for loc in [:config, :custom_code, :rulesets_collection, :ic_substrate] + @test isdir(PhysiCellModelManager.locationPath(loc, folder_name)) +end + +# intentionally sabotage the import +path_to_bad_project = joinpath(""PhysiCell"", ""sample_projects"", ""bad_template"") +cp(path_to_project, joinpath(""PhysiCell"", ""sample_projects"", ""bad_template"")) + +path_to_main = joinpath(""PhysiCell"", ""sample_projects"", ""bad_template"", ""main.cpp"") +lines = readlines(path_to_main) +idx = findfirst(x->contains(x, ""argument_parser""), lines) +lines[idx] = "" //no longer parsing because this is now a bad project"" +idx = findfirst(x->contains(x, ""// load and parse settings file(s)""), lines) +lines[idx] = "" //no longer loading settings because this is now a bad project"" +open(path_to_main, ""w"") do f + for line in lines + println(f, line) + end +end + +path_to_custom_cpp = joinpath(""PhysiCell"", ""sample_projects"", ""bad_template"", ""custom_modules"", ""custom.cpp"") +lines = readlines(path_to_custom_cpp) +idx = findfirst(x->contains(x, ""load_initial_cells""), lines) +lines[idx] = "" //no longer loading initial cells because this is now a bad project"" +open(path_to_custom_cpp, ""w"") do f + for line in lines + println(f, line) + end +end + +@test importProject(path_to_bad_project) |> isnothing + +# import the ecm project to actually use +path_to_project = joinpath(""PhysiCell"", ""sample_projects"", ""template-ecm"") +@test importProject(path_to_project) isa InputFolders + +# import the dirichlet conditions from file project +path_to_project = joinpath(""PhysiCell"", ""sample_projects"", ""dirichlet_from_file"") +@test importProject(path_to_project) isa InputFolders + +# import the combined sbml project +path_to_project = joinpath(""PhysiCell"", ""sample_projects_intracellular"", ""combined"", ""template-combined"") +src = Dict(""intracellular"" => ""sample_combined_sbmls.xml"") +@test importProject(path_to_project; src=src) isa InputFolders + +path_to_project = joinpath(""PhysiCell"", ""sample_projects_intracellular"", ""ode"", ""ode_energy"") +@test importProject(path_to_project) isa InputFolders + +# import the template xml rules (simple) project +path_to_project = joinpath(""PhysiCell"", ""sample_projects"", ""template_xml_rules"") +@test importProject(path_to_project) isa InputFolders + +# import the template xml rules (extended) project +path_to_project = joinpath(""PhysiCell"", ""sample_projects"", ""template_xml_rules_extended"") +@test importProject(path_to_project) isa InputFolders + +# dest depwarn of deprecated method +path_to_project = joinpath(""PhysiCell"", ""sample_projects"", ""template"") +src = Dict() +dest = Dict(""rules"" => ""new-rules-folder"") +@test_warn ""`importProject` with more than one positional argument is deprecated. Use the method `importProject(path_to_project; src=Dict(), dest=Dict())` instead."" importProject(path_to_project, src, dest) +@test isdir(PhysiCellModelManager.locationPath(:rulesets_collection, ""new-rules-folder""))","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/GraphsTests.jl",".jl","1464","23","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +simulation_id = 1 +snapshot = PhysiCellSnapshot(simulation_id, :final) +out = run(Simulation(simulation_id)) +c = connectedComponents(snapshot) +c = connectedComponents(out, :final; include_cell_type_names=:all) +cell_types = PhysiCellModelManager.cellTypeToNameDict(snapshot) |> values |> collect +c = connectedComponents(snapshot; include_cell_type_names=[cell_types]) +c = connectedComponents(snapshot, ""neighbors""; include_cell_type_names=[cell_types], exclude_cell_type_names=cell_types) #! for it to have empty keys after excluding + +simulation_id = simulation_from_import |> simulationIDs |> first +snapshot = PhysiCellModelManager.PhysiCellSnapshot(simulation_id, :final) +c = connectedComponents(snapshot; include_cell_type_names=[""fast T cell"", ""slow T cell"", ""effector T cell"", ""exhausted T cell""]) +c = connectedComponents(snapshot; include_dead=true) +c = connectedComponents(snapshot; include_cell_type_names=[""fast T cell"", ""slow T cell"", ""effector T cell"", ""exhausted T cell""], include_dead=true) + +#! deprecation tests +@test_warn ""Keyword argument `include_cell_types` is deprecated. Use `include_cell_type_names` instead."" connectedComponents(snapshot; include_cell_types=:all) +@test_warn ""Keyword argument `exclude_cell_types` is deprecated. Use `exclude_cell_type_names` instead."" connectedComponents(snapshot; exclude_cell_types=cell_types)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","test/test-scripts/UserAPITests.jl",".jl","1393","45","filename = @__FILE__ +filename = split(filename, ""/"") |> last +str = ""TESTING WITH $(filename)"" +hashBorderPrint(str) + +config_folder = ""0_template"" +rulesets_collection_folder = ""0_template"" +custom_code_folder = ""0_template"" +inputs = InputFolders(config_folder, custom_code_folder; rulesets_collection=rulesets_collection_folder) + +method = GridVariation() + +dv = DiscreteVariation(configPath(""max_time""), [12.0, 13.0]) + +out = run(method, inputs, dv) + +#! test that `createTrial` and `run` work on PCMMOutput{Simulation} +sim_ids = simulationIDs(out) +new_out = run(Simulation(sim_ids[1])) +test_trial = createTrial(new_out) +@test test_trial == Simulation(sim_ids[1]) +test_out = run(new_out) +@test new_out.trial == test_out.trial + +#! test that `createTrial` and `run` work on PCMMOutput{Monad} +monad = Monad(Simulation(sim_ids[1])) +new_out = run(monad) +test_trial = createTrial(new_out; n_replicates=0) +@test test_trial == monad +test_out = run(new_out) +@test new_out.trial == test_out.trial + +method = LHSVariation(3) +dv = UniformDistributedVariation(configPath(""max_time""), 12.0, 20.0) +reference = simulationIDs(out)[1] |> Simulation +out = run(method, reference, dv) + +method = SobolVariation(4) +out = run(method, reference, dv) + +method = RBDVariation(5) +out = run(method, reference, dv) + +@test_throws ArgumentError createTrial(inputs, 1, 2, 3) +@test_throws ArgumentError createTrial(reference, 1, dv, 3)","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/make.jl",".jl","1833","48","using Documenter, PhysiCellModelManager + +DocMeta.setdocmeta!(PhysiCellModelManager, :DocTestSetup, :(using PhysiCellModelManager); recursive=true) + +makedocs(; + modules=[PhysiCellModelManager], + authors=""Daniel Bergman and contributors"", + sitename=""PhysiCellModelManager.jl"", + format=Documenter.HTML(; + canonical=""https://drbergman-lab.github.io/PhysiCellModelManager.jl"", + edit_link=""main"", + assets=String[], + ), + pages=[ + ""Home"" => ""index.md"", + ""Manual"" => Any[ + ""Best practices"" => ""man/best_practices.md"", + ""Getting started"" => ""man/getting_started.md"", + ""Varying parameters"" => ""man/varying_parameters.md"", + ""Querying parameters"" => ""man/querying_parameters.md"", + ""XML path helpers"" => ""man/xml_path_helpers.md"", + ""CoVariations"" => ""man/covariations.md"", + ""Data directory"" => ""man/data_directory.md"", + ""Intracellular inputs"" => ""man/intracellular_inputs.md"", + ""Known limitations"" => ""man/known_limitations.md"", + ""PhysiCell Studio"" => ""man/physicell_studio.md"", + ""Sensitivity analysis"" => ""man/sensitivity_analysis.md"", + ""Analyzing output"" => ""man/analyzing_output.md"", + ""Developer guide"" => ""man/developer_guide.md"", + ""Project configuration"" => ""man/project_configuration.md"", + ""Index"" => ""man/index.md"", + ], + ""Documentation"" => map( + s -> ""lib/$(s)"", + sort(readdir(joinpath(@__DIR__, ""src/lib""))) + ), + ""Miscellaneous"" => Any[ + ""Database upgrades"" => ""misc/database_upgrades.md"", + ], + ], +) + +deploydocs(; + repo=""github.com/drbergman-lab/PhysiCellModelManager.jl"", + devbranch=""main"", + push_preview=true, +) +","Julia" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/index.md",".md","618","9","```@meta +CurrentModule = PhysiCellModelManager +``` + +# PhysiCellModelManager.jl +[PhysiCellModelManager.jl](https://github.com/drbergman-lab/PhysiCellModelManager.jl) (PCMM) is a Julia package that provides a framework for running large [PhysiCell](https://github.com/MathCancer/PhysiCell) simulation campaigns. See [Getting started](@ref) for getting PhysiCellModelManager.jl set up and running. + +## Issues +Have an issue? First check the [Known limitations](@ref) and [Best practices](@ref) sections. If you still have an issue, please submit it [here](https://github.com/drbergman-lab/PhysiCellModelManager.jl/issues).","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/getting_started.md",".md","6506","131","# Getting started +Read [Best practices](@ref) before using PhysiCellModelManager.jl. +## Install PhysiCellModelManager.jl +### Download julia +The easiest way to install julia is to use the command line. On Linux and macOS, you can run: +```sh +curl -fsSL https://install.julialang.org | sh +``` + +On Windows, you can run: +```powershell +winget install --name Julia --id 9NJNWW8PVKMN -e -s msstore +``` + +Note: this command also installs the [JuliaUp](https://github.com/JuliaLang/juliaup) installation manager, which will automatically install julia and help keep it up to date. + +See [here](https://julialang.org/install) for the Julia installation home page. See [here](https://julialang.org/downloads/) for more download options. + +### Add the BergmanLabRegistry +Launch julia by running `julia` in a shell. +Then, enter the Pkg REPL by pressing `]`. +Make sure the General registry is set up by running: +```julia-repl +pkg> registry add General +``` +Finally, add the BergmanLabRegistry by running: +```julia-repl +pkg> registry add https://github.com/drbergman-lab/BergmanLabRegistry +``` + +### Install PhysiCellModelManager.jl +Still in the Pkg REPL, run: +```julia-repl +pkg> add PhysiCellModelManager +``` + +## Set up a PhysiCellModelManager.jl project +Leave the Pkg REPL by pressing the `delete` or `backspace` key (if still in it from the previous step). +Load the PhysiCellModelManager.jl module by running: +```julia-repl +julia> using PhysiCellModelManager +``` +Then, create a new PCMM project by running: +```julia-repl +julia> createProject(path_to_project_folder) # createProject() will use the current directory as the project folder +``` +This creates three folders inside the `path_to_project_folder` folder: `data/`, `PhysiCell/`, and `scripts/`. +See [Data directory structure](@ref) for information about the `data/` folder. +> Note: A PCMM project is distinct from PhysiCell's `sample_projects` and `user_projects`. + +## (Optional) Import from `user_projects` +### Inputs +If you have a project in the `PhysiCell/user_projects/` (or `PhysiCell/sample_projects`) folder that you would like to import, you can do so by running [`importProject`](@ref): +```julia-repl +julia> importProject(path_to_project_folder) +``` +The `path_to_project_folder` string can be either the absolute path (recommended) or the relative path (from the directory julia was launched) to the project folder. + +This function assumes your project files are in the standard `PhysiCell/user_projects/` format. +See the table below for the standard locations of the files. +The `Default directory` column shows the path relative to `path_to_project_folder`. + +| Input | Default directory | Default name | Key | Optional | +| --- | --- | --- | --- | :---: | +| config | `config` | `PhysiCell_settings.xml` | `config` | | +| main | `.` | `main.cpp` | `main` | | +| Makefile | `.` | `Makefile` | `makefile` | | +| custom modules | `.` | `custom_modules/` | `custom_modules` | | +| rules | `config` | `cell_rules.{csv,xml}` | `rulesets_collection` | X | +| cell initial conditions | `config` | `cells.csv` | `ic_cell` | X | +| substrate initial conditions | `config` | `substrates.csv` | `ic_substrate` | X | +| ECM initial conditions | `config` | `ecm.csv` | `ic_ecm` | X | +| DC initial conditions | `config` | `dcs.csv` | `ic_dc` | X | +| intracellular model | `config` | `intracellular.xml` | `intracellular` | X | + +If any of these files are not located in the standard location, you can define a dictionary with keys taken from the table above to specify the path to each file. +**These must be relative to the `Default directory`.** +For example, if the config file is instead located at `PhysiCell/user_projects/[project_name]/config/config.xml`, you would run: +```julia-repl +julia> src = Dict(""config"" => ""config.xml"") +``` +Additional entries can be added in a comma-separated list into `Dict` or added later with `src[key] = rel_path`. +Pass the dictionary in as the second argument as follows: +```julia-repl +julia> importProject(path_to_project_folder; src=src) +``` + +#### Rulesets collection +The rulesets collection can be in either the base PhysiCell CSV version or the `drbergman/PhysiCell` XML version. +`importProject` will first look for `cell_rules.csv` in the `config` folder and if not found, it will look for `cell_rules.xml`. + +#### Intracellular models +If you have previously assembled an intracellular model for use with the `drbergman/PhysiCell` fork, you can import it following the table above. +If the `intracellular` key is not provided and `config/intracellular.xml` is not found, `importProject` will look through the config file to see if any intracellular models are specified and assemble the `intracellular.xml` file from those. + +### Post-processing +If you use `importProject`, then the GenerateData.jl script must be updated to reflect the new project folders. +By default, the folder names are taken from the name of the project with an integer appended if it already exists. +If you want to use a different name, you can pass a `dest` dictionary to `importProject` with the keys tkaen from the table below. +| Output | Key | +| --- | --- | +| config | `config` | +| custom code | `custom_code` | +| rulesets collection | `rulesets_collection` | +| cell initial conditions | `ic_cell` | +| substrate initial conditions | `ic_substrate` | +| ECM initial conditions | `ic_ecm` | +| DC initial conditions | `ic_dc` | +| intracellular | `intracellular` | + +## Running first trial +The `createProject()` command creates three folder, including a `scripts` folder with a single file: `scripts/GenerateData.jl`. +The name of this folder and this file are purely convention, change them as you like. +To run your first PhysiCellModelManager.jl trial, you can run the GenerateData.jl script from the shell: +```sh +julia scripts/GenerateData.jl +``` +Note: if you want to parallelize these 9 runs, you can set the shell environment variable `PCMM_NUM_PARALLEL_SIMS` to the number of parallel simulations you want to run. For example, to run 9 parallel simulations, you would run: +```sh +export PCMM_NUM_PARALLEL_SIMS=9 +julia scripts/GenerateData.jl +``` +Or for a one-off solution: +```sh +PCMM_NUM_PARALLEL_SIMS=9 julia scripts/GenerateData.jl +``` +Alternatively, you can run the script via the REPL. + +Run the script a second time and observe that no new simulations are run. +This is because PhysiCellModelManager.jl looks for matching simulations first before running new ones. +The `use_previous` optional keyword argument can control this behavior if new simulations are desired.","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/analyzing_output.md",".md","14810","246","# Analyzing output + +## Install dependencies +Julia has several packages for plotting. +Here, we will use `Plots.jl` which you can install with +```julia-repl +pkg> add Plots +``` + +## Loading output + +### `PhysiCellSnapshot` +The base unit of PhysiCell output is the `PhysiCellSnapshot`. +Each snapshot records the path to the PhysiCell output folder, its index in the sequence of outputs, the time of the snapshot in the simulation, and optionally the cell, substrate, and mesh data at that snapshot. + +### `PhysiCellSequence` +A `PhysiCellSequence` is the full sequence of snapshots corresponding to a single PhysiCell simulation. +In addition to the path to the PhysiCell output folder and the vector of `PhysiCellSnapshot`'s, it holds metadata for the simulation. + +### `cellDataSequence` +The main function to get sequences of cell data is `cellDataSequence`. +It accepts any of a simulation ID (`<:Integer`), a simulation (`::Simulation`), or a sequence (`::PhysiCellSequence`) and either a single label (`::String`) or a vector of labels (`::Vector{String}`). +For each cell in the simulation (as determined by the cell ID), the output creates a dictionary entry (the key is the integer cell ID) whose value is a named tuple with the input labels as keys as well as `:time`. +This means that if one sets + +```julia +data = cellDataSequence(1, ""position"") +``` +Then one can access the positions of the cell with ID 78 by +```julia +cell_78_positions = data[78].position # an Nx3 matrix for the N integer-indexed outputs (ignores the `initial_*` and `final_*` files) +``` +and plot the x-coordinates of this cell over time using +```julia +cell_78_times = data[78].time + +using Plots +plot(cell_78_times, cell_78_positions[:,1]) +``` + +**Note**: Each call to `cellDataSequence` will load *all* the data unless a `PhysiCellSequence` is passed in. +Plan your analyses accordingly as loading simulation data is not fast. + +## Population plots + +### Group by Monad +Plotting population plots is one the most basic analysis tasks and PhysiCellModelManager.jl makes it super easy! +If you call `plot` on a `Simulation`, `Monad`, `Sampling`, or the return value of a call to `run` (though not for a sensitivity analysis), +then a sequence of panels will be generated in a single figure. +Each panel will correspond to a `Monad` (replicates using the same parameter values) and will plot mean +/- SD for each cell type. + +Finer-grained control of the output is possible, too! +- to include dead cells in your counts: `plot(...; ..., include_dead=true, ...)` +- select a subset of cell types to include: `plot(...; ..., include_cell_type_names=""cancer"", ...)` +- select a subset of cell types to exclude: `plot(...; ..., exclude_cell_type_names=""cancer"", ...)` +- choose time units for the x-axis: `plot(...; ..., time_unit=:h, ...)` + +The `include_cell_type_names` and `exclude_cell_type_names` can also accept a `Vector{String}` to include or exclude certain cell types, respectively. +Furthermore, if the value of `include_cell_type_names` is a `Vector` and one of its entries is a `Vector{String}`, PhysiCellModelManager.jl will interpret this to sum up those cell types. +In other words, to get the total tumor cell count in addition to the epithelial (`""epi""`) and mesenchymal (`""mes""`) components, you could use +```julia +using Plots +plot(Monad(1); include_cell_type_names=[""epi"", ""mes"", [""epi"", ""mes""]]) +``` + +Finally, this makes use of Julia's Plot Recipes (see [RecipesBase.jl](https://docs.juliaplots.org/stable/RecipesBase/)) so any standard plotting keywords can be passed in: +```julia +using Plots +colors = [:blue :red] # Note the absence of a `,` or `;`. This is how Julia requires different series parameters to be passed in +plot(Simulation(1); color=colors, include_cell_type_names=[""cd8"", ""cancer""]) # will plot cd8s in blue and cancer in red. +``` + +### Group by cell type +Invert the above by including all data for a single cell type across all monads in a single panel with a call to `plotbycelltype`. +This function works on any `T<:AbstractTrial` (`Simulation`, `Monad`, `Sampling`, or `Trial`) as well as any `PCMMOutput` object (the return value to `run`). +Everything above for `plot` applies here. + +```julia +using Plots +plotbycelltype(Sampling(1); include_cell_type_names=[""epi"", ""mes"", [""epi"", ""mes""]], color=[:blue :red :purple], labels=[""epi"" ""mes"" ""both""], legend=true) +``` + +## Substrate analysis +PhysiCellModelManager.jl supports two ways to summarize substrate information over time. + +### `AverageSubstrateTimeSeries` +An `AverageSubstrateTimeSeries` gives the time series for the average substrate across the entire domain. + +```julia +simulation_id = 1 +asts = PhysiCellModelManager.AverageSubstrateTimeSeries(simulation_id) +using Plots +plot(asts.time, asts[""oxygen""]) +``` + +### `ExtracellularSubstrateTimeSeries` +An `ExtracellularSubstrateTimeSeries` gives the time series for the average substrate concentration in the extracellular space neighboring all cells of a given cell type. +In a simulation with `cd8` cells and `IFNg` diffusible substrate, plot the average concentration of IFNg experienced by CD8+ T cells using the following: + +```julia +simulation_id = 1 +ests = PhysiCellModelManager.ExtracellularSubstrateTimeSeries(simulation_id) +using Plots +plot(ests.time, ests[""cd8""][""IFNg""]) +``` + +## Motility analysis +The `motilityStatistics` function returns the time alive, distance traveled, and mean speed for each cell in the simulation. +For each cell, these values are split amongst the cell types the given cell assumed throughout (or at least at the save times). +To calculate these values, the cell type at the start of the save interval is used and the net displacement is used to calculate the speed. +Optionally, users can pass in a coordinate direction to only consider speed in a given axis. + +```julia +simulation_id = 1 +mss = motilityStatistics(simulation_id) +all_mean_speeds_as_mes = [ms[""mes""].speed for ms in mss if haskey(ms, ""mes"")] # concatenate all speeds as a ""mes"" cell type (if the given cell ever was a ""mes"") +all_times_as_mes = [ms[""mes""].time for ms in mss if haskey(ms, ""mes"")] # similarly, get the time spent in the ""mes"" state +mean_mes_speed = all_mean_speeds_as_mes .* all_times_as_mes |> sum # start computing the weighted average of their speeds +mean_mes_speed /= sum(all_times_as_mes) # finish computing weighted average +``` + +```julia +mss = motilityStatistics(simulation_id; direction=:x) # only consider the movement in the x direction +``` + +## Pair correlation function (PCF) +Sometimes referred to as radial distribution functions, the pair correlation function (PCF) computes the density of target cells around center cells. +If the two sets of cells are the same (centers = targets), this is called PCF. +If the two are not equal, this is sometimes called cross-PCF. +Both can be computed with a call to `PhysiCellModelManager.pcf` (or just `pcf` if `using PairCorrelationFunction` has been called). + +### Arguments +PCF computations can readily be called on `PhysiCellSnapshot`'s, `PhysiCellSequence`'s, or `Simulation`'s. +If the first argument in a call to `pcf` is an `Integer`, this is treated as a simulation ID. +If this is followed by an index (of type `Integer` or value `:initial` or `:final`), this is treated as a snapshot; otherwise, it computes the PCF for the entire simulation. + +The next argument is the cell type to use as the center cells as either a `String` or `Vector{String}`, representing the name of the cell type(s). +If the target cells are different from the center cells, the next argument is the target cell type as either a `String` or `Vector{String}`. +If omitted, the target cell type is the same as the center cell type and a (non-cross) PCF is computed. +The resulting sets of center and target cell types must either be identical or have no overlap. + +### Keyword arguments +The following keyword arguments are available: +- `include_dead::Union{Bool, Tuple{Bool,Bool}} = false`: whether to include dead cells in the PCF computation. + - If `true`, all cells are included. + - If `false`, only live cells are included. + - If a tuple, the first value is for the center cells and the second is for the target cells. +- `dr::Float64 = 20.0`: the step size for the radial bins in micrometers. + +### Output +The output of `pcf` is a `PCMMPCFResult` object which has two fields: `time` and `pcf_result`. +The `time` field is always a vector of the time points at which the PCF was computed, even if computing PCF for a single snapshot. +The `pcf_result` is of type `PairCorrelationFunction.PCFResult` and has two fields: `radii` and `g`. +The `radii` is the set of cutoffs used to compute the PCF and `g` is either a vector or a matrix of the PCF values of size `length(radii)-1` by `length(time)`. + +### Plotting +An API to make use of the PairCorrelationFunction.jl package plotting interface is available through the `plot` function. +Simply pass in the `PCMMPCFResult`! +You can pass in as many such objects as you like or pass in a `Vector{PCMMPCFResult}`. +In this case, these are interpreted as stochastic realizations of the same PCF and summary statistics are used to plot. +See the [PairCorrelationFunction.jl documentation](https://drbergman-lab.github.io/PairCorrelationFunction.jl/stable/) for more details. + +The PhysiCellModelManager.jl implementation supports two keyword arguments: +- `time_unit::Symbol = :min`: the time unit to use for the time axis (only relevant if the `PCMMPCFResult` has more than one time point). + - The default is `:min` and the other options are `:s`, `:h`, `:d`, `:w`, `:mo`, `:y`. +- `distance_unit::Symbol = :um`: the distance unit to use for the distance axis. + - The default is `:um` and the other options are `:mm` and `:cm`. + +Finally, a keyword argument supported by PairCorrelationFunction.jl is `colorscheme` which can be used to change the colorscheme of the color map. +PhysiCellModelManager.jl overrides the default from PairCorrelationFunction.jl (`:tofino`) with `:cork` to use white to represent values near one. + +### Examples +```julia +simulation_id = 1 +result = PhysiCellModelManager.pcf(simulation_id, ""cancer"", ""cd8"") # using PairCorrelationFunction will obviate the need to prefix with `PhysiCellModelManager` +plot(result) # heatmap of proximity of (living) cd8s to (living) cancer cells throughout simulation 1 +``` +```julia +monad = Monad(1) # let's assume that there are >1 simulations in this monad +results = [PhysiCellModelManager.pcf(simulation_id, :final, ""cancer"", ""cd8"") for simulation_id in simulationIDs(monad)] # one vector of PCF values for each simulation at the final snapshot +plot(results) # line plot of average PCF values against radius across the monad +/- 1 SD +``` +```julia +monad = Monad(1) # let's assume that there are >1 simulations in this monad +results = [PhysiCellModelManager.pcf(simulation_id, ""cancer"", ""cd8"") for simulation_id in simulationIDs(monad)] # one matrix of PCF values for each simulation across all time points +plot(results) # heatmap of average PCF values with time on the x-axis and radius on the y-axis; averages omit NaN values that can occur at higher radii +``` + +## Graph analysis +Every PhysiCell simulation produces three different directed graphs at each save time point. +For each graph, the vertices are the cell agents and the edges are as follows: +- `:neighbors`: the cells overlap based on their positions and adhesion radii +- `:attachments`: manually-defined attachments between cells +- `:spring_attachments`: spring attachments formed automatically using attachment rates +Each of these graphs is expected to be symmetric, i.e., if cell A is attached to cell B, then cell B is attached to cell A. +Nonetheless, PhysiCellModelManager.jl holds the data in a directed graph. + +Currently, PhysiCellModelManager.jl supports computing connected components for any of these graphs using the [`connectedComponents`](@ref) function. +For an [`PhysiCellModelManager.AbstractPhysiCellSequence`](@ref) object, the graphs can be loaded using the [`loadGraph!`](@ref) function for any other analysis. + +### Examples +For all examples that follow, we will assume a [`PhysiCellSnapshot`](@ref) object called `snapshot` has been created, e.g., as follows: +```julia +simulation_id = 1 +index = :final +snapshot = PhysiCellSnapshot(simulation_id, index) +``` + +To get a list of the connected components for the `:neighbors` graph for all living cells in a simulation at the final timepoint, use +```julia +connected_components = connectedComponents(snapshot) # defaults to the :neighbors graph, all cells, and exclude dead cells +``` +The `connected_components` object is a `Dict` with the cell type names in a single vector as the only key with value a vector of vectors. +Each element is a vector of the cell IDs belonging to that connected component in the wrapper type [`PhysiCellModelManager.AgentID`](@ref). + +If you want to compute connected components for subsets of cells, pass in a vector of vectors of cell type names (`String`s) such that each vector corresponds to a subset of cell types. +```julia +subset_1 = [""cd8_active"", ""cd8_inactive""] +subset_2 = [""cancer_epi"", ""cancer_mes""] +connected_components = connectedComponents(snapshot; include_cell_type_names=[subset_1, subset_2]) +``` +In this case, the `connected_components` object is a `Dict` with `subset_1` and `subset_2` as the keys (the values stored in them, not the strings `""subset_1""` and `""subset_2""`). +The value `connected_components[subset_1]` is a vector of vectors of the cell IDs belonging to each connected component just considering the cells in `subset_1`. +Similarly for `subset_2`. + +Including dead cells is possible though not recommended. +This is because dead cells automatically clear their neighbors and (both kinds of) attachments. +The optional keyword argument `include_dead` can be set to `true` to include dead cells in the graph. +```julia +connected_components = connectedComponents(snapshot; include_dead=true) +``` + +Finally, to combine a single connected component with the dataframe of cell data, the following can be used: +```julia +connected_components = connectedComponents(snapshot) +connected_components_1 = connected_components |> # julia's pipe operator + values |> # get the value for each key + first |> # get the connected components for the first subset of cells (in this case there's only one subset consisting of all cells) + first # get the first connected component for this subset + +loadCells!(snapshot) # make sure the cell data is loaded +cells_df = snapshot.cells # this is the cell data + +agent_ids = DataFrame(ID=[a.id for a in connected_components_1]) # get the IDs for the agents in the connected component +component_df = rightjoin(cells_df, agent_ids, on=:ID) # join on the agent IDs, keeping only the rows in the connected component +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/varying_parameters.md",".md","2527","55","# Varying parameters +All inputs that are varied by PhysiCellModelManager.jl are stored in XML files, and PhysiCellModelManager.jl has a standard representation of the paths to these parameters. + +## XML paths +XML paths are represented as a vector of strings, where each string corresponds to a tag in the XML file. +When an attribute is needed to identify which of the identically tagged children to select, the string is formatted as +```julia +""::"" +``` + +If the content of a child element is needed to identify which tag to select, the string is formatted as +```julia +"":::"" +``` +where `::` is used to separate the tag from the child tag. +This is necessary, e.g., for the `initial_parameter_distributions` as the `behavior` is a child element of the `distribution` element: +```julia +[""cell_definitions"", ""cell_definition:name:T_cell"", ""initial_parameter_distributions"", ""distribution::behavior:cycle entry""] +``` + +See [Helper functions to define targets](@ref) for helper functions that can be used to create these paths easily for all the varied input types. + +## Discrete variations +Once the XML path is defined, a discrete variation (selecting a finite set of values) can be defined using [`DiscreteVariation`](@ref): + +```julia +xml_path = configPath(""max_time"") +dv = DiscreteVariation(xml_path, [1440.0, 2880.0]) +``` + +These can then be passed into either [`createTrial`](@ref) or ([`run`](@ref)) to create (or run) simulations with the specific paramater variations, automatically adding them to the database for future reference. +If multiple variations are used, they are by default combined on a grid, i.e., all combinations of the variations are used. + +```julia +xml_path = configPath(""cd8"", ""cycle"", ""rate"", 0) +dv_g1 = DiscreteVariation(xml_path, [0.001, 0.002]) #! vary g1 duration + +xml_path2 = configPath(""cd8"", ""cycle"", ""rate"", 1) +dv_s = DiscreteVariation(xml_path2, [0.001, 0.002, 0.003]) #! vary s duration + +sampling = createTrial(inputs, dv_g1, dv_s; n_replicates=4) #! will run 2x3=6 monads (identical parameters) 4 times each for a total of 24 simulations +``` + +## Distributed variations +Distributed variations are used to vary a parameter over a continuous range, e.g., a range of values for a parameter. +These are defined using [`DistributedVariation`](@ref): + +```julia +using Distributions +xml_path = configPath(""cd8"", ""apoptosis"", ""rate"") +d = Uniform(0, 0.001) +dv = DistributedVariation(xml_path, d) +``` + +These variations are useful for doing [Sensitivity analysis](@ref).","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/querying_parameters.md",".md","2100","34","# Querying parameters +It is often helpful to access the parameters used in a simulation after it has been run. +There are two main ways to achieve this: +- [`simulationsTable`](@ref) uses the databases and excels at user-readability +- [`getAllParameterValues`](@ref) uses all values in the XMLs, exceling at programmatic access + +## [`simulationsTable`](@ref) +The function [`simulationsTable`](@ref) can be used to print a table of simulation data. +This function, by default, only prints varied values and does some renaming to make the column names more human-readable. + +The function [`printSimulationsTable`](@ref) is a convenience wrapper around [`simulationsTable`](@ref) that prints the table directly. +Use the `sink` keyword argument to, for example, redirect the output to a file instead of the console. + +## [`getAllParameterValues`](@ref) +The function [`getAllParameterValues`](@ref) can be used to programmatically access all the terminal elements in the XML input files for a given set of simulations. +The simulations must all belong to the same `Sampling`, i.e. use the same input files. +The column names are the XML paths to the parameters, meaning they can be converted into the format for creating a [`DiscreteVariation`](@ref), for example, by splitting on `/`. + +```julia +df = getAllParameterValues(sampling) +col1 = names(df)[1] # get the name of the first column +xml_path = split(col1, ""/"") # convert to XML path format +dv = DiscreteVariation(xml_path, [0.0, 1.0]) # create a discrete variation using this parameter +``` + +The internal functions [`PhysiCellModelManager.columnName`](@ref) and [`PhysiCellModelManager.columnNameToXMLPath`](@ref) can also be used to convert between the column names and XML paths. + +> Note: The XML paths returned by [`getAllParameterValues`](@ref) as column names **may** include what look like attributes to distinguish between multiple children with the same tag. +> These can be found by searching for column names with `"":temp_id:""` in them: + +```julia +df = getAllParameterValues(sampling) +names_with_temp_id = filter(contains("":temp_id:""), names(df)) +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/data_directory.md",".md","3872","78","# Data directory structure + +To set up your PhysiCellModelManager.jl-enabled repository within `project-dir` (the name of your project directory), create the following directory structure: + +``` +project-dir/ +├── data/ +│ └── inputs/ +│ ├── configs/ +│ ├── custom_codes/ +│ ├── ics/ +│ │ ├── cells/ +│ │ ├── dcs/ +│ │ ├── ecms/ +│ │ └── substrates/ +│ ├── intracellulars/ +│ ├── rulesets_collections/ +... +``` + +Within each of the terminal subdirectories above within `data/inputs/`, add a subdirectory with a user-defined name with content described below. +We will use the name `""default""` for all as an example. + +## Configs + +Add a single file within `data/inputs/configs/default/` called `PhysiCell_settings.xml` with the base configuration file for your PhysiCell project. + +## Custom codes + +Add within `data/inputs/custom_codes/default/` the following, each exactly as is used in a PhysiCell project: +- `main.cpp` +- `Makefile` +- `custom_modules/` + +## Rulesets collections + +Add a single file within `data/inputs/rulesets_collections/default/` called `base_rulesets.csv` with the base ruleset collection for your PhysiCell project. +If your project does not use rules, you can skip this step. + +You may also place an XML file here. Use [PhysiCellXMLRules.jl](https://github.com/drbergman-lab/PhysiCellXMLRules.jl) to create one from a standard CSV version of the rules. + +**Important**: In either case, the variations you define *must* be on the XML version. +After calling [`initializeModelManager`](@ref), any folder with `base_rulesets.csv` will now be populated with a `base_rulesets.xml` file that can be referenced to set the XML paths. + +## Intracellulars + +Add a single XML file within `data/inputs/intracellulars/default/` called `intracellular.xml` in which the root has two child elements: `cell_definitions` and `intracellulars`. +This currently only supports libRoadRunner, i.e., ODEs. +See the `sample_projects_intracellular/combined/template-combined` for an example. +See [Intracellular inputs](@ref) for much more information. + +## ICs + +These folders are optional as not every model includes initial conditions as separate files. +If your model does, for each initial condition add a subfolder. +For example, if you have two initial cell position conditions, `random_cells.csv` and `structured_cells.csv`, the `data/inputs/ics/cells/` directory would look like this: +``` +cells/ +├── random_cells/ +│ └── cells.csv +└── structured_cells/ + └── cells.csv +``` +**Note:** Place the files in their corresponding folders and rename to `cells.csv`. + +Proceed similarly for `dcs/`, `ecms/`, and `substrates/`, renaming those files to `dcs.csv`, `ecm.csv`, and `substrates.csv`, respectively. + +### IC cells + +PhysiCellModelManager.jl uses [PhysiCellCellCreator.jl](https://github.com/drbergman-lab/PhysiCellCellCreator.jl) to allow for creation of `cells.csv` files based on geometries defined in a `cells.xml` file. +To use this, first create such an XML document (see [PhysiCellCellCreator.jl](https://github.com/drbergman-lab/PhysiCellCellCreator.jl) for details) and place this in place of the `cells.csv` file. +You may make variations on this in the same way as for `config` and `rulesets_collection`. + +### IC ecm + +PhysiCellModelManager.jl uses [PhysiCellECMCreator.jl](https://github.com/drbergman-lab/PhysiCellECMCreator.jl) to allow for creation of `ecm.csv` files based on the structure defined in a `ecm.xml` file. +To use this, first create such an XML document (see [PhysiCellECMCreator.jl](https://github.com/drbergman-lab/PhysiCellECMCreator.jl) for details) and place this in place of the `ecm.csv` file. +You may make variations on this in the same way as for `config` and `rulesets_collection`.","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/physicell_studio.md",".md","3234","63","# Using PhysiCell Studio +See [PhysiCell-Studio](https://github.com/PhysiCell-Tools/PhysiCell-Studio). +Using PhysiCell Studio within PhysiCellModelManager.jl is designed for visualizing output in the `Plot` tab and observing model parameters in the remaining tabs. + +**Do not use the `Run` tab in PhysiCell Studio as this may delete simulation data.** + +See [below](#editing-in-physicell-studio) for how to edit the configuration and rules files in studio. + +## Setting paths +### Environment variables +You must first inform PhysiCellModelManager.jl where your desired `python` executable is and the PhysiCell Studio folder. +The recommended way to do this on macOS/Linux is to add the following two lines to your shell environment file (e.g. `~/.bashrc` or `~/.zshenv`): +``` +export PCMM_PYTHON_PATH=/usr/bin/python3 +export PCMM_STUDIO_PATH=/home/user/PhysiCell-Studio +``` +If your python executable is on your PATH, you can set `PCMM_PYTHON_PATH=python3`, for example. + +After making these changes, make sure to source the file to apply the changes: +```sh +source ~/.bashrc +``` +Or open a new terminal window. + +On Windows, the simplest way to set these is to use the GUI for setting environment variables. + +Troubleshooting: If you are having trouble launching PhysiCell Studio... +- `PCMM_PYTHON_PATH` must point to a valid python executable +- `PCMM_STUDIO_PATH` must point to the PhysiCell Studio folder, **not the `studio.py` file** +- the `~` character is not expanded when in quotes, so `export PCMM_STUDIO_PATH=""~/PhysiCell-Studio""` will not work + +### Using keyword arguments +If you prefer not to set these environment variables, you can pass the paths as keyword arguments to the `runStudio` function. +It will remember these settings during the session, so you only need to pass them once. +See below for the function signature. + +## Launching PhysiCell Studio +First, launch julia in a new shell session and make sure the project is initialized by running: +```julia +using PhysiCellModelManager +``` +> Note: If you have already loaded the package in this session, run [`initializeModelManager`](@ref) if you need to initialize the project. + +As soon as the simulation has begun (so that its PhysiCell-generated `output` folder is created and populated), you can launch PhysiCell Studio. +If you set the environment variables, you can run the following command for a simulation with id `sim_id::Integer`: +```julia-repl +julia> runStudio(sim_id) +``` +If you did not set the environment variables, you can run the following command: +```julia-repl +julia> runStudio(sim_id; python_path=path_to_python, studio_path=path_to_studio) +``` + +## Editing in PhysiCell Studio +When you run the `runStudio` function, PhysiCell Studio will open with the simulation you specified using temporary files for the configuration and rules. +Any edits to these in studio will be lost when the studio is closed. +Remember: this is the output of a simulation that __already__ ran. +Use the `File > Save as` dropdown to save the configuration file. +Use the `Rules` tab to save the rules file. +Note: the recent changes in PhysiCell 1.14.1 copying over the initial conditions files are not yet supported by this. +See [Known limitations](#known-limitations) for more information. + +","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/developer_guide.md",".md","233","6","# Developer guide + +## Style guide +- Use `#!` for comments that are informative + - This helps find code lines commented out in development. + - Using the regexp `^(\s+)?# .+\n` seems to work well for finding commented out code lines.","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/intracellular_inputs.md",".md","2334","31","# Intracellular inputs + +PhysiCellModelManager.jl currently only supports ODE intracellular models using libRoadRunner. +It uses a specialized format to achieve this, creating the SBML files needed by libRoadRunner at PhysiCell runtime. +Briefly, the `intracellular.xml` file defines a mapping between cell definitions and intracellular models. +See the template provided [here](https://github.com/drbergman/PhysiCell/blob/my-physicell/sample_projects_intracellular/combined/template-combined/config/sample_combined_sbmls.xml). + +To facilitate creation of such files, and to make it easy to mix-and-match intracellular models, users can place the SBML files that define the ODEs into `data/components/roadrunner` and then simply reference those to construct the specialized XMLs needed. +For example, place the `Toy_Metabolic_Model.xml` from [sample\_projects\_intracellular/ode/ode\_energy/config/](https://github.com/drbergman/PhysiCell/blob/my-physicell/sample_projects_intracellular/ode/ode_energy/config) into `data/components/roadrunner` and assemble the XML as follows + +```julia +cell_type = ""default"" # name of the cell type using this intracellular model +component = PhysiCellComponent(""roadrunner"", ""Toy_Metabolic_Model.xml"") # pass in the type of the component and the name of the file to use +cell_type_to_component = Dict{String, PhysiCellComponent}(cell_type => component) # add other entries to this Dict for other cell types using an intracellular model +intracellular_folder = assembleIntracellular!(cell_type_to_component; name=""toy_metabolic"") # will return ""toy_metabolic"" or ""toy_metabolic_n"" +``` + +This creates a folder at `data/inputs/intracellulars/` with the name stored in `intracellular_folder`. +Also, the `!` in `assembleIntracellular!` references how the components in the `cell_type_to_component` `Dict` are updated to match those in `data/inputs/intracellulars/$(intracellular_folder)/intracellular.xml`. +Use these IDs to make variations on the components by using + +```julia +xml_path = [""intracellulars"", ""intracellular:ID:$(component.id)"", ...] +``` + +where the `...` is the path starting with the root of the XML file (`sbml` for SBML files). + +Finally, pass this folder into `InputFolders` to use this input in simulation runs: +```julia +inputs = InputFolders(...; ..., intracellular=intracellular_folder, ...) +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/index.md",".md","22","4","# Index + +```@index +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/xml_path_helpers.md",".md","3906","72","# Helper functions to define targets +For each of the varied input types, PhysiCellModelManager.jl has a helper function to create the XML path. + +## Varying config parameters +The [`configPath`](@ref) function can be used to create the XML path to almost[^1] any parameter in the configuration file intuitively. +See [Config XML paths](@ref) for an exhaustive explanation of the available tokens. +Here are some simple examples to get you started: + +```julia +configPath(""max_time"") +configPath(""full_data_interval"") +configPath(, ""diffusion_coefficient"") +configPath(, ""cycle"", ""rate"", 0) +configPath(, ""speed"") +configPath(, ""custom"", ) +configPath(""user_parameters"", ) +``` + +[^1]: Intracellular parameters are not supported (yet). Others may also be missing. If the [`configPath`](@ref) function does not recognize the tokens you pass it, it will throw an error showing the available tokens (for the given number of tokens you passed). + +## Varying rules parameters +The [`rulePath`](@ref) function can help start the XML path to rules parameters. +It does not infer the full path from tokens like [`configPath`](@ref), but relies on the user knowing the structure of the rules XML file. +The first argument is the cell type and the second argument is the behavior. +The remaining arguments are the remaining entries in the XML path. +Here are some examples: + +```julia +rulePath(, , ""increasing_signals"", ""max_response"") +rulePath(, , ""decreasing_signals"", ""max_resposne"") +rulePath(, , ""increasing_signals"", ""signal:name:"", ) +rulePath(, , ""decreasing_signals"", ""signal:name:"", ""reference"", ""value"") +``` + +## Varying initial cell parameters +PhysiCellModelManager.jl supports an XML-based initialization of cell locations using [PhysiCellCellCreator.jl](https://github.com/drbergman-lab/PhysiCellCellCreator.jl). +See the documentation of that package for details on how to create the XML file. +Use [`PhysiCellModelManager.createICCellXMLTemplate`](@ref) to create a template XML file and automatically add it to the database. +From there, you can edit it directly (though as per [Best practices](@ref) do not edit after simulations are created that rely on it). + +To vary parameters in this XML file, the [`icCellsPath`](@ref) function can be used. +The signature is as follows: + +```julia +icCellsPath(, , , ) +``` + +[PhysiCellCellCreator.jl](https://github.com/drbergman-lab/PhysiCellCellCreator.jl) supports carveouts that can be used to not place cells within the given patches. +These are contained in a child element of the patch element and their parameters can be varied using the following signature: + +```julia +icCellsPath(, , , , , ) +``` + +## Varying initial ECM parameters +PhysiCellModelManager.jl supports an XML-based initialization of ECMs using [PhysiCellECMCreator.jl](https://github.com/drbergman-lab/PhysiCellECMCreator.jl). +See the documentation of that package for details on how to create the XML file. +Use [`PhysiCellModelManager.createICECMXMLTemplate`](@ref) to create a template XML file and automatically add it to the database. +From there, you can edit it directly (though as per [Best practices](@ref) do not edit after simulations are created that rely on it). + +To vary parameters in this XML file, the [`icECMPath`](@ref) function can be used. +The signature is as follows: + +```julia +icECMPath(, , , ) +``` + +Or in the case of using a patch type `""ellipse_with_shell""` there are additional parameters for the two (or three) subpatches: +```julia +icECMPath(, ""ellipse_with_shell"", , , ) +``` +where `` is one of `""interior""`, `""shell""`, or `""exterior""`.","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/project_configuration.md",".md","2109","40","# Project configuration + +The `inputs.toml` file is used to configure the inputs for the project. +It is located in the `inputs` directory within the project data directory. + +## TOML-defined structure +Each section of the `inputs.toml` file defines one of the input ""locations"" in the project. +An example of the structure is as follows: + +```toml +[config] +required = true +varied = true +basename = ""PhysiCell_settings.xml"" +``` + +Upon initialization of the model manager, i.e., calling `using PhysiCellModelManager` (or [`initializeModelManager`](@ref)), the `inputs.toml` file is parsed and each entry (`config` is shown above) has four features stored: +- `required`: A boolean indicating if the location is required for the model to run. +- `basename`: The base name of the file to be used for the location. +- `varied`: A boolean indicating if the location can vary between different model runs. +- `path_from_inputs`: The path to the location relative to the `inputs` directory. + +### `required` +This field is necessary and must either be `true` or `false`. +If `true`, an `InputsFolder` object cannot be created without this location. + +### `basename` +This field enforces the name of the file to be used for the location. +A vector can be supplied of names in the order to look for the files in cases when multiple files are acceptable. +This field is necessary if `varied` is `true`, but can be omitted if `varied` is `false`. + +### `varied` +This field is necessary and must either be `true`, `false`, or a vector of Booleans matching the length of the `basename` vector. +If `true`, the location can be varied and the necessary databases and folders are created to support this. + +### `path_from_inputs` +This optional field sets the path to the location relative to the `inputs` directory. +If not provided, the path is assumed to be `inputs/s`. +For example, the `config` section above would be located at `inputs/configs` (note the pluralization of the section name). +To provide this path, use a vector of strings, e.g., `[""ics"", ""cells""]` to define the path to the `[ic_cell]` location as `inputs/ics/cells`.","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/best_practices.md",".md","2121","30","# Best practices + +## Do NOT manually edit files inside `inputs`. +If parameter values need to be changed, use variations as shown in `scripts/GenerateData.jl`. +Let PhysiCellModelManager.jl manage the databases that track simulation parameters. + +If you need to change the structure of an input file, e.g., adding a new rule or editing custom code, create an entire new subdirectory within the relevant `inputs` subdirectory. +If you anticipate doing a lot of this, consider using PhysiCell Studio for your first round of model development and refinement. + +# Suggested practices + +## Use [`createProject`](@ref) to create a new PCMM project. +[`createProject`](@ref) will create a new PCMM project directory with the necessary structure and files. +*Note: This is a distinct folder from a PhysiCell sample project or user project.* +If you do not want the template PhysiCell project copied over, use the keyword argument `template_as_default=false`, i.e., +```julia-repl +createProject(""MyNewProject""; template_as_default=false) +``` + +## Be slow to delete simulations and scripts. +PhysiCellModelManager.jl tracks simulations in a database so that it does not have to re-run simulations that have already been run. +This means that adding new simulations to a script and re-running the entire script, including on an HPC, will not run extraneous simulations. +Thus, the script can serve as a record of the simulations that have been run, and can be used to reproduce the results at a later date. + +If you do need to manually delete simulations--for example, because of an error that prevented the simulation entry in the database updating its record--use the [`deleteSimulations`](@ref) function to ensure that the database is updated appropriately. + +## Use version control on `inputs` and `scripts` directories. +Alone, these two directories along with the version of PhysiCell can be used to reproduce the results of a project. +The `createProject` function will create a `.gitignore` file in the data directory to make sure the appropriate files are tracked. +","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/sensitivity_analysis.md",".md","9301","144","# Sensitivity analysis + +PhysiCellModelManager.jl supports some sensitivity analysis workflows. +By using PhysiCellModelManager.jl, you will have the opportunity to readily reuse previous simulations to perform and extend sensitivity analyses. + +## Supported sensitivity analysis methods +PhysiCellModelManager.jl currently supports three sensitivity analysis methods: +- Morris One-At-A-Time (MOAT) +- Sobol' +- Random Balance Design (RBD) + +### Morris One-At-A-Time (MOAT) +The Morris One-At-A-Time (MOAT) method gives an intuitive understanding of the sensitivity of a model to its parameters. +What it lacks in theoretical grounding, it makes up for in speed and ease of use. +In short, MOAT will sample parameter space at `n` points. +From each point, it will vary each parameter one at a time and record the change in model output. +Aggregating these changes, MOAT will quantify the sensitivity of the model to each parameter. + +`MOAT` uses a Latin Hypercube Sampling (LHS) to sample the parameter space. +By default, it will use the centerpoint of each bin as the point to vary each parameter from. +To pick a random point within the bin, set `add_noise=true`. + +`MOAT` furthermore uses an orthogonal LHS, if possible. +If `n=k^d` for some integer `k`, then the LHS will be orthogonal. +Here, `n` is the requested number of base points and `d` is the number of parameters varied. +For example, if `n=16` and `d=4`, then `k=2` and the LHS will be orthogonal. +To force PhysiCellModelManager.jl to NOT use an orthogonal LHS, set `orthogonalize=false`. + +To use the MOAT method, any of the following signatures can be used: +```julia +MOAT() # will default to n=15 +MOAT(8) # set n=8 +MOAT(8; add_noise=true) # use a random point in the bin, not necessarily the center +MOAT(8; orthogonalize=false) # do not use an orthogonal LHS (even if d=3, so k=2 would make an orthogonal LHS) +``` + +### Sobol' +The Sobol' method is a more rigorous sensitivity analysis method, relying on the variance of the model output to quantify sensitivity. +It relies on a Sobol' sequence, a deterministic sequence of points that are evenly distributed in the unit hypercube. +The important main feature of the Sobol' sequence is that it is a _low-discrepancy_ sequence, meaning that it fills the space very evenly. +Thus, using such sequences can give a very good approximation of certain quantities (like integrals) with fewer points than a random sequence would require. +The Sobol' sequence is built around powers of 2, and so picking `n=2^k` (as well as ±1) will give the best results. +See [`SobolVariation`](@ref) for more information on how PhysiCellModelManager.jl will use the Sobol' sequence to sample the parameter space and how you can control it. + +If the extremes of your distributions (where the CDF is 0 or 1) are non-physical, e.g., an unbounded normal distribution, then consider using `n=2^k-1` to pick a subsequence that does not include the extremes. +For example, if you choose `n=7`, then the Sobol' sequence will be `[0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875]`. +If you do want to include the extremes, consider using `n=2^k+1`. +For example, if you choose `n=9`, then the Sobol' sequence will be `[0, 0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875, 1]`. + +You can also choose which method is used to compute the first and total order Sobol' indices. +For first order: the choices are `:Sobol1993`, `:Jansen1999`, and `:Saltelli2010`. Default is `:Jansen1999`. +For total order: the choices are `:Homma1996`, `:Jansen1999`, and `:Sobol2007`. Default is `:Jansen1999`. + +To use the Sobol' method, any of the following signatures can be used: +```julia +Sobolʼ(9) +Sobolʼ(9; skip_start=true) # skip to the odd multiples of 1/32 (smallest one with at least 9) +``` + +The rasp symbol is used to avoid conflict with the Sobol module. +To type it in VS Code, use `\\rasp` and then press `tab`. +Alternatively, the constructor [`SobolPCMM`](@ref) is provided as an alias for convenience. + +### Random Balance Design (RBD) +The RBD method uses a random design matrix (similar to the Sobol' method) and uses a Fourier transform (as in in the FAST method) to compute the sensitivity indices. +It is much cheaper than Sobol', but only gives first order indices. +Choosing `n` design points, RBD will run `n` monads. +It will then rearrange the `n` output values so that each parameter in turn is varied along a sinusoid and computes the Fourier transforms to estimate the first order indices. +By default, it looks up to the 6th harmonic, but you can control this with the `num_harmonics` keyword argument. + +By default, PhysiCellModelManager.jl will make use of the Sobol' sequence to pick the design points. +It is best to pick `n` such that is differs from a power of 2 by at most 1, e.g. 7, 8, or 9. +In this case, PhysiCellModelManager.jl will actually use a half-period of a sinusoid when converting the design points into CDF space. +Otherwise, PhysiCellModelManager.jl will use random permuations of `n` uniformly spaced points in each parameter dimension and will use a full period of a sinusoid when converting the design points into CDF space. + +To use the RBD method, any of the following signatures can be used: +```julia +RBD(9) # will use a Sobol' sequence with elements chosen from 0:0.125:1 +RBD(32; use_sobol=false) # opt out of using the Sobol' sequence +RBD(22) # will use the first 22 elements of the Sobol' sequence, including 0 +RBD(32; num_harmonics=4) # will look up to the 4th harmonic, instead of the default 6th +``` + +If you choose `n=2^k - 1` or `n=2^k + 1`, then you will be well-positioned to increment `k` by one and rerun the RBD method to get more accurate results. +The reason: PhysiCellModelManager.jl will start from the start of the Sobol' sequence to cover these `n` points, meaning runs will not need to be repeated. +If `n=2^k`, then PhysiCellModelManager.jl will choose the `n` odd multiples of `1/2^(k+1)` from the Sobol' sequence, which will not be used if `k` is incremented. + +## Setting up a sensitivity analysis + +### Simulation inputs +Having chosen a sensitivity analysis method, you must now choose the same set of inputs as required for a sampling. You will need: +- `inputs::InputFolders` containing the `data/inputs/` folder info defining your model +- `evs::Vector{<:ElementaryVariation}` to define the parameters to conduct the sensitivity analysis on and their ranges/distributions + +Unlike for (most) trials, the `ElementaryVariation`'s you will want here are likely to be [`DistributedVariation`](@ref)'s to allow for a continuum of parameter values to be tested. +PhysiCellModelManager.jl offers [`UniformDistributedVariation`](@ref) and [`NormalDistributedVariation`](@ref) as convenience functions to create these `DistributedVariation`'s. +You can also use any `d::Distribution` to create a `DistributedVariation` directly: +```julia +dv = DistributedVariation(xml_path, d) +``` + +Currently, PhysiCellModelManager.jl only supports [`CoVariation`](@ref)s to correlate parameters in a sensitivity analysis. + +### Sensitivity functions +At the time of starting the sensitivity analysis, you can include any number of sensitivity functions to compute. +They must take a single argument, the simulation ID (an `Int64`) and return a `Number` (or any type that `Statistics.mean` will accept a `Vector` of). +For example, `finalPopulationCount` returns a dictionary of the final population counts of each cell type from a simulation ID. +So, if you want to know the sensitivity of the final population count of cell type ""cancer"", you could define a function like: +```julia +f(sim_id) = finalPopulationCount(sim_id)[""cancer""] +``` + +## Running the analysis +Putting it all together, you can run this analysis: +```julia +config_folder = ""default"" +custom_codes = ""default"" +inputs = InputFolders(config_folder, custom_codes) +n_replicates = 3 +evs = [NormalDistributedVariation(configPath(""cancer"", ""apoptosis"", ""rate""), 1e-3, 1e-4; lb=0), + UniformDistributedVariation(configPath(""cancer"", ""cycle"", ""duration"", 0), 720, 2880)] +method = MOAT(15) +sensitivity_sampling = run(method, inputs, evs; n_replicates=n_replicates) +``` + +## Post-processing +The object `sensitivity_sampling` is of type [`PhysiCellModelManager.GSASampling`](@ref), meaning you can use [`PhysiCellModelManager.calculateGSA!`](@ref) to compute sensitivity analyses. +```julia +f = simulation_id -> finalPopulationCount(simulation_id)[""default""] # count the final population of cell type ""default"" +calculateGSA!(sensitivity_sampling, f) +``` +These results are stored in a `Dict` in the `sensitivity_sampling` object: +```julia +println(sensitivity_sampling.results[f]) +``` + +The exact concrete type of `sensitivity_sampling` will depend on the `method` used. +This, in turn, is used by `calculateGSA!` to determine how to compute the sensitivity indices. + +Likewise, the `method` will determine how the sensitivity scheme is saved. +After running the simulations, PhysiCellModelManager.jl will print a CSV in the `data/outputs/sampling/$(sampling)` folder named based on the `method`. +This can later be used to reload the `GSASampling` and continue doing analysis. +The simplest way to do that in a new Julia session is to re-run the code that generated the `GSASampling` object. +So long as the `use_previous` keyword argument is set to `true`, the previous results will be reused.","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/covariations.md",".md","4257","65","# CoVariations +Sometimes several parameters need to be varied together. +A common use case is the varying the base value of a rule and the max response of the rule[^1] +To handle this scenario, PhysiCellModelManager.jl provides the `CoVariation` type. +A `CoVariation` is a wrapper for a vector of `ElementaryVariation`'s, and each `ElementaryVariation` must be of the same type, i.e., all `DiscreteVariation`'s or all `DistributedVariation`'s. +The type of a `CoVariation` is parameterized by the type of `ElementaryVariation`'s it contains. +Thus, there are, for now, two types of `CoVariation`'s: `CoVariation{DiscreteVariation}` and `CoVariation{DistributedVariation}`. + +[^1]: PhysiCell does not allow the base value to exceed the max response. That is, the base response of a decreasing signal cannot be < the max response. Similarly, the base resposne of an increasing signal cannot be > the max response. + +## `CoVariation{DiscreteVariation}` +For a `CoVariation{DiscreteVariation}`, each of the `DiscreteVariation`'s must have the same number of values. +This may be relaxed in future versions, but the primary use case anticipated is a [`GridVariation`](@ref) which requires the variations to inform the size of the grid. +No restrictions are imposed on how the values of the various variations are linked. +PhysiCellModelManager.jl will use values that share an index in their respective vectors together. + +```julia +base_xml_path = configPath(""default"", ""custom:sample"") +ev1 = DiscreteVariation(base_xml_path, [1, 2, 3]) # vary the `sample` custom data for cell type default +max_xml_path = rulePath(""default"", ""custom:sample"", ""increasing_signals"", ""max_response"") # the max response of the rule increasing sample (must be bigger than the base response above) +ev2 = DiscreteVariation(rule_xml_path, [2, 3, 4]) +covariation = CoVariation(ev1, ev2) # CoVariation([ev1, ev2]) also works +``` + +It is also not necessary to create the `ElementaryVariation`'s separately and then pass them to the `CoVariation` constructor. +```julia +# have the phase durations vary and compensate for each other +phase_0_xml_path = configPath(""default"", ""cycle"", ""duration"", 0) +phase_1_xml_path = configPath(""default"", ""cycle"", ""duration"", 1) +phase_0_durations = [300.0, 400.0] +phase_1_durations = [200.0, 100.0] # the (mean) duration through these two phases is 500 min +# input any number of tuples (xml_path, values) +covariation = CoVariation((phase_0_xml_path, phase_0_durations), (phase_1_xml_path, phase_1_durations)) +``` + +## `CoVariation{DistributedVariation}` +For a `CoVariation{DistributedVariation}`, the conversion of a CDF value, $x \in [0, 1]$, is done independently for each distribution. +That is, in the joint probability space, a `CoVariation{DistributedVariation}` restricts us to the one-dimensional line connecting $\mathbf{0}$ to $\mathbf{1}$. +To allow for the parameters to vary inversely with one another, the `DistributedVariation` type accepts an optional keyword argument: `flip::Bool`. +For a distribution `dv` with `dv.flip=true`, when a value is requested with a CDF $x$, PhysiCellModelManager.jl will ""flip"" the CDF to give the value with CDF $1 - x$. + +```jldoctest +using PhysiCellModelManager +timing_1_path = configPath(""user_parameters"", ""event_1_time"") +timing_2_path = configPath(""user_parameters"", ""event_2_time"") +dv1 = UniformDistributedVariation(timing_1_path, 100.0, 200.0) +dv2 = UniformDistributedVariation(timing_2_path, 100.0, 200.0; flip=true) +covariation = CoVariation(dv1, dv2) +cdf = 0.1 +PhysiCellModelManager.variationValues.(covariation.variations, cdf) # PhysiCellModelManager.jl internal for getting values for an ElementaryVariation +# output +2-element Vector{Vector{Float64}}: + [110.0] + [190.0] +``` + +As with `CoVariation{DiscreteVariation}`, it is not necessary to create the `ElementaryVariation`'s separately and then pass them to the `CoVariation` constructor. It is not possible to `flip` a `DistributedVariation` with this syntax, however. + +```julia +apop_xml_path = configPath(""default"", ""apoptosis"", ""death_rate"") +apop_dist = Uniform(0, 0.001) +cycle_entry_path = configPath(""default"", ""cycle"", ""rate"", 0) +cycle_dist = Uniform(0.00001, 0.0001) +covariation = CoVariation((apop_xml_path, apop_dist), (cycle_entry_path, cycle_dist)) +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/man/known_limitations.md",".md","613","10","# Known limitations +## Always select all simulations associated with a `Monad` +Anytime a group of simulation replicates (a `Monad` in PhysiCellModelManager.jl internals) is requested, all simulations in that group are used, regardless of the value of `n_replicates`. + +## Initial conditions not loaded when launching PhysiCell Studio for a simulation. +When launching PhysiCell Studio from PhysiCellModelManager.jl, the initial conditions (cells and substrates) are not loaded. + +## Limited intracellular models +Currently only supports ODE intracellular models (using libRoadRunner). +Does not support MaBoSS or dFBA.","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/misc/database_upgrades.md",".md","2990","41","# Database upgrades +Over time, the database structure of PhysiCellModelManager.jl will evolve to reflect new capabilities, features, and improvements. +Not every release will change the database structure, but when one does in a way that could affect your workflow, PhysiCellModelManager.jl will throw a warning. +The warning will link to this page and the function will wait for user input to proceed. +Changes are listed in reverse chronological order. + +## to v0.2.0 +Add a unique column to each variations database (e.g. `config_variations.db`) to replace the previous index that tracked all parameter values. This makes the check of parameter uniqueness robust to more columns. + +## to v0.1.3 +Rename the database file from `pcvct.db` to `pcmm.db` to reflect the name change of the package. + +## to v0.0.30 +The `pcvct_version` table is renamed to `pcmm_version` due to the name change of the package. +Also, check any environment variables you have set, e.g., in the `~/.zshrc` or `~/.bashrc` files, and update them to reflect the new package name. +Any that were prefixed with `PCVCT_` should now be prefixed with `PCMM_`. + +## to v0.0.29 +The `inputs.toml` file has been moved from `data/` to `data/inputs/`. + +## to v0.0.15 +Introduce XML-based ECM initial conditions. This introduces `ic_ecm_variations`. +Also, introduce Dirichlet initial conditions from file, which introduces the `ic_dc_id` in the database. +For any simulations in the database before upgrading, both of these will be set to `-1` (i.e., no initial conditions) except if `ic_ecm_id` is not `-1`, in which case `ic_ecm_variation_id` will be set to `0` (i.e., the default ECM initial conditions which is all the original CSV version can handle). + +## to v0.0.10 +Start tracking the PhysiCell version used in the simulation. +This introduces the `physicell_versions` table which tracks the PhysiCell versions used in simulations. +Currently, only supports reading the PhysiCell version, not setting it (e.g., through git commands). +Key changes include: +- Adding the `physicell_version_id` column to the `simulations`, `monads`, and `samplings` tables. +- Adding the `physicell_versions` table. + - If `PhysiCell` is a git-tracked repo, this will store the commit hash as well as any tag and repo owner it can find based on the remotes. It will also store the date of the commit. + - If `PhysiCell` is not a git-tracked repo, it will read the `VERSION.txt` file and store that as the `commit_hash` with `-download` appended to the version. + +## to v0.0.3 +Introduce XML-based cell initial conditions. This introduces `ic_cell_variations`. +Also, standardized the use of `config_variation` in place of `variation`. Key changes include: +- Renaming the `variation_id` column in the `simulations` and `monads` tables to `config_variation_id`. +- Adding the `ic_cell_variation_id` column to the `simulations` and `monads` tables. +- In `data/inputs/configs`, renaming all instances of ""variation"" to ""config_variation"" in filenames and databases.","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/variations.md",".md","302","21","```@meta +CollapsedDocStrings = true +``` + +# Variations + +Vary parameters of the project. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""variations.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""variations.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/utilities.md",".md","286","21","```@meta +CollapsedDocStrings = true +``` + +# Utilities + +Utility functions. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""utilities.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""utilities.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/user_api.md",".md","356","21","```@meta +CollapsedDocStrings = true +``` + +# User API + +Main functions users will use to create and run simulations, monads, samplings, and trials. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""user_api.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""user_api.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/deletion.md",".md","328","23","```@meta +CollapsedDocStrings = true +``` + +# Deletion + +Safely delete output from a PhysiCellModelManager.jl project. + +## Public API + +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""deletion.jl""] +Private = false +``` + +## Private API + +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""deletion.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/movie.md",".md","300","21","```@meta +CollapsedDocStrings = true +``` + +# Movie + +Make movies for simulations in the database. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""movie.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""movie.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/PhysiCellModelManager.md",".md","335","21","```@meta +CollapsedDocStrings = true +``` + +# Core + +Core functionality for PhysiCellModelManager.jl. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""PhysiCellModelManager.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""PhysiCellModelManager.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/ic_cell.md",".md","436","21","```@meta +CollapsedDocStrings = true +``` + +# Cell Initial Conditions + +Functionality for the using [PhysiCellCellCreator.jl](https://github.com/drbergman-lab/PhysiCellCellCreator.jl) to create and use PhysiCell IC cell XML files. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""ic_cell.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""ic_cell.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/sensitivity.md",".md","310","21","```@meta +CollapsedDocStrings = true +``` + +# Sensitivity + +Run sensitivity analyses on a model. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""sensitivity.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""sensitivity.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/database.md",".md","321","21","```@meta +CollapsedDocStrings = true +``` + +# Database + +Create and manage the PhysiCellModelManager.jl database. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""database.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""database.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/physicell_studio.md",".md","362","21","```@meta +CollapsedDocStrings = true +``` + +# PhysiCell Studio + +Launch PhysiCell Studio for a simulation run in PhysiCellModelManager.jl. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""physicell_studio.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""physicell_studio.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/components.md",".md","414","23","```@meta +CollapsedDocStrings = true +``` + +# Components + +Allows for combining PhysiCell input components into whole inputs. + +Currently, only supports this for intracellular ODE (libRoadRunner) models. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""components.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""components.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/compilation.md",".md","426","21","```@meta +CollapsedDocStrings = true +``` + +# Compilation + +Compile a PhysiCell project in PCMM. Includes the necessary compiler macros and checks PhysiCell version by the commit hash of the PhysiCell repository. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""compilation.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""compilation.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/export.md",".md","343","21","```@meta +CollapsedDocStrings = true +``` + +# Export + +This file holds the functions for exporting a simulation to a `user_project` format. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""export.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""export.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/hpc.md",".md","289","21","```@meta +CollapsedDocStrings = true +``` + +# HPC + +Run PhysiCellModelManager.jl on an HPC. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""hpc.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""hpc.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/runner.md",".md","348","21","```@meta +CollapsedDocStrings = true +``` + +# Runner + +Run simulations, monads, samplings, and trials in the PhysiCellModelManager.jl framework. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""runner.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""runner.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/import.md",".md","391","21","```@meta +CollapsedDocStrings = true +``` + +# Import + +Import a project from the standard PhysiCell format (`sample_projects` or `user_projects`) into the PhysiCellModelManager.jl format. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""import.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""import.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/loader.md",".md","416","22","```@meta +CollapsedDocStrings = true +``` + +# Loader + +Load PhysiCell data into useful forms for downstream analysis. +This may be split off into its own module or even package eventually, likely with analysis.jl. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""loader.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""loader.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/globals.md",".md","310","21","```@meta +CollapsedDocStrings = true +``` + +# Globals + +Global variables used in PhysiCellModelManager. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""globals.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""globals.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/deprecate_keywords.md",".md","479","21","```@meta +CollapsedDocStrings = true +``` + +# Deprecate Keywords + +A light edit of the [DeprecateKeywords.jl](https://github.com/MilesCranmer/DeprecateKeywords.jl) package to enable the deprecation warnings for users. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager.DeprecateKeywords] +Pages = [""DeprecateKeywords.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager.DeprecateKeywords] +Pages = [""DeprecateKeywords.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/analysis.md",".md","599","23","```@meta +CollapsedDocStrings = true +``` + +# Analysis + +Analyze output from a PCMM project. +It is anticipated that this will eventually be split off into its own module or even package. +Possibly with loader.jl. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""graphs.jl"", ""motility.jl"", ""pcf.jl"", ""population.jl"", ""preprocessing.jl"", ""runtime.jl"", ""substrate.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""graphs.jl"", ""motility.jl"", ""pcf.jl"", ""population.jl"", ""preprocessing.jl"", ""runtime.jl"", ""substrate.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/up.md",".md","375","21","```@meta +CollapsedDocStrings = true +``` + +# PhysiCellModelManager.jl Upgrade + +Functionality for upgrading the database to match the current version of PhysiCellModelManager.jl. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""up.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""up.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/pruner.md",".md","1055","23","```@meta +CollapsedDocStrings = true +``` + +# Pruner + +Prune files from a simulation immediately after finishing the simulation. + +To motivate this functionality, consider the following scenario. A user has been testing their model, including making movies, and is ready to do a large simulation campaign with thousands of simulations. Saving all the SVGs will require gigabytes of storage, which is not ideal for the user. The user could choose to create a new variation on the SVG parameters (e.g., increase the SVG save interval), but then PhysiCellModelManager.jl will not be able to reuse previous simulations as they have different variation IDs. Alternatively, the user can use the `PruneOptions` to delete the SVGs after each simulation is finished. This way, there are fewer variations in the database and more capability to reuse simulations. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""pruner.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""pruner.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/ic_ecm.md",".md","427","21","```@meta +CollapsedDocStrings = true +``` + +# ECM Initial Conditions + +Functionality for the using [PhysiCellECMCreator.jl](https://github.com/drbergman-lab/PhysiCellECMCreator.jl) to create and use PhysiCell ECM XML files. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""ic_ecm.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""ic_ecm.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/classes.md",".md","312","23","```@meta +CollapsedDocStrings = true +``` + +# Classes + +Class definitions for the hierarchical structure connecting simulations to trials. + +## Public API +```@docs +InputFolders +Simulation +Monad +Sampling +Trial +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""classes.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/physicell_version.md",".md","341","21","```@meta +CollapsedDocStrings = true +``` + +# PhysiCell Version + +Manage the PhysiCell version used in the project. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""physicell_version.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""physicell_version.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/pcmm_version.md",".md","360","21","```@meta +CollapsedDocStrings = true +``` + +# PhysiCellModelManager.jl Version + +Manage the version of PhysiCellModelManager.jl in the database. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""pcmm_version.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""pcmm_version.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/configuration.md",".md","7497","136","```@meta +CollapsedDocStrings = true +``` + +# Configuration + +Interface with the configuration file necessary for PhysiCell simulations. + +Provide functionality for accessing and modifying elements in any XML, including the PhysiCell configuration file, XML rules file, combined intracellular XML file, XML IC cell file, and XML IC ECM file. + +## Config XML paths +The [`configPath`](@ref) is the most user-friendly way to create the XML path to (most) any parameter in the configuration file. +The following functions are called by `configPath` and are more explicit and rigid. +Note, none of these are exported and so they must be called with the `PhysiCellModelManager.` prefix, e.g., `PhysiCellModelManager.domainPath(""x_min"")`. + +| | | | | +|--------------------------------------|----------------------------------|--------------------------------------------------|-----------------------------------| +| [`domainPath`](@ref PhysiCellModelManager.domainPath) | [`timePath`](@ref PhysiCellModelManager.timePath) | [`fullSavePath`](@ref PhysiCellModelManager.fullSavePath) | [`svgSavePath`](@ref PhysiCellModelManager.svgSavePath) | +| [`substratePath`](@ref PhysiCellModelManager.substratePath) | [`cyclePath`](@ref PhysiCellModelManager.cyclePath) | [`apoptosisPath`](@ref PhysiCellModelManager.apoptosisPath) | [`necrosisPath`](@ref PhysiCellModelManager.necrosisPath) | +| [`volumePath`](@ref PhysiCellModelManager.volumePath) | [`mechanicsPath`](@ref PhysiCellModelManager.mechanicsPath) | [`motilityPath`](@ref PhysiCellModelManager.motilityPath) | [`secretionPath`](@ref PhysiCellModelManager.secretionPath) | +| [`cellInteractionsPath`](@ref PhysiCellModelManager.cellInteractionsPath) | [`phagocytosisPath`](@ref PhysiCellModelManager.phagocytosisPath) | [`attackRatePath`](@ref PhysiCellModelManager.attackRatePath) | [`fusionPath`](@ref PhysiCellModelManager.fusionPath) | +| [`integrityPath`](@ref PhysiCellModelManager.integrityPath) | [`customDataPath`](@ref PhysiCellModelManager.customDataPath) | [`initialParameterDistributionPath`](@ref PhysiCellModelManager.initialParameterDistributionPath) | [`userParameterPath`](@ref PhysiCellModelManager.userParameterPath) | + +Here is a near-exhaustive list of the available tokens (the flexibiilty of `configPath` allows for some of these XML paths to be created in multiple ways): + +### Single tokens +The following can be passed in alone to `configPath`: +```julia +- ""x_min"", ""x_max"", ""y_min"", ""y_max"", ""z_min"", ""z_max"", ""dx"", ""dy"", ""dz"", ""use_2D"" (`domainPath`) +- ""max_time"", ""dt_intracellular"", ""dt_diffusion"", ""dt_mechanics"", ""dt_phenotype"" (`timePath`) +- ""full_data_interval"" (`fullSavePath`) +- ""SVG_save_interval"" (`svgSavePath`) +``` + +### Double tokens +The following can be passed in as the second argument to `configPath(, )` where `` is the name of the substrate in your model: +```julia +- ""diffusion_coefficient"", ""decay_rate"" +- ""initial_condition"", ""Dirichlet_boundary_condition"" +- ""xmin"", ""xmax"", ""ymin"", ""ymax"", ""zmin"", ""zmax"" +``` + +The following can be passed in as the second argument to `configPath(, )` where `` is the name of the cell type in your model: +```julia +- ""total"", ""fluid_fraction"", ""nuclear"", ""fluid_change_rate"", ""cytoplasmic_biomass_change_rate"", ""nuclear_biomass_change_rate"", ""calcified_fraction"", ""calcification_rate"", ""relative_rupture_volume"" (`volumePath`) +- ""cell_cell_adhesion_strength"", ""cell_cell_repulsion_strength"", ""relative_maximum_adhesion_distance"", ""attachment_elastic_constant"", ""attachment_rate"", ""detachment_rate"", ""maximum_number_of_attachments"" (`mechanicsPath`) +- ""set_relative_equilibrium_distance"", ""set_absolute_equilibrium_distance"" (`mechanicsPath`) +- ""speed"", ""persistence_time"", ""migration_bias"" (`motilityPath`) +- ""apoptotic_phagocytosis_rate"", ""necrotic_phagocytosis_rate"", ""other_dead_phagocytosis_rate"", ""attack_damage_rate"", ""attack_duration"" (`cellInteractionsPath`) +- ""damage_rate"", ""damage_repair_rate"" (`integrityPath`) +- ""custom:"" (`customDataPath`) +``` + +Finally, for a user parameter you can use the following: +```julia +configPath(""user_parameters"", ) +``` +where `` is the name of the user parameter in your model. + +### Triple tokens +The following can be passed in as the third argument to `configPath(, ""Dirichlet_options"", )` where `` is the name of the substrate in your model: +```julia +- ""xmin"", ""xmax"", ""ymin"", ""ymax"", ""zmin"", ""zmax"" (`substratePath`) +``` + +The following tokens work with a `cell_type` from your model: +```julia +- `configPath(, ""cycle_rate"", )` (`cyclePath`) +- `configPath(, ""cycle_duration"", )` (`cyclePath`) +- `configPath(, ""apoptosis"", )` (`apoptosisPath`) +- `configPath(, ""necrosis"", )` (`necrosisPath`) +- `configPath(, ""adhesion"", )` (`mechanicsPath`) +- `configPath(, ""motility"", )` (`motilityPath`) +- `configPath(, ""chemotaxis"", )` (`motilityPath`) +- `configPath(, ""advanced_chemotaxis"", )` (`motilityPath`) +- `configPath(, ""advanced_chemotaxis"", )` (`motilityPath`) +- `configPath(, , )` (`secretionPath`) +- `configPath(, , )` (`` is one of ""phagocytosis"", ""fusion"", ""transformation"", ""attack_rate"") (`cellInteractionsPath`) +- `configPath(, ""custom"", )` (`customDataPath`) +``` + +### Four tokens +The following tokens work with a `cell_type` from your model: +```julia +- `configPath(, ""cycle"", ""duration"", )` (`cyclePath`) +- `configPath(, ""cycle"", ""rate"", )` (`cyclePath`) +- `configPath(, ""necrosis"", ""duration"", )` (`necrosisPath`) +- `configPath(, ""necrosis"", ""transition_rate"", )` (`necrosisPath`) +- `configPath(, ""initial_parameter_distribution"", , )` (`initialParameterDistributionPath`) +``` + +## Main XML path functions +```@docs; canonical=false +configPath +rulePath +icCellsPath +icECMPath +``` + +## Config file specific functions +```@docs; canonical=false +PhysiCellModelManager.domainPath +PhysiCellModelManager.timePath +PhysiCellModelManager.fullSavePath +PhysiCellModelManager.svgSavePath +PhysiCellModelManager.substratePath +PhysiCellModelManager.cyclePath +PhysiCellModelManager.apoptosisPath +PhysiCellModelManager.necrosisPath +PhysiCellModelManager.volumePath +PhysiCellModelManager.mechanicsPath +PhysiCellModelManager.motilityPath +PhysiCellModelManager.secretionPath +PhysiCellModelManager.cellInteractionsPath +PhysiCellModelManager.phagocytosisPath +PhysiCellModelManager.attackRatePath +PhysiCellModelManager.fusionPath +PhysiCellModelManager.integrityPath +PhysiCellModelManager.customDataPath +PhysiCellModelManager.initialParameterDistributionPath +PhysiCellModelManager.userParameterPath +``` + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""configuration.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""configuration.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/recorder.md",".md","348","21","```@meta +CollapsedDocStrings = true +``` + +# Recorder + +Functionality for recording constituent IDs of `Monad`s, `Sampling`s, and `Trial`s. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""recorder.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""recorder.jl""] +Public = false +```","Markdown" +"Substrate","drbergman-lab/PhysiCellModelManager.jl","docs/src/lib/creation.md",".md","311","21","```@meta +CollapsedDocStrings = true +``` + +# Creation + +Create a new PhysiCellModelManager.jl project. + +## Public API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""creation.jl""] +Private = false +``` + +## Private API +```@autodocs +Modules = [PhysiCellModelManager] +Pages = [""creation.jl""] +Public = false +```","Markdown"